PackageManagerService.java revision 28ec27cbfa157c242fd9330a10c7c2b8ea838694
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 = false;
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    @Override
3199    public String getPermissionControllerPackageName() {
3200        synchronized (mPackages) {
3201            return mRequiredInstallerPackage;
3202        }
3203    }
3204
3205    /**
3206     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3207     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3208     * @param checkShell TODO(yamasani):
3209     * @param message the message to log on security exception
3210     */
3211    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3212            boolean checkShell, String message) {
3213        if (userId < 0) {
3214            throw new IllegalArgumentException("Invalid userId " + userId);
3215        }
3216        if (checkShell) {
3217            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3218        }
3219        if (userId == UserHandle.getUserId(callingUid)) return;
3220        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3221            if (requireFullPermission) {
3222                mContext.enforceCallingOrSelfPermission(
3223                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3224            } else {
3225                try {
3226                    mContext.enforceCallingOrSelfPermission(
3227                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3228                } catch (SecurityException se) {
3229                    mContext.enforceCallingOrSelfPermission(
3230                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3231                }
3232            }
3233        }
3234    }
3235
3236    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3237        if (callingUid == Process.SHELL_UID) {
3238            if (userHandle >= 0
3239                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3240                throw new SecurityException("Shell does not have permission to access user "
3241                        + userHandle);
3242            } else if (userHandle < 0) {
3243                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3244                        + Debug.getCallers(3));
3245            }
3246        }
3247    }
3248
3249    private BasePermission findPermissionTreeLP(String permName) {
3250        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3251            if (permName.startsWith(bp.name) &&
3252                    permName.length() > bp.name.length() &&
3253                    permName.charAt(bp.name.length()) == '.') {
3254                return bp;
3255            }
3256        }
3257        return null;
3258    }
3259
3260    private BasePermission checkPermissionTreeLP(String permName) {
3261        if (permName != null) {
3262            BasePermission bp = findPermissionTreeLP(permName);
3263            if (bp != null) {
3264                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3265                    return bp;
3266                }
3267                throw new SecurityException("Calling uid "
3268                        + Binder.getCallingUid()
3269                        + " is not allowed to add to permission tree "
3270                        + bp.name + " owned by uid " + bp.uid);
3271            }
3272        }
3273        throw new SecurityException("No permission tree found for " + permName);
3274    }
3275
3276    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3277        if (s1 == null) {
3278            return s2 == null;
3279        }
3280        if (s2 == null) {
3281            return false;
3282        }
3283        if (s1.getClass() != s2.getClass()) {
3284            return false;
3285        }
3286        return s1.equals(s2);
3287    }
3288
3289    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3290        if (pi1.icon != pi2.icon) return false;
3291        if (pi1.logo != pi2.logo) return false;
3292        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3293        if (!compareStrings(pi1.name, pi2.name)) return false;
3294        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3295        // We'll take care of setting this one.
3296        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3297        // These are not currently stored in settings.
3298        //if (!compareStrings(pi1.group, pi2.group)) return false;
3299        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3300        //if (pi1.labelRes != pi2.labelRes) return false;
3301        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3302        return true;
3303    }
3304
3305    int permissionInfoFootprint(PermissionInfo info) {
3306        int size = info.name.length();
3307        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3308        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3309        return size;
3310    }
3311
3312    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3313        int size = 0;
3314        for (BasePermission perm : mSettings.mPermissions.values()) {
3315            if (perm.uid == tree.uid) {
3316                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3317            }
3318        }
3319        return size;
3320    }
3321
3322    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3323        // We calculate the max size of permissions defined by this uid and throw
3324        // if that plus the size of 'info' would exceed our stated maximum.
3325        if (tree.uid != Process.SYSTEM_UID) {
3326            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3327            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3328                throw new SecurityException("Permission tree size cap exceeded");
3329            }
3330        }
3331    }
3332
3333    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3334        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3335            throw new SecurityException("Label must be specified in permission");
3336        }
3337        BasePermission tree = checkPermissionTreeLP(info.name);
3338        BasePermission bp = mSettings.mPermissions.get(info.name);
3339        boolean added = bp == null;
3340        boolean changed = true;
3341        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3342        if (added) {
3343            enforcePermissionCapLocked(info, tree);
3344            bp = new BasePermission(info.name, tree.sourcePackage,
3345                    BasePermission.TYPE_DYNAMIC);
3346        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3347            throw new SecurityException(
3348                    "Not allowed to modify non-dynamic permission "
3349                    + info.name);
3350        } else {
3351            if (bp.protectionLevel == fixedLevel
3352                    && bp.perm.owner.equals(tree.perm.owner)
3353                    && bp.uid == tree.uid
3354                    && comparePermissionInfos(bp.perm.info, info)) {
3355                changed = false;
3356            }
3357        }
3358        bp.protectionLevel = fixedLevel;
3359        info = new PermissionInfo(info);
3360        info.protectionLevel = fixedLevel;
3361        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3362        bp.perm.info.packageName = tree.perm.info.packageName;
3363        bp.uid = tree.uid;
3364        if (added) {
3365            mSettings.mPermissions.put(info.name, bp);
3366        }
3367        if (changed) {
3368            if (!async) {
3369                mSettings.writeLPr();
3370            } else {
3371                scheduleWriteSettingsLocked();
3372            }
3373        }
3374        return added;
3375    }
3376
3377    @Override
3378    public boolean addPermission(PermissionInfo info) {
3379        synchronized (mPackages) {
3380            return addPermissionLocked(info, false);
3381        }
3382    }
3383
3384    @Override
3385    public boolean addPermissionAsync(PermissionInfo info) {
3386        synchronized (mPackages) {
3387            return addPermissionLocked(info, true);
3388        }
3389    }
3390
3391    @Override
3392    public void removePermission(String name) {
3393        synchronized (mPackages) {
3394            checkPermissionTreeLP(name);
3395            BasePermission bp = mSettings.mPermissions.get(name);
3396            if (bp != null) {
3397                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3398                    throw new SecurityException(
3399                            "Not allowed to modify non-dynamic permission "
3400                            + name);
3401                }
3402                mSettings.mPermissions.remove(name);
3403                mSettings.writeLPr();
3404            }
3405        }
3406    }
3407
3408    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3409            BasePermission bp) {
3410        int index = pkg.requestedPermissions.indexOf(bp.name);
3411        if (index == -1) {
3412            throw new SecurityException("Package " + pkg.packageName
3413                    + " has not requested permission " + bp.name);
3414        }
3415        if (!bp.isRuntime()) {
3416            throw new SecurityException("Permission " + bp.name
3417                    + " is not a changeable permission type");
3418        }
3419    }
3420
3421    @Override
3422    public void grantRuntimePermission(String packageName, String name, final int userId) {
3423        if (!sUserManager.exists(userId)) {
3424            Log.e(TAG, "No such user:" + userId);
3425            return;
3426        }
3427
3428        mContext.enforceCallingOrSelfPermission(
3429                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3430                "grantRuntimePermission");
3431
3432        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3433                "grantRuntimePermission");
3434
3435        final int uid;
3436        final SettingBase sb;
3437
3438        synchronized (mPackages) {
3439            final PackageParser.Package pkg = mPackages.get(packageName);
3440            if (pkg == null) {
3441                throw new IllegalArgumentException("Unknown package: " + packageName);
3442            }
3443
3444            final BasePermission bp = mSettings.mPermissions.get(name);
3445            if (bp == null) {
3446                throw new IllegalArgumentException("Unknown permission: " + name);
3447            }
3448
3449            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3450
3451            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3452            sb = (SettingBase) pkg.mExtras;
3453            if (sb == null) {
3454                throw new IllegalArgumentException("Unknown package: " + packageName);
3455            }
3456
3457            final PermissionsState permissionsState = sb.getPermissionsState();
3458
3459            final int flags = permissionsState.getPermissionFlags(name, userId);
3460            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3461                throw new SecurityException("Cannot grant system fixed permission: "
3462                        + name + " for package: " + packageName);
3463            }
3464
3465            final int result = permissionsState.grantRuntimePermission(bp, userId);
3466            switch (result) {
3467                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3468                    return;
3469                }
3470
3471                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3472                    mHandler.post(new Runnable() {
3473                        @Override
3474                        public void run() {
3475                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3476                        }
3477                    });
3478                } break;
3479            }
3480
3481            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3482
3483            // Not critical if that is lost - app has to request again.
3484            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3485        }
3486
3487        // Only need to do this if user is initialized. Otherwise it's a new user
3488        // and there are no processes running as the user yet and there's no need
3489        // to make an expensive call to remount processes for the changed permissions.
3490        if (READ_EXTERNAL_STORAGE.equals(name)
3491                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3492            final long token = Binder.clearCallingIdentity();
3493            try {
3494                if (sUserManager.isInitialized(userId)) {
3495                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3496                            MountServiceInternal.class);
3497                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3498                }
3499            } finally {
3500                Binder.restoreCallingIdentity(token);
3501            }
3502        }
3503    }
3504
3505    @Override
3506    public void revokeRuntimePermission(String packageName, String name, int userId) {
3507        if (!sUserManager.exists(userId)) {
3508            Log.e(TAG, "No such user:" + userId);
3509            return;
3510        }
3511
3512        mContext.enforceCallingOrSelfPermission(
3513                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3514                "revokeRuntimePermission");
3515
3516        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3517                "revokeRuntimePermission");
3518
3519        final SettingBase sb;
3520
3521        synchronized (mPackages) {
3522            final PackageParser.Package pkg = mPackages.get(packageName);
3523            if (pkg == null) {
3524                throw new IllegalArgumentException("Unknown package: " + packageName);
3525            }
3526
3527            final BasePermission bp = mSettings.mPermissions.get(name);
3528            if (bp == null) {
3529                throw new IllegalArgumentException("Unknown permission: " + name);
3530            }
3531
3532            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3533
3534            sb = (SettingBase) pkg.mExtras;
3535            if (sb == null) {
3536                throw new IllegalArgumentException("Unknown package: " + packageName);
3537            }
3538
3539            final PermissionsState permissionsState = sb.getPermissionsState();
3540
3541            final int flags = permissionsState.getPermissionFlags(name, userId);
3542            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3543                throw new SecurityException("Cannot revoke system fixed permission: "
3544                        + name + " for package: " + packageName);
3545            }
3546
3547            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3548                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3549                return;
3550            }
3551
3552            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3553
3554            // Critical, after this call app should never have the permission.
3555            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3556        }
3557
3558        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3559    }
3560
3561    @Override
3562    public void resetRuntimePermissions() {
3563        mContext.enforceCallingOrSelfPermission(
3564                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3565                "revokeRuntimePermission");
3566
3567        int callingUid = Binder.getCallingUid();
3568        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3569            mContext.enforceCallingOrSelfPermission(
3570                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3571                    "resetRuntimePermissions");
3572        }
3573
3574        synchronized (mPackages) {
3575            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3576            for (int userId : UserManagerService.getInstance().getUserIds()) {
3577                final int packageCount = mPackages.size();
3578                for (int i = 0; i < packageCount; i++) {
3579                    PackageParser.Package pkg = mPackages.valueAt(i);
3580                    if (!(pkg.mExtras instanceof PackageSetting)) {
3581                        continue;
3582                    }
3583                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3584                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3585                }
3586            }
3587        }
3588    }
3589
3590    @Override
3591    public int getPermissionFlags(String name, String packageName, int userId) {
3592        if (!sUserManager.exists(userId)) {
3593            return 0;
3594        }
3595
3596        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3597
3598        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3599                "getPermissionFlags");
3600
3601        synchronized (mPackages) {
3602            final PackageParser.Package pkg = mPackages.get(packageName);
3603            if (pkg == null) {
3604                throw new IllegalArgumentException("Unknown package: " + packageName);
3605            }
3606
3607            final BasePermission bp = mSettings.mPermissions.get(name);
3608            if (bp == null) {
3609                throw new IllegalArgumentException("Unknown permission: " + name);
3610            }
3611
3612            SettingBase sb = (SettingBase) pkg.mExtras;
3613            if (sb == null) {
3614                throw new IllegalArgumentException("Unknown package: " + packageName);
3615            }
3616
3617            PermissionsState permissionsState = sb.getPermissionsState();
3618            return permissionsState.getPermissionFlags(name, userId);
3619        }
3620    }
3621
3622    @Override
3623    public void updatePermissionFlags(String name, String packageName, int flagMask,
3624            int flagValues, int userId) {
3625        if (!sUserManager.exists(userId)) {
3626            return;
3627        }
3628
3629        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3630
3631        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3632                "updatePermissionFlags");
3633
3634        // Only the system can change these flags and nothing else.
3635        if (getCallingUid() != Process.SYSTEM_UID) {
3636            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3637            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3638            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3639            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3640        }
3641
3642        synchronized (mPackages) {
3643            final PackageParser.Package pkg = mPackages.get(packageName);
3644            if (pkg == null) {
3645                throw new IllegalArgumentException("Unknown package: " + packageName);
3646            }
3647
3648            final BasePermission bp = mSettings.mPermissions.get(name);
3649            if (bp == null) {
3650                throw new IllegalArgumentException("Unknown permission: " + name);
3651            }
3652
3653            SettingBase sb = (SettingBase) pkg.mExtras;
3654            if (sb == null) {
3655                throw new IllegalArgumentException("Unknown package: " + packageName);
3656            }
3657
3658            PermissionsState permissionsState = sb.getPermissionsState();
3659
3660            // Only the package manager can change flags for system component permissions.
3661            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3662            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3663                return;
3664            }
3665
3666            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3667
3668            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3669                // Install and runtime permissions are stored in different places,
3670                // so figure out what permission changed and persist the change.
3671                if (permissionsState.getInstallPermissionState(name) != null) {
3672                    scheduleWriteSettingsLocked();
3673                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3674                        || hadState) {
3675                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3676                }
3677            }
3678        }
3679    }
3680
3681    /**
3682     * Update the permission flags for all packages and runtime permissions of a user in order
3683     * to allow device or profile owner to remove POLICY_FIXED.
3684     */
3685    @Override
3686    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3687        if (!sUserManager.exists(userId)) {
3688            return;
3689        }
3690
3691        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3692
3693        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3694                "updatePermissionFlagsForAllApps");
3695
3696        // Only the system can change system fixed flags.
3697        if (getCallingUid() != Process.SYSTEM_UID) {
3698            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3699            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3700        }
3701
3702        synchronized (mPackages) {
3703            boolean changed = false;
3704            final int packageCount = mPackages.size();
3705            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3706                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3707                SettingBase sb = (SettingBase) pkg.mExtras;
3708                if (sb == null) {
3709                    continue;
3710                }
3711                PermissionsState permissionsState = sb.getPermissionsState();
3712                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3713                        userId, flagMask, flagValues);
3714            }
3715            if (changed) {
3716                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3717            }
3718        }
3719    }
3720
3721    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3722        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3723                != PackageManager.PERMISSION_GRANTED
3724            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3725                != PackageManager.PERMISSION_GRANTED) {
3726            throw new SecurityException(message + " requires "
3727                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3728                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3729        }
3730    }
3731
3732    @Override
3733    public boolean shouldShowRequestPermissionRationale(String permissionName,
3734            String packageName, int userId) {
3735        if (UserHandle.getCallingUserId() != userId) {
3736            mContext.enforceCallingPermission(
3737                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3738                    "canShowRequestPermissionRationale for user " + userId);
3739        }
3740
3741        final int uid = getPackageUid(packageName, userId);
3742        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3743            return false;
3744        }
3745
3746        if (checkPermission(permissionName, packageName, userId)
3747                == PackageManager.PERMISSION_GRANTED) {
3748            return false;
3749        }
3750
3751        final int flags;
3752
3753        final long identity = Binder.clearCallingIdentity();
3754        try {
3755            flags = getPermissionFlags(permissionName,
3756                    packageName, userId);
3757        } finally {
3758            Binder.restoreCallingIdentity(identity);
3759        }
3760
3761        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3762                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3763                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3764
3765        if ((flags & fixedFlags) != 0) {
3766            return false;
3767        }
3768
3769        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3770    }
3771
3772    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3773        BasePermission bp = mSettings.mPermissions.get(permission);
3774        if (bp == null) {
3775            throw new SecurityException("Missing " + permission + " permission");
3776        }
3777
3778        SettingBase sb = (SettingBase) pkg.mExtras;
3779        PermissionsState permissionsState = sb.getPermissionsState();
3780
3781        if (permissionsState.grantInstallPermission(bp) !=
3782                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3783            scheduleWriteSettingsLocked();
3784        }
3785    }
3786
3787    @Override
3788    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3789        mContext.enforceCallingOrSelfPermission(
3790                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3791                "addOnPermissionsChangeListener");
3792
3793        synchronized (mPackages) {
3794            mOnPermissionChangeListeners.addListenerLocked(listener);
3795        }
3796    }
3797
3798    @Override
3799    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3800        synchronized (mPackages) {
3801            mOnPermissionChangeListeners.removeListenerLocked(listener);
3802        }
3803    }
3804
3805    @Override
3806    public boolean isProtectedBroadcast(String actionName) {
3807        synchronized (mPackages) {
3808            return mProtectedBroadcasts.contains(actionName);
3809        }
3810    }
3811
3812    @Override
3813    public int checkSignatures(String pkg1, String pkg2) {
3814        synchronized (mPackages) {
3815            final PackageParser.Package p1 = mPackages.get(pkg1);
3816            final PackageParser.Package p2 = mPackages.get(pkg2);
3817            if (p1 == null || p1.mExtras == null
3818                    || p2 == null || p2.mExtras == null) {
3819                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3820            }
3821            return compareSignatures(p1.mSignatures, p2.mSignatures);
3822        }
3823    }
3824
3825    @Override
3826    public int checkUidSignatures(int uid1, int uid2) {
3827        // Map to base uids.
3828        uid1 = UserHandle.getAppId(uid1);
3829        uid2 = UserHandle.getAppId(uid2);
3830        // reader
3831        synchronized (mPackages) {
3832            Signature[] s1;
3833            Signature[] s2;
3834            Object obj = mSettings.getUserIdLPr(uid1);
3835            if (obj != null) {
3836                if (obj instanceof SharedUserSetting) {
3837                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3838                } else if (obj instanceof PackageSetting) {
3839                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3840                } else {
3841                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3842                }
3843            } else {
3844                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3845            }
3846            obj = mSettings.getUserIdLPr(uid2);
3847            if (obj != null) {
3848                if (obj instanceof SharedUserSetting) {
3849                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3850                } else if (obj instanceof PackageSetting) {
3851                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3852                } else {
3853                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3854                }
3855            } else {
3856                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3857            }
3858            return compareSignatures(s1, s2);
3859        }
3860    }
3861
3862    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3863        final long identity = Binder.clearCallingIdentity();
3864        try {
3865            if (sb instanceof SharedUserSetting) {
3866                SharedUserSetting sus = (SharedUserSetting) sb;
3867                final int packageCount = sus.packages.size();
3868                for (int i = 0; i < packageCount; i++) {
3869                    PackageSetting susPs = sus.packages.valueAt(i);
3870                    if (userId == UserHandle.USER_ALL) {
3871                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3872                    } else {
3873                        final int uid = UserHandle.getUid(userId, susPs.appId);
3874                        killUid(uid, reason);
3875                    }
3876                }
3877            } else if (sb instanceof PackageSetting) {
3878                PackageSetting ps = (PackageSetting) sb;
3879                if (userId == UserHandle.USER_ALL) {
3880                    killApplication(ps.pkg.packageName, ps.appId, reason);
3881                } else {
3882                    final int uid = UserHandle.getUid(userId, ps.appId);
3883                    killUid(uid, reason);
3884                }
3885            }
3886        } finally {
3887            Binder.restoreCallingIdentity(identity);
3888        }
3889    }
3890
3891    private static void killUid(int uid, String reason) {
3892        IActivityManager am = ActivityManagerNative.getDefault();
3893        if (am != null) {
3894            try {
3895                am.killUid(uid, reason);
3896            } catch (RemoteException e) {
3897                /* ignore - same process */
3898            }
3899        }
3900    }
3901
3902    /**
3903     * Compares two sets of signatures. Returns:
3904     * <br />
3905     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3906     * <br />
3907     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3908     * <br />
3909     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3910     * <br />
3911     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3912     * <br />
3913     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3914     */
3915    static int compareSignatures(Signature[] s1, Signature[] s2) {
3916        if (s1 == null) {
3917            return s2 == null
3918                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3919                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3920        }
3921
3922        if (s2 == null) {
3923            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3924        }
3925
3926        if (s1.length != s2.length) {
3927            return PackageManager.SIGNATURE_NO_MATCH;
3928        }
3929
3930        // Since both signature sets are of size 1, we can compare without HashSets.
3931        if (s1.length == 1) {
3932            return s1[0].equals(s2[0]) ?
3933                    PackageManager.SIGNATURE_MATCH :
3934                    PackageManager.SIGNATURE_NO_MATCH;
3935        }
3936
3937        ArraySet<Signature> set1 = new ArraySet<Signature>();
3938        for (Signature sig : s1) {
3939            set1.add(sig);
3940        }
3941        ArraySet<Signature> set2 = new ArraySet<Signature>();
3942        for (Signature sig : s2) {
3943            set2.add(sig);
3944        }
3945        // Make sure s2 contains all signatures in s1.
3946        if (set1.equals(set2)) {
3947            return PackageManager.SIGNATURE_MATCH;
3948        }
3949        return PackageManager.SIGNATURE_NO_MATCH;
3950    }
3951
3952    /**
3953     * If the database version for this type of package (internal storage or
3954     * external storage) is less than the version where package signatures
3955     * were updated, return true.
3956     */
3957    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3958        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3959        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3960    }
3961
3962    /**
3963     * Used for backward compatibility to make sure any packages with
3964     * certificate chains get upgraded to the new style. {@code existingSigs}
3965     * will be in the old format (since they were stored on disk from before the
3966     * system upgrade) and {@code scannedSigs} will be in the newer format.
3967     */
3968    private int compareSignaturesCompat(PackageSignatures existingSigs,
3969            PackageParser.Package scannedPkg) {
3970        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3971            return PackageManager.SIGNATURE_NO_MATCH;
3972        }
3973
3974        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3975        for (Signature sig : existingSigs.mSignatures) {
3976            existingSet.add(sig);
3977        }
3978        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3979        for (Signature sig : scannedPkg.mSignatures) {
3980            try {
3981                Signature[] chainSignatures = sig.getChainSignatures();
3982                for (Signature chainSig : chainSignatures) {
3983                    scannedCompatSet.add(chainSig);
3984                }
3985            } catch (CertificateEncodingException e) {
3986                scannedCompatSet.add(sig);
3987            }
3988        }
3989        /*
3990         * Make sure the expanded scanned set contains all signatures in the
3991         * existing one.
3992         */
3993        if (scannedCompatSet.equals(existingSet)) {
3994            // Migrate the old signatures to the new scheme.
3995            existingSigs.assignSignatures(scannedPkg.mSignatures);
3996            // The new KeySets will be re-added later in the scanning process.
3997            synchronized (mPackages) {
3998                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3999            }
4000            return PackageManager.SIGNATURE_MATCH;
4001        }
4002        return PackageManager.SIGNATURE_NO_MATCH;
4003    }
4004
4005    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4006        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4007        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4008    }
4009
4010    private int compareSignaturesRecover(PackageSignatures existingSigs,
4011            PackageParser.Package scannedPkg) {
4012        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4013            return PackageManager.SIGNATURE_NO_MATCH;
4014        }
4015
4016        String msg = null;
4017        try {
4018            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4019                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4020                        + scannedPkg.packageName);
4021                return PackageManager.SIGNATURE_MATCH;
4022            }
4023        } catch (CertificateException e) {
4024            msg = e.getMessage();
4025        }
4026
4027        logCriticalInfo(Log.INFO,
4028                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4029        return PackageManager.SIGNATURE_NO_MATCH;
4030    }
4031
4032    @Override
4033    public String[] getPackagesForUid(int uid) {
4034        uid = UserHandle.getAppId(uid);
4035        // reader
4036        synchronized (mPackages) {
4037            Object obj = mSettings.getUserIdLPr(uid);
4038            if (obj instanceof SharedUserSetting) {
4039                final SharedUserSetting sus = (SharedUserSetting) obj;
4040                final int N = sus.packages.size();
4041                final String[] res = new String[N];
4042                final Iterator<PackageSetting> it = sus.packages.iterator();
4043                int i = 0;
4044                while (it.hasNext()) {
4045                    res[i++] = it.next().name;
4046                }
4047                return res;
4048            } else if (obj instanceof PackageSetting) {
4049                final PackageSetting ps = (PackageSetting) obj;
4050                return new String[] { ps.name };
4051            }
4052        }
4053        return null;
4054    }
4055
4056    @Override
4057    public String getNameForUid(int uid) {
4058        // reader
4059        synchronized (mPackages) {
4060            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4061            if (obj instanceof SharedUserSetting) {
4062                final SharedUserSetting sus = (SharedUserSetting) obj;
4063                return sus.name + ":" + sus.userId;
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return ps.name;
4067            }
4068        }
4069        return null;
4070    }
4071
4072    @Override
4073    public int getUidForSharedUser(String sharedUserName) {
4074        if(sharedUserName == null) {
4075            return -1;
4076        }
4077        // reader
4078        synchronized (mPackages) {
4079            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4080            if (suid == null) {
4081                return -1;
4082            }
4083            return suid.userId;
4084        }
4085    }
4086
4087    @Override
4088    public int getFlagsForUid(int uid) {
4089        synchronized (mPackages) {
4090            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4091            if (obj instanceof SharedUserSetting) {
4092                final SharedUserSetting sus = (SharedUserSetting) obj;
4093                return sus.pkgFlags;
4094            } else if (obj instanceof PackageSetting) {
4095                final PackageSetting ps = (PackageSetting) obj;
4096                return ps.pkgFlags;
4097            }
4098        }
4099        return 0;
4100    }
4101
4102    @Override
4103    public int getPrivateFlagsForUid(int uid) {
4104        synchronized (mPackages) {
4105            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4106            if (obj instanceof SharedUserSetting) {
4107                final SharedUserSetting sus = (SharedUserSetting) obj;
4108                return sus.pkgPrivateFlags;
4109            } else if (obj instanceof PackageSetting) {
4110                final PackageSetting ps = (PackageSetting) obj;
4111                return ps.pkgPrivateFlags;
4112            }
4113        }
4114        return 0;
4115    }
4116
4117    @Override
4118    public boolean isUidPrivileged(int uid) {
4119        uid = UserHandle.getAppId(uid);
4120        // reader
4121        synchronized (mPackages) {
4122            Object obj = mSettings.getUserIdLPr(uid);
4123            if (obj instanceof SharedUserSetting) {
4124                final SharedUserSetting sus = (SharedUserSetting) obj;
4125                final Iterator<PackageSetting> it = sus.packages.iterator();
4126                while (it.hasNext()) {
4127                    if (it.next().isPrivileged()) {
4128                        return true;
4129                    }
4130                }
4131            } else if (obj instanceof PackageSetting) {
4132                final PackageSetting ps = (PackageSetting) obj;
4133                return ps.isPrivileged();
4134            }
4135        }
4136        return false;
4137    }
4138
4139    @Override
4140    public String[] getAppOpPermissionPackages(String permissionName) {
4141        synchronized (mPackages) {
4142            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4143            if (pkgs == null) {
4144                return null;
4145            }
4146            return pkgs.toArray(new String[pkgs.size()]);
4147        }
4148    }
4149
4150    @Override
4151    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4152            int flags, int userId) {
4153        if (!sUserManager.exists(userId)) return null;
4154        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4155        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4156        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4157    }
4158
4159    @Override
4160    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4161            IntentFilter filter, int match, ComponentName activity) {
4162        final int userId = UserHandle.getCallingUserId();
4163        if (DEBUG_PREFERRED) {
4164            Log.v(TAG, "setLastChosenActivity intent=" + intent
4165                + " resolvedType=" + resolvedType
4166                + " flags=" + flags
4167                + " filter=" + filter
4168                + " match=" + match
4169                + " activity=" + activity);
4170            filter.dump(new PrintStreamPrinter(System.out), "    ");
4171        }
4172        intent.setComponent(null);
4173        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4174        // Find any earlier preferred or last chosen entries and nuke them
4175        findPreferredActivity(intent, resolvedType,
4176                flags, query, 0, false, true, false, userId);
4177        // Add the new activity as the last chosen for this filter
4178        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4179                "Setting last chosen");
4180    }
4181
4182    @Override
4183    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4184        final int userId = UserHandle.getCallingUserId();
4185        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4186        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4187        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4188                false, false, false, userId);
4189    }
4190
4191    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4192            int flags, List<ResolveInfo> query, int userId) {
4193        if (query != null) {
4194            final int N = query.size();
4195            if (N == 1) {
4196                return query.get(0);
4197            } else if (N > 1) {
4198                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4199                // If there is more than one activity with the same priority,
4200                // then let the user decide between them.
4201                ResolveInfo r0 = query.get(0);
4202                ResolveInfo r1 = query.get(1);
4203                if (DEBUG_INTENT_MATCHING || debug) {
4204                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4205                            + r1.activityInfo.name + "=" + r1.priority);
4206                }
4207                // If the first activity has a higher priority, or a different
4208                // default, then it is always desireable to pick it.
4209                if (r0.priority != r1.priority
4210                        || r0.preferredOrder != r1.preferredOrder
4211                        || r0.isDefault != r1.isDefault) {
4212                    return query.get(0);
4213                }
4214                // If we have saved a preference for a preferred activity for
4215                // this Intent, use that.
4216                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4217                        flags, query, r0.priority, true, false, debug, userId);
4218                if (ri != null) {
4219                    return ri;
4220                }
4221                if (userId != 0) {
4222                    ri = new ResolveInfo(mResolveInfo);
4223                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4224                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4225                            ri.activityInfo.applicationInfo);
4226                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4227                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4228                    return ri;
4229                }
4230                return mResolveInfo;
4231            }
4232        }
4233        return null;
4234    }
4235
4236    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4237            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4238        final int N = query.size();
4239        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4240                .get(userId);
4241        // Get the list of persistent preferred activities that handle the intent
4242        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4243        List<PersistentPreferredActivity> pprefs = ppir != null
4244                ? ppir.queryIntent(intent, resolvedType,
4245                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4246                : null;
4247        if (pprefs != null && pprefs.size() > 0) {
4248            final int M = pprefs.size();
4249            for (int i=0; i<M; i++) {
4250                final PersistentPreferredActivity ppa = pprefs.get(i);
4251                if (DEBUG_PREFERRED || debug) {
4252                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4253                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4254                            + "\n  component=" + ppa.mComponent);
4255                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4256                }
4257                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4258                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4259                if (DEBUG_PREFERRED || debug) {
4260                    Slog.v(TAG, "Found persistent preferred activity:");
4261                    if (ai != null) {
4262                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4263                    } else {
4264                        Slog.v(TAG, "  null");
4265                    }
4266                }
4267                if (ai == null) {
4268                    // This previously registered persistent preferred activity
4269                    // component is no longer known. Ignore it and do NOT remove it.
4270                    continue;
4271                }
4272                for (int j=0; j<N; j++) {
4273                    final ResolveInfo ri = query.get(j);
4274                    if (!ri.activityInfo.applicationInfo.packageName
4275                            .equals(ai.applicationInfo.packageName)) {
4276                        continue;
4277                    }
4278                    if (!ri.activityInfo.name.equals(ai.name)) {
4279                        continue;
4280                    }
4281                    //  Found a persistent preference that can handle the intent.
4282                    if (DEBUG_PREFERRED || debug) {
4283                        Slog.v(TAG, "Returning persistent preferred activity: " +
4284                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4285                    }
4286                    return ri;
4287                }
4288            }
4289        }
4290        return null;
4291    }
4292
4293    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4294            List<ResolveInfo> query, int priority, boolean always,
4295            boolean removeMatches, boolean debug, int userId) {
4296        if (!sUserManager.exists(userId)) return null;
4297        // writer
4298        synchronized (mPackages) {
4299            if (intent.getSelector() != null) {
4300                intent = intent.getSelector();
4301            }
4302            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4303
4304            // Try to find a matching persistent preferred activity.
4305            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4306                    debug, userId);
4307
4308            // If a persistent preferred activity matched, use it.
4309            if (pri != null) {
4310                return pri;
4311            }
4312
4313            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4314            // Get the list of preferred activities that handle the intent
4315            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4316            List<PreferredActivity> prefs = pir != null
4317                    ? pir.queryIntent(intent, resolvedType,
4318                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4319                    : null;
4320            if (prefs != null && prefs.size() > 0) {
4321                boolean changed = false;
4322                try {
4323                    // First figure out how good the original match set is.
4324                    // We will only allow preferred activities that came
4325                    // from the same match quality.
4326                    int match = 0;
4327
4328                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4329
4330                    final int N = query.size();
4331                    for (int j=0; j<N; j++) {
4332                        final ResolveInfo ri = query.get(j);
4333                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4334                                + ": 0x" + Integer.toHexString(match));
4335                        if (ri.match > match) {
4336                            match = ri.match;
4337                        }
4338                    }
4339
4340                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4341                            + Integer.toHexString(match));
4342
4343                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4344                    final int M = prefs.size();
4345                    for (int i=0; i<M; i++) {
4346                        final PreferredActivity pa = prefs.get(i);
4347                        if (DEBUG_PREFERRED || debug) {
4348                            Slog.v(TAG, "Checking PreferredActivity ds="
4349                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4350                                    + "\n  component=" + pa.mPref.mComponent);
4351                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4352                        }
4353                        if (pa.mPref.mMatch != match) {
4354                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4355                                    + Integer.toHexString(pa.mPref.mMatch));
4356                            continue;
4357                        }
4358                        // If it's not an "always" type preferred activity and that's what we're
4359                        // looking for, skip it.
4360                        if (always && !pa.mPref.mAlways) {
4361                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4362                            continue;
4363                        }
4364                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4365                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4366                        if (DEBUG_PREFERRED || debug) {
4367                            Slog.v(TAG, "Found preferred activity:");
4368                            if (ai != null) {
4369                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4370                            } else {
4371                                Slog.v(TAG, "  null");
4372                            }
4373                        }
4374                        if (ai == null) {
4375                            // This previously registered preferred activity
4376                            // component is no longer known.  Most likely an update
4377                            // to the app was installed and in the new version this
4378                            // component no longer exists.  Clean it up by removing
4379                            // it from the preferred activities list, and skip it.
4380                            Slog.w(TAG, "Removing dangling preferred activity: "
4381                                    + pa.mPref.mComponent);
4382                            pir.removeFilter(pa);
4383                            changed = true;
4384                            continue;
4385                        }
4386                        for (int j=0; j<N; j++) {
4387                            final ResolveInfo ri = query.get(j);
4388                            if (!ri.activityInfo.applicationInfo.packageName
4389                                    .equals(ai.applicationInfo.packageName)) {
4390                                continue;
4391                            }
4392                            if (!ri.activityInfo.name.equals(ai.name)) {
4393                                continue;
4394                            }
4395
4396                            if (removeMatches) {
4397                                pir.removeFilter(pa);
4398                                changed = true;
4399                                if (DEBUG_PREFERRED) {
4400                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4401                                }
4402                                break;
4403                            }
4404
4405                            // Okay we found a previously set preferred or last chosen app.
4406                            // If the result set is different from when this
4407                            // was created, we need to clear it and re-ask the
4408                            // user their preference, if we're looking for an "always" type entry.
4409                            if (always && !pa.mPref.sameSet(query)) {
4410                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4411                                        + intent + " type " + resolvedType);
4412                                if (DEBUG_PREFERRED) {
4413                                    Slog.v(TAG, "Removing preferred activity since set changed "
4414                                            + pa.mPref.mComponent);
4415                                }
4416                                pir.removeFilter(pa);
4417                                // Re-add the filter as a "last chosen" entry (!always)
4418                                PreferredActivity lastChosen = new PreferredActivity(
4419                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4420                                pir.addFilter(lastChosen);
4421                                changed = true;
4422                                return null;
4423                            }
4424
4425                            // Yay! Either the set matched or we're looking for the last chosen
4426                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4427                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4428                            return ri;
4429                        }
4430                    }
4431                } finally {
4432                    if (changed) {
4433                        if (DEBUG_PREFERRED) {
4434                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4435                        }
4436                        scheduleWritePackageRestrictionsLocked(userId);
4437                    }
4438                }
4439            }
4440        }
4441        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4442        return null;
4443    }
4444
4445    /*
4446     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4447     */
4448    @Override
4449    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4450            int targetUserId) {
4451        mContext.enforceCallingOrSelfPermission(
4452                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4453        List<CrossProfileIntentFilter> matches =
4454                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4455        if (matches != null) {
4456            int size = matches.size();
4457            for (int i = 0; i < size; i++) {
4458                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4459            }
4460        }
4461        if (hasWebURI(intent)) {
4462            // cross-profile app linking works only towards the parent.
4463            final UserInfo parent = getProfileParent(sourceUserId);
4464            synchronized(mPackages) {
4465                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4466                        intent, resolvedType, 0, sourceUserId, parent.id);
4467                return xpDomainInfo != null;
4468            }
4469        }
4470        return false;
4471    }
4472
4473    private UserInfo getProfileParent(int userId) {
4474        final long identity = Binder.clearCallingIdentity();
4475        try {
4476            return sUserManager.getProfileParent(userId);
4477        } finally {
4478            Binder.restoreCallingIdentity(identity);
4479        }
4480    }
4481
4482    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4483            String resolvedType, int userId) {
4484        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4485        if (resolver != null) {
4486            return resolver.queryIntent(intent, resolvedType, false, userId);
4487        }
4488        return null;
4489    }
4490
4491    @Override
4492    public List<ResolveInfo> queryIntentActivities(Intent intent,
4493            String resolvedType, int flags, int userId) {
4494        if (!sUserManager.exists(userId)) return Collections.emptyList();
4495        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4496        ComponentName comp = intent.getComponent();
4497        if (comp == null) {
4498            if (intent.getSelector() != null) {
4499                intent = intent.getSelector();
4500                comp = intent.getComponent();
4501            }
4502        }
4503
4504        if (comp != null) {
4505            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4506            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4507            if (ai != null) {
4508                final ResolveInfo ri = new ResolveInfo();
4509                ri.activityInfo = ai;
4510                list.add(ri);
4511            }
4512            return list;
4513        }
4514
4515        // reader
4516        synchronized (mPackages) {
4517            final String pkgName = intent.getPackage();
4518            if (pkgName == null) {
4519                List<CrossProfileIntentFilter> matchingFilters =
4520                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4521                // Check for results that need to skip the current profile.
4522                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4523                        resolvedType, flags, userId);
4524                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4525                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4526                    result.add(xpResolveInfo);
4527                    return filterIfNotPrimaryUser(result, userId);
4528                }
4529
4530                // Check for results in the current profile.
4531                List<ResolveInfo> result = mActivities.queryIntent(
4532                        intent, resolvedType, flags, userId);
4533
4534                // Check for cross profile results.
4535                xpResolveInfo = queryCrossProfileIntents(
4536                        matchingFilters, intent, resolvedType, flags, userId);
4537                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4538                    result.add(xpResolveInfo);
4539                    Collections.sort(result, mResolvePrioritySorter);
4540                }
4541                result = filterIfNotPrimaryUser(result, userId);
4542                if (hasWebURI(intent)) {
4543                    CrossProfileDomainInfo xpDomainInfo = null;
4544                    final UserInfo parent = getProfileParent(userId);
4545                    if (parent != null) {
4546                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4547                                flags, userId, parent.id);
4548                    }
4549                    if (xpDomainInfo != null) {
4550                        if (xpResolveInfo != null) {
4551                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4552                            // in the result.
4553                            result.remove(xpResolveInfo);
4554                        }
4555                        if (result.size() == 0) {
4556                            result.add(xpDomainInfo.resolveInfo);
4557                            return result;
4558                        }
4559                    } else if (result.size() <= 1) {
4560                        return result;
4561                    }
4562                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4563                            xpDomainInfo, userId);
4564                    Collections.sort(result, mResolvePrioritySorter);
4565                }
4566                return result;
4567            }
4568            final PackageParser.Package pkg = mPackages.get(pkgName);
4569            if (pkg != null) {
4570                return filterIfNotPrimaryUser(
4571                        mActivities.queryIntentForPackage(
4572                                intent, resolvedType, flags, pkg.activities, userId),
4573                        userId);
4574            }
4575            return new ArrayList<ResolveInfo>();
4576        }
4577    }
4578
4579    private static class CrossProfileDomainInfo {
4580        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4581        ResolveInfo resolveInfo;
4582        /* Best domain verification status of the activities found in the other profile */
4583        int bestDomainVerificationStatus;
4584    }
4585
4586    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4587            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4588        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4589                sourceUserId)) {
4590            return null;
4591        }
4592        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4593                resolvedType, flags, parentUserId);
4594
4595        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4596            return null;
4597        }
4598        CrossProfileDomainInfo result = null;
4599        int size = resultTargetUser.size();
4600        for (int i = 0; i < size; i++) {
4601            ResolveInfo riTargetUser = resultTargetUser.get(i);
4602            // Intent filter verification is only for filters that specify a host. So don't return
4603            // those that handle all web uris.
4604            if (riTargetUser.handleAllWebDataURI) {
4605                continue;
4606            }
4607            String packageName = riTargetUser.activityInfo.packageName;
4608            PackageSetting ps = mSettings.mPackages.get(packageName);
4609            if (ps == null) {
4610                continue;
4611            }
4612            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4613            int status = (int)(verificationState >> 32);
4614            if (result == null) {
4615                result = new CrossProfileDomainInfo();
4616                result.resolveInfo =
4617                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4618                result.bestDomainVerificationStatus = status;
4619            } else {
4620                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4621                        result.bestDomainVerificationStatus);
4622            }
4623        }
4624        // Don't consider matches with status NEVER across profiles.
4625        if (result != null && result.bestDomainVerificationStatus
4626                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4627            return null;
4628        }
4629        return result;
4630    }
4631
4632    /**
4633     * Verification statuses are ordered from the worse to the best, except for
4634     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4635     */
4636    private int bestDomainVerificationStatus(int status1, int status2) {
4637        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4638            return status2;
4639        }
4640        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4641            return status1;
4642        }
4643        return (int) MathUtils.max(status1, status2);
4644    }
4645
4646    private boolean isUserEnabled(int userId) {
4647        long callingId = Binder.clearCallingIdentity();
4648        try {
4649            UserInfo userInfo = sUserManager.getUserInfo(userId);
4650            return userInfo != null && userInfo.isEnabled();
4651        } finally {
4652            Binder.restoreCallingIdentity(callingId);
4653        }
4654    }
4655
4656    /**
4657     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4658     *
4659     * @return filtered list
4660     */
4661    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4662        if (userId == UserHandle.USER_OWNER) {
4663            return resolveInfos;
4664        }
4665        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4666            ResolveInfo info = resolveInfos.get(i);
4667            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4668                resolveInfos.remove(i);
4669            }
4670        }
4671        return resolveInfos;
4672    }
4673
4674    private static boolean hasWebURI(Intent intent) {
4675        if (intent.getData() == null) {
4676            return false;
4677        }
4678        final String scheme = intent.getScheme();
4679        if (TextUtils.isEmpty(scheme)) {
4680            return false;
4681        }
4682        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4683    }
4684
4685    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4686            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4687            int userId) {
4688        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4689
4690        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4691            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4692                    candidates.size());
4693        }
4694
4695        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4696        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4697        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4698        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4699        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4700
4701        synchronized (mPackages) {
4702            final int count = candidates.size();
4703            // First, try to use linked apps. Partition the candidates into four lists:
4704            // one for the final results, one for the "do not use ever", one for "undefined status"
4705            // and finally one for "browser app type".
4706            for (int n=0; n<count; n++) {
4707                ResolveInfo info = candidates.get(n);
4708                String packageName = info.activityInfo.packageName;
4709                PackageSetting ps = mSettings.mPackages.get(packageName);
4710                if (ps != null) {
4711                    // Add to the special match all list (Browser use case)
4712                    if (info.handleAllWebDataURI) {
4713                        matchAllList.add(info);
4714                        continue;
4715                    }
4716                    // Try to get the status from User settings first
4717                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4718                    int status = (int)(packedStatus >> 32);
4719                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4720                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4721                        if (DEBUG_DOMAIN_VERIFICATION) {
4722                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4723                                    + " : linkgen=" + linkGeneration);
4724                        }
4725                        // Use link-enabled generation as preferredOrder, i.e.
4726                        // prefer newly-enabled over earlier-enabled.
4727                        info.preferredOrder = linkGeneration;
4728                        alwaysList.add(info);
4729                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4730                        if (DEBUG_DOMAIN_VERIFICATION) {
4731                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4732                        }
4733                        neverList.add(info);
4734                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4735                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4736                        if (DEBUG_DOMAIN_VERIFICATION) {
4737                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4738                        }
4739                        undefinedList.add(info);
4740                    }
4741                }
4742            }
4743            // First try to add the "always" resolution(s) for the current user, if any
4744            if (alwaysList.size() > 0) {
4745                result.addAll(alwaysList);
4746            // if there is an "always" for the parent user, add it.
4747            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4748                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4749                result.add(xpDomainInfo.resolveInfo);
4750            } else {
4751                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4752                result.addAll(undefinedList);
4753                if (xpDomainInfo != null && (
4754                        xpDomainInfo.bestDomainVerificationStatus
4755                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4756                        || xpDomainInfo.bestDomainVerificationStatus
4757                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4758                    result.add(xpDomainInfo.resolveInfo);
4759                }
4760                // Also add Browsers (all of them or only the default one)
4761                if ((matchFlags & MATCH_ALL) != 0) {
4762                    result.addAll(matchAllList);
4763                } else {
4764                    // Browser/generic handling case.  If there's a default browser, go straight
4765                    // to that (but only if there is no other higher-priority match).
4766                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4767                    int maxMatchPrio = 0;
4768                    ResolveInfo defaultBrowserMatch = null;
4769                    final int numCandidates = matchAllList.size();
4770                    for (int n = 0; n < numCandidates; n++) {
4771                        ResolveInfo info = matchAllList.get(n);
4772                        // track the highest overall match priority...
4773                        if (info.priority > maxMatchPrio) {
4774                            maxMatchPrio = info.priority;
4775                        }
4776                        // ...and the highest-priority default browser match
4777                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4778                            if (defaultBrowserMatch == null
4779                                    || (defaultBrowserMatch.priority < info.priority)) {
4780                                if (debug) {
4781                                    Slog.v(TAG, "Considering default browser match " + info);
4782                                }
4783                                defaultBrowserMatch = info;
4784                            }
4785                        }
4786                    }
4787                    if (defaultBrowserMatch != null
4788                            && defaultBrowserMatch.priority >= maxMatchPrio
4789                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4790                    {
4791                        if (debug) {
4792                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4793                        }
4794                        result.add(defaultBrowserMatch);
4795                    } else {
4796                        result.addAll(matchAllList);
4797                    }
4798                }
4799
4800                // If there is nothing selected, add all candidates and remove the ones that the user
4801                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4802                if (result.size() == 0) {
4803                    result.addAll(candidates);
4804                    result.removeAll(neverList);
4805                }
4806            }
4807        }
4808        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4809            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4810                    result.size());
4811            for (ResolveInfo info : result) {
4812                Slog.v(TAG, "  + " + info.activityInfo);
4813            }
4814        }
4815        return result;
4816    }
4817
4818    // Returns a packed value as a long:
4819    //
4820    // high 'int'-sized word: link status: undefined/ask/never/always.
4821    // low 'int'-sized word: relative priority among 'always' results.
4822    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4823        long result = ps.getDomainVerificationStatusForUser(userId);
4824        // if none available, get the master status
4825        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4826            if (ps.getIntentFilterVerificationInfo() != null) {
4827                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4828            }
4829        }
4830        return result;
4831    }
4832
4833    private ResolveInfo querySkipCurrentProfileIntents(
4834            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4835            int flags, int sourceUserId) {
4836        if (matchingFilters != null) {
4837            int size = matchingFilters.size();
4838            for (int i = 0; i < size; i ++) {
4839                CrossProfileIntentFilter filter = matchingFilters.get(i);
4840                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4841                    // Checking if there are activities in the target user that can handle the
4842                    // intent.
4843                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4844                            flags, sourceUserId);
4845                    if (resolveInfo != null) {
4846                        return resolveInfo;
4847                    }
4848                }
4849            }
4850        }
4851        return null;
4852    }
4853
4854    // Return matching ResolveInfo if any for skip current profile intent filters.
4855    private ResolveInfo queryCrossProfileIntents(
4856            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4857            int flags, int sourceUserId) {
4858        if (matchingFilters != null) {
4859            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4860            // match the same intent. For performance reasons, it is better not to
4861            // run queryIntent twice for the same userId
4862            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4863            int size = matchingFilters.size();
4864            for (int i = 0; i < size; i++) {
4865                CrossProfileIntentFilter filter = matchingFilters.get(i);
4866                int targetUserId = filter.getTargetUserId();
4867                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4868                        && !alreadyTriedUserIds.get(targetUserId)) {
4869                    // Checking if there are activities in the target user that can handle the
4870                    // intent.
4871                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4872                            flags, sourceUserId);
4873                    if (resolveInfo != null) return resolveInfo;
4874                    alreadyTriedUserIds.put(targetUserId, true);
4875                }
4876            }
4877        }
4878        return null;
4879    }
4880
4881    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4882            String resolvedType, int flags, int sourceUserId) {
4883        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4884                resolvedType, flags, filter.getTargetUserId());
4885        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4886            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4887        }
4888        return null;
4889    }
4890
4891    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4892            int sourceUserId, int targetUserId) {
4893        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4894        String className;
4895        if (targetUserId == UserHandle.USER_OWNER) {
4896            className = FORWARD_INTENT_TO_USER_OWNER;
4897        } else {
4898            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4899        }
4900        ComponentName forwardingActivityComponentName = new ComponentName(
4901                mAndroidApplication.packageName, className);
4902        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4903                sourceUserId);
4904        if (targetUserId == UserHandle.USER_OWNER) {
4905            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4906            forwardingResolveInfo.noResourceId = true;
4907        }
4908        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4909        forwardingResolveInfo.priority = 0;
4910        forwardingResolveInfo.preferredOrder = 0;
4911        forwardingResolveInfo.match = 0;
4912        forwardingResolveInfo.isDefault = true;
4913        forwardingResolveInfo.filter = filter;
4914        forwardingResolveInfo.targetUserId = targetUserId;
4915        return forwardingResolveInfo;
4916    }
4917
4918    @Override
4919    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4920            Intent[] specifics, String[] specificTypes, Intent intent,
4921            String resolvedType, int flags, int userId) {
4922        if (!sUserManager.exists(userId)) return Collections.emptyList();
4923        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4924                false, "query intent activity options");
4925        final String resultsAction = intent.getAction();
4926
4927        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4928                | PackageManager.GET_RESOLVED_FILTER, userId);
4929
4930        if (DEBUG_INTENT_MATCHING) {
4931            Log.v(TAG, "Query " + intent + ": " + results);
4932        }
4933
4934        int specificsPos = 0;
4935        int N;
4936
4937        // todo: note that the algorithm used here is O(N^2).  This
4938        // isn't a problem in our current environment, but if we start running
4939        // into situations where we have more than 5 or 10 matches then this
4940        // should probably be changed to something smarter...
4941
4942        // First we go through and resolve each of the specific items
4943        // that were supplied, taking care of removing any corresponding
4944        // duplicate items in the generic resolve list.
4945        if (specifics != null) {
4946            for (int i=0; i<specifics.length; i++) {
4947                final Intent sintent = specifics[i];
4948                if (sintent == null) {
4949                    continue;
4950                }
4951
4952                if (DEBUG_INTENT_MATCHING) {
4953                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4954                }
4955
4956                String action = sintent.getAction();
4957                if (resultsAction != null && resultsAction.equals(action)) {
4958                    // If this action was explicitly requested, then don't
4959                    // remove things that have it.
4960                    action = null;
4961                }
4962
4963                ResolveInfo ri = null;
4964                ActivityInfo ai = null;
4965
4966                ComponentName comp = sintent.getComponent();
4967                if (comp == null) {
4968                    ri = resolveIntent(
4969                        sintent,
4970                        specificTypes != null ? specificTypes[i] : null,
4971                            flags, userId);
4972                    if (ri == null) {
4973                        continue;
4974                    }
4975                    if (ri == mResolveInfo) {
4976                        // ACK!  Must do something better with this.
4977                    }
4978                    ai = ri.activityInfo;
4979                    comp = new ComponentName(ai.applicationInfo.packageName,
4980                            ai.name);
4981                } else {
4982                    ai = getActivityInfo(comp, flags, userId);
4983                    if (ai == null) {
4984                        continue;
4985                    }
4986                }
4987
4988                // Look for any generic query activities that are duplicates
4989                // of this specific one, and remove them from the results.
4990                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4991                N = results.size();
4992                int j;
4993                for (j=specificsPos; j<N; j++) {
4994                    ResolveInfo sri = results.get(j);
4995                    if ((sri.activityInfo.name.equals(comp.getClassName())
4996                            && sri.activityInfo.applicationInfo.packageName.equals(
4997                                    comp.getPackageName()))
4998                        || (action != null && sri.filter.matchAction(action))) {
4999                        results.remove(j);
5000                        if (DEBUG_INTENT_MATCHING) Log.v(
5001                            TAG, "Removing duplicate item from " + j
5002                            + " due to specific " + specificsPos);
5003                        if (ri == null) {
5004                            ri = sri;
5005                        }
5006                        j--;
5007                        N--;
5008                    }
5009                }
5010
5011                // Add this specific item to its proper place.
5012                if (ri == null) {
5013                    ri = new ResolveInfo();
5014                    ri.activityInfo = ai;
5015                }
5016                results.add(specificsPos, ri);
5017                ri.specificIndex = i;
5018                specificsPos++;
5019            }
5020        }
5021
5022        // Now we go through the remaining generic results and remove any
5023        // duplicate actions that are found here.
5024        N = results.size();
5025        for (int i=specificsPos; i<N-1; i++) {
5026            final ResolveInfo rii = results.get(i);
5027            if (rii.filter == null) {
5028                continue;
5029            }
5030
5031            // Iterate over all of the actions of this result's intent
5032            // filter...  typically this should be just one.
5033            final Iterator<String> it = rii.filter.actionsIterator();
5034            if (it == null) {
5035                continue;
5036            }
5037            while (it.hasNext()) {
5038                final String action = it.next();
5039                if (resultsAction != null && resultsAction.equals(action)) {
5040                    // If this action was explicitly requested, then don't
5041                    // remove things that have it.
5042                    continue;
5043                }
5044                for (int j=i+1; j<N; j++) {
5045                    final ResolveInfo rij = results.get(j);
5046                    if (rij.filter != null && rij.filter.hasAction(action)) {
5047                        results.remove(j);
5048                        if (DEBUG_INTENT_MATCHING) Log.v(
5049                            TAG, "Removing duplicate item from " + j
5050                            + " due to action " + action + " at " + i);
5051                        j--;
5052                        N--;
5053                    }
5054                }
5055            }
5056
5057            // If the caller didn't request filter information, drop it now
5058            // so we don't have to marshall/unmarshall it.
5059            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5060                rii.filter = null;
5061            }
5062        }
5063
5064        // Filter out the caller activity if so requested.
5065        if (caller != null) {
5066            N = results.size();
5067            for (int i=0; i<N; i++) {
5068                ActivityInfo ainfo = results.get(i).activityInfo;
5069                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5070                        && caller.getClassName().equals(ainfo.name)) {
5071                    results.remove(i);
5072                    break;
5073                }
5074            }
5075        }
5076
5077        // If the caller didn't request filter information,
5078        // drop them now so we don't have to
5079        // marshall/unmarshall it.
5080        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5081            N = results.size();
5082            for (int i=0; i<N; i++) {
5083                results.get(i).filter = null;
5084            }
5085        }
5086
5087        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5088        return results;
5089    }
5090
5091    @Override
5092    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5093            int userId) {
5094        if (!sUserManager.exists(userId)) return Collections.emptyList();
5095        ComponentName comp = intent.getComponent();
5096        if (comp == null) {
5097            if (intent.getSelector() != null) {
5098                intent = intent.getSelector();
5099                comp = intent.getComponent();
5100            }
5101        }
5102        if (comp != null) {
5103            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5104            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5105            if (ai != null) {
5106                ResolveInfo ri = new ResolveInfo();
5107                ri.activityInfo = ai;
5108                list.add(ri);
5109            }
5110            return list;
5111        }
5112
5113        // reader
5114        synchronized (mPackages) {
5115            String pkgName = intent.getPackage();
5116            if (pkgName == null) {
5117                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5118            }
5119            final PackageParser.Package pkg = mPackages.get(pkgName);
5120            if (pkg != null) {
5121                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5122                        userId);
5123            }
5124            return null;
5125        }
5126    }
5127
5128    @Override
5129    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5130        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5131        if (!sUserManager.exists(userId)) return null;
5132        if (query != null) {
5133            if (query.size() >= 1) {
5134                // If there is more than one service with the same priority,
5135                // just arbitrarily pick the first one.
5136                return query.get(0);
5137            }
5138        }
5139        return null;
5140    }
5141
5142    @Override
5143    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5144            int userId) {
5145        if (!sUserManager.exists(userId)) return Collections.emptyList();
5146        ComponentName comp = intent.getComponent();
5147        if (comp == null) {
5148            if (intent.getSelector() != null) {
5149                intent = intent.getSelector();
5150                comp = intent.getComponent();
5151            }
5152        }
5153        if (comp != null) {
5154            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5155            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5156            if (si != null) {
5157                final ResolveInfo ri = new ResolveInfo();
5158                ri.serviceInfo = si;
5159                list.add(ri);
5160            }
5161            return list;
5162        }
5163
5164        // reader
5165        synchronized (mPackages) {
5166            String pkgName = intent.getPackage();
5167            if (pkgName == null) {
5168                return mServices.queryIntent(intent, resolvedType, flags, userId);
5169            }
5170            final PackageParser.Package pkg = mPackages.get(pkgName);
5171            if (pkg != null) {
5172                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5173                        userId);
5174            }
5175            return null;
5176        }
5177    }
5178
5179    @Override
5180    public List<ResolveInfo> queryIntentContentProviders(
5181            Intent intent, String resolvedType, int flags, int userId) {
5182        if (!sUserManager.exists(userId)) return Collections.emptyList();
5183        ComponentName comp = intent.getComponent();
5184        if (comp == null) {
5185            if (intent.getSelector() != null) {
5186                intent = intent.getSelector();
5187                comp = intent.getComponent();
5188            }
5189        }
5190        if (comp != null) {
5191            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5192            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5193            if (pi != null) {
5194                final ResolveInfo ri = new ResolveInfo();
5195                ri.providerInfo = pi;
5196                list.add(ri);
5197            }
5198            return list;
5199        }
5200
5201        // reader
5202        synchronized (mPackages) {
5203            String pkgName = intent.getPackage();
5204            if (pkgName == null) {
5205                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5206            }
5207            final PackageParser.Package pkg = mPackages.get(pkgName);
5208            if (pkg != null) {
5209                return mProviders.queryIntentForPackage(
5210                        intent, resolvedType, flags, pkg.providers, userId);
5211            }
5212            return null;
5213        }
5214    }
5215
5216    @Override
5217    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5218        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5219
5220        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5221
5222        // writer
5223        synchronized (mPackages) {
5224            ArrayList<PackageInfo> list;
5225            if (listUninstalled) {
5226                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5227                for (PackageSetting ps : mSettings.mPackages.values()) {
5228                    PackageInfo pi;
5229                    if (ps.pkg != null) {
5230                        pi = generatePackageInfo(ps.pkg, flags, userId);
5231                    } else {
5232                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5233                    }
5234                    if (pi != null) {
5235                        list.add(pi);
5236                    }
5237                }
5238            } else {
5239                list = new ArrayList<PackageInfo>(mPackages.size());
5240                for (PackageParser.Package p : mPackages.values()) {
5241                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5242                    if (pi != null) {
5243                        list.add(pi);
5244                    }
5245                }
5246            }
5247
5248            return new ParceledListSlice<PackageInfo>(list);
5249        }
5250    }
5251
5252    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5253            String[] permissions, boolean[] tmp, int flags, int userId) {
5254        int numMatch = 0;
5255        final PermissionsState permissionsState = ps.getPermissionsState();
5256        for (int i=0; i<permissions.length; i++) {
5257            final String permission = permissions[i];
5258            if (permissionsState.hasPermission(permission, userId)) {
5259                tmp[i] = true;
5260                numMatch++;
5261            } else {
5262                tmp[i] = false;
5263            }
5264        }
5265        if (numMatch == 0) {
5266            return;
5267        }
5268        PackageInfo pi;
5269        if (ps.pkg != null) {
5270            pi = generatePackageInfo(ps.pkg, flags, userId);
5271        } else {
5272            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5273        }
5274        // The above might return null in cases of uninstalled apps or install-state
5275        // skew across users/profiles.
5276        if (pi != null) {
5277            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5278                if (numMatch == permissions.length) {
5279                    pi.requestedPermissions = permissions;
5280                } else {
5281                    pi.requestedPermissions = new String[numMatch];
5282                    numMatch = 0;
5283                    for (int i=0; i<permissions.length; i++) {
5284                        if (tmp[i]) {
5285                            pi.requestedPermissions[numMatch] = permissions[i];
5286                            numMatch++;
5287                        }
5288                    }
5289                }
5290            }
5291            list.add(pi);
5292        }
5293    }
5294
5295    @Override
5296    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5297            String[] permissions, int flags, int userId) {
5298        if (!sUserManager.exists(userId)) return null;
5299        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5300
5301        // writer
5302        synchronized (mPackages) {
5303            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5304            boolean[] tmpBools = new boolean[permissions.length];
5305            if (listUninstalled) {
5306                for (PackageSetting ps : mSettings.mPackages.values()) {
5307                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5308                }
5309            } else {
5310                for (PackageParser.Package pkg : mPackages.values()) {
5311                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5312                    if (ps != null) {
5313                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5314                                userId);
5315                    }
5316                }
5317            }
5318
5319            return new ParceledListSlice<PackageInfo>(list);
5320        }
5321    }
5322
5323    @Override
5324    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5325        if (!sUserManager.exists(userId)) return null;
5326        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5327
5328        // writer
5329        synchronized (mPackages) {
5330            ArrayList<ApplicationInfo> list;
5331            if (listUninstalled) {
5332                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5333                for (PackageSetting ps : mSettings.mPackages.values()) {
5334                    ApplicationInfo ai;
5335                    if (ps.pkg != null) {
5336                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5337                                ps.readUserState(userId), userId);
5338                    } else {
5339                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5340                    }
5341                    if (ai != null) {
5342                        list.add(ai);
5343                    }
5344                }
5345            } else {
5346                list = new ArrayList<ApplicationInfo>(mPackages.size());
5347                for (PackageParser.Package p : mPackages.values()) {
5348                    if (p.mExtras != null) {
5349                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5350                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5351                        if (ai != null) {
5352                            list.add(ai);
5353                        }
5354                    }
5355                }
5356            }
5357
5358            return new ParceledListSlice<ApplicationInfo>(list);
5359        }
5360    }
5361
5362    public List<ApplicationInfo> getPersistentApplications(int flags) {
5363        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5364
5365        // reader
5366        synchronized (mPackages) {
5367            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5368            final int userId = UserHandle.getCallingUserId();
5369            while (i.hasNext()) {
5370                final PackageParser.Package p = i.next();
5371                if (p.applicationInfo != null
5372                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5373                        && (!mSafeMode || isSystemApp(p))) {
5374                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5375                    if (ps != null) {
5376                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5377                                ps.readUserState(userId), userId);
5378                        if (ai != null) {
5379                            finalList.add(ai);
5380                        }
5381                    }
5382                }
5383            }
5384        }
5385
5386        return finalList;
5387    }
5388
5389    @Override
5390    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5391        if (!sUserManager.exists(userId)) return null;
5392        // reader
5393        synchronized (mPackages) {
5394            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5395            PackageSetting ps = provider != null
5396                    ? mSettings.mPackages.get(provider.owner.packageName)
5397                    : null;
5398            return ps != null
5399                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5400                    && (!mSafeMode || (provider.info.applicationInfo.flags
5401                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5402                    ? PackageParser.generateProviderInfo(provider, flags,
5403                            ps.readUserState(userId), userId)
5404                    : null;
5405        }
5406    }
5407
5408    /**
5409     * @deprecated
5410     */
5411    @Deprecated
5412    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5413        // reader
5414        synchronized (mPackages) {
5415            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5416                    .entrySet().iterator();
5417            final int userId = UserHandle.getCallingUserId();
5418            while (i.hasNext()) {
5419                Map.Entry<String, PackageParser.Provider> entry = i.next();
5420                PackageParser.Provider p = entry.getValue();
5421                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5422
5423                if (ps != null && p.syncable
5424                        && (!mSafeMode || (p.info.applicationInfo.flags
5425                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5426                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5427                            ps.readUserState(userId), userId);
5428                    if (info != null) {
5429                        outNames.add(entry.getKey());
5430                        outInfo.add(info);
5431                    }
5432                }
5433            }
5434        }
5435    }
5436
5437    @Override
5438    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5439            int uid, int flags) {
5440        ArrayList<ProviderInfo> finalList = null;
5441        // reader
5442        synchronized (mPackages) {
5443            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5444            final int userId = processName != null ?
5445                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5446            while (i.hasNext()) {
5447                final PackageParser.Provider p = i.next();
5448                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5449                if (ps != null && p.info.authority != null
5450                        && (processName == null
5451                                || (p.info.processName.equals(processName)
5452                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5453                        && mSettings.isEnabledLPr(p.info, flags, userId)
5454                        && (!mSafeMode
5455                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5456                    if (finalList == null) {
5457                        finalList = new ArrayList<ProviderInfo>(3);
5458                    }
5459                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5460                            ps.readUserState(userId), userId);
5461                    if (info != null) {
5462                        finalList.add(info);
5463                    }
5464                }
5465            }
5466        }
5467
5468        if (finalList != null) {
5469            Collections.sort(finalList, mProviderInitOrderSorter);
5470            return new ParceledListSlice<ProviderInfo>(finalList);
5471        }
5472
5473        return null;
5474    }
5475
5476    @Override
5477    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5478            int flags) {
5479        // reader
5480        synchronized (mPackages) {
5481            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5482            return PackageParser.generateInstrumentationInfo(i, flags);
5483        }
5484    }
5485
5486    @Override
5487    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5488            int flags) {
5489        ArrayList<InstrumentationInfo> finalList =
5490            new ArrayList<InstrumentationInfo>();
5491
5492        // reader
5493        synchronized (mPackages) {
5494            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5495            while (i.hasNext()) {
5496                final PackageParser.Instrumentation p = i.next();
5497                if (targetPackage == null
5498                        || targetPackage.equals(p.info.targetPackage)) {
5499                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5500                            flags);
5501                    if (ii != null) {
5502                        finalList.add(ii);
5503                    }
5504                }
5505            }
5506        }
5507
5508        return finalList;
5509    }
5510
5511    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5512        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5513        if (overlays == null) {
5514            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5515            return;
5516        }
5517        for (PackageParser.Package opkg : overlays.values()) {
5518            // Not much to do if idmap fails: we already logged the error
5519            // and we certainly don't want to abort installation of pkg simply
5520            // because an overlay didn't fit properly. For these reasons,
5521            // ignore the return value of createIdmapForPackagePairLI.
5522            createIdmapForPackagePairLI(pkg, opkg);
5523        }
5524    }
5525
5526    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5527            PackageParser.Package opkg) {
5528        if (!opkg.mTrustedOverlay) {
5529            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5530                    opkg.baseCodePath + ": overlay not trusted");
5531            return false;
5532        }
5533        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5534        if (overlaySet == null) {
5535            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5536                    opkg.baseCodePath + " but target package has no known overlays");
5537            return false;
5538        }
5539        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5540        // TODO: generate idmap for split APKs
5541        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5542            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5543                    + opkg.baseCodePath);
5544            return false;
5545        }
5546        PackageParser.Package[] overlayArray =
5547            overlaySet.values().toArray(new PackageParser.Package[0]);
5548        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5549            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5550                return p1.mOverlayPriority - p2.mOverlayPriority;
5551            }
5552        };
5553        Arrays.sort(overlayArray, cmp);
5554
5555        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5556        int i = 0;
5557        for (PackageParser.Package p : overlayArray) {
5558            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5559        }
5560        return true;
5561    }
5562
5563    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5564        final File[] files = dir.listFiles();
5565        if (ArrayUtils.isEmpty(files)) {
5566            Log.d(TAG, "No files in app dir " + dir);
5567            return;
5568        }
5569
5570        if (DEBUG_PACKAGE_SCANNING) {
5571            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5572                    + " flags=0x" + Integer.toHexString(parseFlags));
5573        }
5574
5575        for (File file : files) {
5576            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5577                    && !PackageInstallerService.isStageName(file.getName());
5578            if (!isPackage) {
5579                // Ignore entries which are not packages
5580                continue;
5581            }
5582            try {
5583                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5584                        scanFlags, currentTime, null);
5585            } catch (PackageManagerException e) {
5586                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5587
5588                // Delete invalid userdata apps
5589                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5590                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5591                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5592                    if (file.isDirectory()) {
5593                        mInstaller.rmPackageDir(file.getAbsolutePath());
5594                    } else {
5595                        file.delete();
5596                    }
5597                }
5598            }
5599        }
5600    }
5601
5602    private static File getSettingsProblemFile() {
5603        File dataDir = Environment.getDataDirectory();
5604        File systemDir = new File(dataDir, "system");
5605        File fname = new File(systemDir, "uiderrors.txt");
5606        return fname;
5607    }
5608
5609    static void reportSettingsProblem(int priority, String msg) {
5610        logCriticalInfo(priority, msg);
5611    }
5612
5613    static void logCriticalInfo(int priority, String msg) {
5614        Slog.println(priority, TAG, msg);
5615        EventLogTags.writePmCriticalInfo(msg);
5616        try {
5617            File fname = getSettingsProblemFile();
5618            FileOutputStream out = new FileOutputStream(fname, true);
5619            PrintWriter pw = new FastPrintWriter(out);
5620            SimpleDateFormat formatter = new SimpleDateFormat();
5621            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5622            pw.println(dateString + ": " + msg);
5623            pw.close();
5624            FileUtils.setPermissions(
5625                    fname.toString(),
5626                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5627                    -1, -1);
5628        } catch (java.io.IOException e) {
5629        }
5630    }
5631
5632    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5633            PackageParser.Package pkg, File srcFile, int parseFlags)
5634            throws PackageManagerException {
5635        if (ps != null
5636                && ps.codePath.equals(srcFile)
5637                && ps.timeStamp == srcFile.lastModified()
5638                && !isCompatSignatureUpdateNeeded(pkg)
5639                && !isRecoverSignatureUpdateNeeded(pkg)) {
5640            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5641            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5642            ArraySet<PublicKey> signingKs;
5643            synchronized (mPackages) {
5644                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5645            }
5646            if (ps.signatures.mSignatures != null
5647                    && ps.signatures.mSignatures.length != 0
5648                    && signingKs != null) {
5649                // Optimization: reuse the existing cached certificates
5650                // if the package appears to be unchanged.
5651                pkg.mSignatures = ps.signatures.mSignatures;
5652                pkg.mSigningKeys = signingKs;
5653                return;
5654            }
5655
5656            Slog.w(TAG, "PackageSetting for " + ps.name
5657                    + " is missing signatures.  Collecting certs again to recover them.");
5658        } else {
5659            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5660        }
5661
5662        try {
5663            pp.collectCertificates(pkg, parseFlags);
5664            pp.collectManifestDigest(pkg);
5665        } catch (PackageParserException e) {
5666            throw PackageManagerException.from(e);
5667        }
5668    }
5669
5670    /*
5671     *  Scan a package and return the newly parsed package.
5672     *  Returns null in case of errors and the error code is stored in mLastScanError
5673     */
5674    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5675            long currentTime, UserHandle user) throws PackageManagerException {
5676        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5677        parseFlags |= mDefParseFlags;
5678        PackageParser pp = new PackageParser();
5679        pp.setSeparateProcesses(mSeparateProcesses);
5680        pp.setOnlyCoreApps(mOnlyCore);
5681        pp.setDisplayMetrics(mMetrics);
5682
5683        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5684            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5685        }
5686
5687        final PackageParser.Package pkg;
5688        try {
5689            pkg = pp.parsePackage(scanFile, parseFlags);
5690        } catch (PackageParserException e) {
5691            throw PackageManagerException.from(e);
5692        }
5693
5694        PackageSetting ps = null;
5695        PackageSetting updatedPkg;
5696        // reader
5697        synchronized (mPackages) {
5698            // Look to see if we already know about this package.
5699            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5700            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5701                // This package has been renamed to its original name.  Let's
5702                // use that.
5703                ps = mSettings.peekPackageLPr(oldName);
5704            }
5705            // If there was no original package, see one for the real package name.
5706            if (ps == null) {
5707                ps = mSettings.peekPackageLPr(pkg.packageName);
5708            }
5709            // Check to see if this package could be hiding/updating a system
5710            // package.  Must look for it either under the original or real
5711            // package name depending on our state.
5712            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5713            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5714        }
5715        boolean updatedPkgBetter = false;
5716        // First check if this is a system package that may involve an update
5717        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5718            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5719            // it needs to drop FLAG_PRIVILEGED.
5720            if (locationIsPrivileged(scanFile)) {
5721                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5722            } else {
5723                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5724            }
5725
5726            if (ps != null && !ps.codePath.equals(scanFile)) {
5727                // The path has changed from what was last scanned...  check the
5728                // version of the new path against what we have stored to determine
5729                // what to do.
5730                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5731                if (pkg.mVersionCode <= ps.versionCode) {
5732                    // The system package has been updated and the code path does not match
5733                    // Ignore entry. Skip it.
5734                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5735                            + " ignored: updated version " + ps.versionCode
5736                            + " better than this " + pkg.mVersionCode);
5737                    if (!updatedPkg.codePath.equals(scanFile)) {
5738                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5739                                + ps.name + " changing from " + updatedPkg.codePathString
5740                                + " to " + scanFile);
5741                        updatedPkg.codePath = scanFile;
5742                        updatedPkg.codePathString = scanFile.toString();
5743                        updatedPkg.resourcePath = scanFile;
5744                        updatedPkg.resourcePathString = scanFile.toString();
5745                    }
5746                    updatedPkg.pkg = pkg;
5747                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5748                            "Package " + ps.name + " at " + scanFile
5749                                    + " ignored: updated version " + ps.versionCode
5750                                    + " better than this " + pkg.mVersionCode);
5751                } else {
5752                    // The current app on the system partition is better than
5753                    // what we have updated to on the data partition; switch
5754                    // back to the system partition version.
5755                    // At this point, its safely assumed that package installation for
5756                    // apps in system partition will go through. If not there won't be a working
5757                    // version of the app
5758                    // writer
5759                    synchronized (mPackages) {
5760                        // Just remove the loaded entries from package lists.
5761                        mPackages.remove(ps.name);
5762                    }
5763
5764                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5765                            + " reverting from " + ps.codePathString
5766                            + ": new version " + pkg.mVersionCode
5767                            + " better than installed " + ps.versionCode);
5768
5769                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5770                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5771                    synchronized (mInstallLock) {
5772                        args.cleanUpResourcesLI();
5773                    }
5774                    synchronized (mPackages) {
5775                        mSettings.enableSystemPackageLPw(ps.name);
5776                    }
5777                    updatedPkgBetter = true;
5778                }
5779            }
5780        }
5781
5782        if (updatedPkg != null) {
5783            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5784            // initially
5785            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5786
5787            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5788            // flag set initially
5789            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5790                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5791            }
5792        }
5793
5794        // Verify certificates against what was last scanned
5795        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5796
5797        /*
5798         * A new system app appeared, but we already had a non-system one of the
5799         * same name installed earlier.
5800         */
5801        boolean shouldHideSystemApp = false;
5802        if (updatedPkg == null && ps != null
5803                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5804            /*
5805             * Check to make sure the signatures match first. If they don't,
5806             * wipe the installed application and its data.
5807             */
5808            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5809                    != PackageManager.SIGNATURE_MATCH) {
5810                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5811                        + " signatures don't match existing userdata copy; removing");
5812                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5813                ps = null;
5814            } else {
5815                /*
5816                 * If the newly-added system app is an older version than the
5817                 * already installed version, hide it. It will be scanned later
5818                 * and re-added like an update.
5819                 */
5820                if (pkg.mVersionCode <= ps.versionCode) {
5821                    shouldHideSystemApp = true;
5822                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5823                            + " but new version " + pkg.mVersionCode + " better than installed "
5824                            + ps.versionCode + "; hiding system");
5825                } else {
5826                    /*
5827                     * The newly found system app is a newer version that the
5828                     * one previously installed. Simply remove the
5829                     * already-installed application and replace it with our own
5830                     * while keeping the application data.
5831                     */
5832                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5833                            + " reverting from " + ps.codePathString + ": new version "
5834                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5835                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5836                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5837                    synchronized (mInstallLock) {
5838                        args.cleanUpResourcesLI();
5839                    }
5840                }
5841            }
5842        }
5843
5844        // The apk is forward locked (not public) if its code and resources
5845        // are kept in different files. (except for app in either system or
5846        // vendor path).
5847        // TODO grab this value from PackageSettings
5848        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5849            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5850                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5851            }
5852        }
5853
5854        // TODO: extend to support forward-locked splits
5855        String resourcePath = null;
5856        String baseResourcePath = null;
5857        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5858            if (ps != null && ps.resourcePathString != null) {
5859                resourcePath = ps.resourcePathString;
5860                baseResourcePath = ps.resourcePathString;
5861            } else {
5862                // Should not happen at all. Just log an error.
5863                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5864            }
5865        } else {
5866            resourcePath = pkg.codePath;
5867            baseResourcePath = pkg.baseCodePath;
5868        }
5869
5870        // Set application objects path explicitly.
5871        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5872        pkg.applicationInfo.setCodePath(pkg.codePath);
5873        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5874        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5875        pkg.applicationInfo.setResourcePath(resourcePath);
5876        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5877        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5878
5879        // Note that we invoke the following method only if we are about to unpack an application
5880        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5881                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5882
5883        /*
5884         * If the system app should be overridden by a previously installed
5885         * data, hide the system app now and let the /data/app scan pick it up
5886         * again.
5887         */
5888        if (shouldHideSystemApp) {
5889            synchronized (mPackages) {
5890                /*
5891                 * We have to grant systems permissions before we hide, because
5892                 * grantPermissions will assume the package update is trying to
5893                 * expand its permissions.
5894                 */
5895                grantPermissionsLPw(pkg, true, pkg.packageName);
5896                mSettings.disableSystemPackageLPw(pkg.packageName);
5897            }
5898        }
5899
5900        return scannedPkg;
5901    }
5902
5903    private static String fixProcessName(String defProcessName,
5904            String processName, int uid) {
5905        if (processName == null) {
5906            return defProcessName;
5907        }
5908        return processName;
5909    }
5910
5911    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5912            throws PackageManagerException {
5913        if (pkgSetting.signatures.mSignatures != null) {
5914            // Already existing package. Make sure signatures match
5915            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5916                    == PackageManager.SIGNATURE_MATCH;
5917            if (!match) {
5918                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5919                        == PackageManager.SIGNATURE_MATCH;
5920            }
5921            if (!match) {
5922                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5923                        == PackageManager.SIGNATURE_MATCH;
5924            }
5925            if (!match) {
5926                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5927                        + pkg.packageName + " signatures do not match the "
5928                        + "previously installed version; ignoring!");
5929            }
5930        }
5931
5932        // Check for shared user signatures
5933        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5934            // Already existing package. Make sure signatures match
5935            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5936                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5937            if (!match) {
5938                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5939                        == PackageManager.SIGNATURE_MATCH;
5940            }
5941            if (!match) {
5942                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5943                        == PackageManager.SIGNATURE_MATCH;
5944            }
5945            if (!match) {
5946                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5947                        "Package " + pkg.packageName
5948                        + " has no signatures that match those in shared user "
5949                        + pkgSetting.sharedUser.name + "; ignoring!");
5950            }
5951        }
5952    }
5953
5954    /**
5955     * Enforces that only the system UID or root's UID can call a method exposed
5956     * via Binder.
5957     *
5958     * @param message used as message if SecurityException is thrown
5959     * @throws SecurityException if the caller is not system or root
5960     */
5961    private static final void enforceSystemOrRoot(String message) {
5962        final int uid = Binder.getCallingUid();
5963        if (uid != Process.SYSTEM_UID && uid != 0) {
5964            throw new SecurityException(message);
5965        }
5966    }
5967
5968    @Override
5969    public void performBootDexOpt() {
5970        enforceSystemOrRoot("Only the system can request dexopt be performed");
5971
5972        // Before everything else, see whether we need to fstrim.
5973        try {
5974            IMountService ms = PackageHelper.getMountService();
5975            if (ms != null) {
5976                final boolean isUpgrade = isUpgrade();
5977                boolean doTrim = isUpgrade;
5978                if (doTrim) {
5979                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5980                } else {
5981                    final long interval = android.provider.Settings.Global.getLong(
5982                            mContext.getContentResolver(),
5983                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5984                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5985                    if (interval > 0) {
5986                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5987                        if (timeSinceLast > interval) {
5988                            doTrim = true;
5989                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5990                                    + "; running immediately");
5991                        }
5992                    }
5993                }
5994                if (doTrim) {
5995                    if (!isFirstBoot()) {
5996                        try {
5997                            ActivityManagerNative.getDefault().showBootMessage(
5998                                    mContext.getResources().getString(
5999                                            R.string.android_upgrading_fstrim), true);
6000                        } catch (RemoteException e) {
6001                        }
6002                    }
6003                    ms.runMaintenance();
6004                }
6005            } else {
6006                Slog.e(TAG, "Mount service unavailable!");
6007            }
6008        } catch (RemoteException e) {
6009            // Can't happen; MountService is local
6010        }
6011
6012        final ArraySet<PackageParser.Package> pkgs;
6013        synchronized (mPackages) {
6014            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6015        }
6016
6017        if (pkgs != null) {
6018            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6019            // in case the device runs out of space.
6020            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6021            // Give priority to core apps.
6022            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6023                PackageParser.Package pkg = it.next();
6024                if (pkg.coreApp) {
6025                    if (DEBUG_DEXOPT) {
6026                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6027                    }
6028                    sortedPkgs.add(pkg);
6029                    it.remove();
6030                }
6031            }
6032            // Give priority to system apps that listen for pre boot complete.
6033            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6034            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6035            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6036                PackageParser.Package pkg = it.next();
6037                if (pkgNames.contains(pkg.packageName)) {
6038                    if (DEBUG_DEXOPT) {
6039                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6040                    }
6041                    sortedPkgs.add(pkg);
6042                    it.remove();
6043                }
6044            }
6045            // Give priority to system apps.
6046            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6047                PackageParser.Package pkg = it.next();
6048                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6049                    if (DEBUG_DEXOPT) {
6050                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6051                    }
6052                    sortedPkgs.add(pkg);
6053                    it.remove();
6054                }
6055            }
6056            // Give priority to updated system apps.
6057            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6058                PackageParser.Package pkg = it.next();
6059                if (pkg.isUpdatedSystemApp()) {
6060                    if (DEBUG_DEXOPT) {
6061                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6062                    }
6063                    sortedPkgs.add(pkg);
6064                    it.remove();
6065                }
6066            }
6067            // Give priority to apps that listen for boot complete.
6068            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6069            pkgNames = getPackageNamesForIntent(intent);
6070            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6071                PackageParser.Package pkg = it.next();
6072                if (pkgNames.contains(pkg.packageName)) {
6073                    if (DEBUG_DEXOPT) {
6074                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6075                    }
6076                    sortedPkgs.add(pkg);
6077                    it.remove();
6078                }
6079            }
6080            // Filter out packages that aren't recently used.
6081            filterRecentlyUsedApps(pkgs);
6082            // Add all remaining apps.
6083            for (PackageParser.Package pkg : pkgs) {
6084                if (DEBUG_DEXOPT) {
6085                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6086                }
6087                sortedPkgs.add(pkg);
6088            }
6089
6090            // If we want to be lazy, filter everything that wasn't recently used.
6091            if (mLazyDexOpt) {
6092                filterRecentlyUsedApps(sortedPkgs);
6093            }
6094
6095            int i = 0;
6096            int total = sortedPkgs.size();
6097            File dataDir = Environment.getDataDirectory();
6098            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6099            if (lowThreshold == 0) {
6100                throw new IllegalStateException("Invalid low memory threshold");
6101            }
6102            for (PackageParser.Package pkg : sortedPkgs) {
6103                long usableSpace = dataDir.getUsableSpace();
6104                if (usableSpace < lowThreshold) {
6105                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6106                    break;
6107                }
6108                performBootDexOpt(pkg, ++i, total);
6109            }
6110        }
6111    }
6112
6113    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6114        // Filter out packages that aren't recently used.
6115        //
6116        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6117        // should do a full dexopt.
6118        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6119            int total = pkgs.size();
6120            int skipped = 0;
6121            long now = System.currentTimeMillis();
6122            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6123                PackageParser.Package pkg = i.next();
6124                long then = pkg.mLastPackageUsageTimeInMills;
6125                if (then + mDexOptLRUThresholdInMills < now) {
6126                    if (DEBUG_DEXOPT) {
6127                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6128                              ((then == 0) ? "never" : new Date(then)));
6129                    }
6130                    i.remove();
6131                    skipped++;
6132                }
6133            }
6134            if (DEBUG_DEXOPT) {
6135                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6136            }
6137        }
6138    }
6139
6140    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6141        List<ResolveInfo> ris = null;
6142        try {
6143            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6144                    intent, null, 0, UserHandle.USER_OWNER);
6145        } catch (RemoteException e) {
6146        }
6147        ArraySet<String> pkgNames = new ArraySet<String>();
6148        if (ris != null) {
6149            for (ResolveInfo ri : ris) {
6150                pkgNames.add(ri.activityInfo.packageName);
6151            }
6152        }
6153        return pkgNames;
6154    }
6155
6156    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6157        if (DEBUG_DEXOPT) {
6158            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6159        }
6160        if (!isFirstBoot()) {
6161            try {
6162                ActivityManagerNative.getDefault().showBootMessage(
6163                        mContext.getResources().getString(R.string.android_upgrading_apk,
6164                                curr, total), true);
6165            } catch (RemoteException e) {
6166            }
6167        }
6168        PackageParser.Package p = pkg;
6169        synchronized (mInstallLock) {
6170            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6171                    false /* force dex */, false /* defer */, true /* include dependencies */);
6172        }
6173    }
6174
6175    @Override
6176    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6177        return performDexOpt(packageName, instructionSet, false);
6178    }
6179
6180    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6181        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6182        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6183        if (!dexopt && !updateUsage) {
6184            // We aren't going to dexopt or update usage, so bail early.
6185            return false;
6186        }
6187        PackageParser.Package p;
6188        final String targetInstructionSet;
6189        synchronized (mPackages) {
6190            p = mPackages.get(packageName);
6191            if (p == null) {
6192                return false;
6193            }
6194            if (updateUsage) {
6195                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6196            }
6197            mPackageUsage.write(false);
6198            if (!dexopt) {
6199                // We aren't going to dexopt, so bail early.
6200                return false;
6201            }
6202
6203            targetInstructionSet = instructionSet != null ? instructionSet :
6204                    getPrimaryInstructionSet(p.applicationInfo);
6205            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6206                return false;
6207            }
6208        }
6209        long callingId = Binder.clearCallingIdentity();
6210        try {
6211            synchronized (mInstallLock) {
6212                final String[] instructionSets = new String[] { targetInstructionSet };
6213                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6214                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6215                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6216            }
6217        } finally {
6218            Binder.restoreCallingIdentity(callingId);
6219        }
6220    }
6221
6222    public ArraySet<String> getPackagesThatNeedDexOpt() {
6223        ArraySet<String> pkgs = null;
6224        synchronized (mPackages) {
6225            for (PackageParser.Package p : mPackages.values()) {
6226                if (DEBUG_DEXOPT) {
6227                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6228                }
6229                if (!p.mDexOptPerformed.isEmpty()) {
6230                    continue;
6231                }
6232                if (pkgs == null) {
6233                    pkgs = new ArraySet<String>();
6234                }
6235                pkgs.add(p.packageName);
6236            }
6237        }
6238        return pkgs;
6239    }
6240
6241    public void shutdown() {
6242        mPackageUsage.write(true);
6243    }
6244
6245    @Override
6246    public void forceDexOpt(String packageName) {
6247        enforceSystemOrRoot("forceDexOpt");
6248
6249        PackageParser.Package pkg;
6250        synchronized (mPackages) {
6251            pkg = mPackages.get(packageName);
6252            if (pkg == null) {
6253                throw new IllegalArgumentException("Missing package: " + packageName);
6254            }
6255        }
6256
6257        synchronized (mInstallLock) {
6258            final String[] instructionSets = new String[] {
6259                    getPrimaryInstructionSet(pkg.applicationInfo) };
6260            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6261                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6262            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6263                throw new IllegalStateException("Failed to dexopt: " + res);
6264            }
6265        }
6266    }
6267
6268    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6269        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6270            Slog.w(TAG, "Unable to update from " + oldPkg.name
6271                    + " to " + newPkg.packageName
6272                    + ": old package not in system partition");
6273            return false;
6274        } else if (mPackages.get(oldPkg.name) != null) {
6275            Slog.w(TAG, "Unable to update from " + oldPkg.name
6276                    + " to " + newPkg.packageName
6277                    + ": old package still exists");
6278            return false;
6279        }
6280        return true;
6281    }
6282
6283    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6284        int[] users = sUserManager.getUserIds();
6285        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6286        if (res < 0) {
6287            return res;
6288        }
6289        for (int user : users) {
6290            if (user != 0) {
6291                res = mInstaller.createUserData(volumeUuid, packageName,
6292                        UserHandle.getUid(user, uid), user, seinfo);
6293                if (res < 0) {
6294                    return res;
6295                }
6296            }
6297        }
6298        return res;
6299    }
6300
6301    private int removeDataDirsLI(String volumeUuid, String packageName) {
6302        int[] users = sUserManager.getUserIds();
6303        int res = 0;
6304        for (int user : users) {
6305            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6306            if (resInner < 0) {
6307                res = resInner;
6308            }
6309        }
6310
6311        return res;
6312    }
6313
6314    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6315        int[] users = sUserManager.getUserIds();
6316        int res = 0;
6317        for (int user : users) {
6318            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6319            if (resInner < 0) {
6320                res = resInner;
6321            }
6322        }
6323        return res;
6324    }
6325
6326    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6327            PackageParser.Package changingLib) {
6328        if (file.path != null) {
6329            usesLibraryFiles.add(file.path);
6330            return;
6331        }
6332        PackageParser.Package p = mPackages.get(file.apk);
6333        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6334            // If we are doing this while in the middle of updating a library apk,
6335            // then we need to make sure to use that new apk for determining the
6336            // dependencies here.  (We haven't yet finished committing the new apk
6337            // to the package manager state.)
6338            if (p == null || p.packageName.equals(changingLib.packageName)) {
6339                p = changingLib;
6340            }
6341        }
6342        if (p != null) {
6343            usesLibraryFiles.addAll(p.getAllCodePaths());
6344        }
6345    }
6346
6347    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6348            PackageParser.Package changingLib) throws PackageManagerException {
6349        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6350            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6351            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6352            for (int i=0; i<N; i++) {
6353                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6354                if (file == null) {
6355                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6356                            "Package " + pkg.packageName + " requires unavailable shared library "
6357                            + pkg.usesLibraries.get(i) + "; failing!");
6358                }
6359                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6360            }
6361            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6362            for (int i=0; i<N; i++) {
6363                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6364                if (file == null) {
6365                    Slog.w(TAG, "Package " + pkg.packageName
6366                            + " desires unavailable shared library "
6367                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6368                } else {
6369                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6370                }
6371            }
6372            N = usesLibraryFiles.size();
6373            if (N > 0) {
6374                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6375            } else {
6376                pkg.usesLibraryFiles = null;
6377            }
6378        }
6379    }
6380
6381    private static boolean hasString(List<String> list, List<String> which) {
6382        if (list == null) {
6383            return false;
6384        }
6385        for (int i=list.size()-1; i>=0; i--) {
6386            for (int j=which.size()-1; j>=0; j--) {
6387                if (which.get(j).equals(list.get(i))) {
6388                    return true;
6389                }
6390            }
6391        }
6392        return false;
6393    }
6394
6395    private void updateAllSharedLibrariesLPw() {
6396        for (PackageParser.Package pkg : mPackages.values()) {
6397            try {
6398                updateSharedLibrariesLPw(pkg, null);
6399            } catch (PackageManagerException e) {
6400                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6401            }
6402        }
6403    }
6404
6405    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6406            PackageParser.Package changingPkg) {
6407        ArrayList<PackageParser.Package> res = null;
6408        for (PackageParser.Package pkg : mPackages.values()) {
6409            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6410                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6411                if (res == null) {
6412                    res = new ArrayList<PackageParser.Package>();
6413                }
6414                res.add(pkg);
6415                try {
6416                    updateSharedLibrariesLPw(pkg, changingPkg);
6417                } catch (PackageManagerException e) {
6418                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6419                }
6420            }
6421        }
6422        return res;
6423    }
6424
6425    /**
6426     * Derive the value of the {@code cpuAbiOverride} based on the provided
6427     * value and an optional stored value from the package settings.
6428     */
6429    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6430        String cpuAbiOverride = null;
6431
6432        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6433            cpuAbiOverride = null;
6434        } else if (abiOverride != null) {
6435            cpuAbiOverride = abiOverride;
6436        } else if (settings != null) {
6437            cpuAbiOverride = settings.cpuAbiOverrideString;
6438        }
6439
6440        return cpuAbiOverride;
6441    }
6442
6443    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6444            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6445        boolean success = false;
6446        try {
6447            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6448                    currentTime, user);
6449            success = true;
6450            return res;
6451        } finally {
6452            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6453                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6454            }
6455        }
6456    }
6457
6458    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6459            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6460        final File scanFile = new File(pkg.codePath);
6461        if (pkg.applicationInfo.getCodePath() == null ||
6462                pkg.applicationInfo.getResourcePath() == null) {
6463            // Bail out. The resource and code paths haven't been set.
6464            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6465                    "Code and resource paths haven't been set correctly");
6466        }
6467
6468        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6469            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6470        } else {
6471            // Only allow system apps to be flagged as core apps.
6472            pkg.coreApp = false;
6473        }
6474
6475        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6476            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6477        }
6478
6479        if (mCustomResolverComponentName != null &&
6480                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6481            setUpCustomResolverActivity(pkg);
6482        }
6483
6484        if (pkg.packageName.equals("android")) {
6485            synchronized (mPackages) {
6486                if (mAndroidApplication != null) {
6487                    Slog.w(TAG, "*************************************************");
6488                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6489                    Slog.w(TAG, " file=" + scanFile);
6490                    Slog.w(TAG, "*************************************************");
6491                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6492                            "Core android package being redefined.  Skipping.");
6493                }
6494
6495                // Set up information for our fall-back user intent resolution activity.
6496                mPlatformPackage = pkg;
6497                pkg.mVersionCode = mSdkVersion;
6498                mAndroidApplication = pkg.applicationInfo;
6499
6500                if (!mResolverReplaced) {
6501                    mResolveActivity.applicationInfo = mAndroidApplication;
6502                    mResolveActivity.name = ResolverActivity.class.getName();
6503                    mResolveActivity.packageName = mAndroidApplication.packageName;
6504                    mResolveActivity.processName = "system:ui";
6505                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6506                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6507                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6508                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6509                    mResolveActivity.exported = true;
6510                    mResolveActivity.enabled = true;
6511                    mResolveInfo.activityInfo = mResolveActivity;
6512                    mResolveInfo.priority = 0;
6513                    mResolveInfo.preferredOrder = 0;
6514                    mResolveInfo.match = 0;
6515                    mResolveComponentName = new ComponentName(
6516                            mAndroidApplication.packageName, mResolveActivity.name);
6517                }
6518            }
6519        }
6520
6521        if (DEBUG_PACKAGE_SCANNING) {
6522            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6523                Log.d(TAG, "Scanning package " + pkg.packageName);
6524        }
6525
6526        if (mPackages.containsKey(pkg.packageName)
6527                || mSharedLibraries.containsKey(pkg.packageName)) {
6528            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6529                    "Application package " + pkg.packageName
6530                    + " already installed.  Skipping duplicate.");
6531        }
6532
6533        // If we're only installing presumed-existing packages, require that the
6534        // scanned APK is both already known and at the path previously established
6535        // for it.  Previously unknown packages we pick up normally, but if we have an
6536        // a priori expectation about this package's install presence, enforce it.
6537        // With a singular exception for new system packages. When an OTA contains
6538        // a new system package, we allow the codepath to change from a system location
6539        // to the user-installed location. If we don't allow this change, any newer,
6540        // user-installed version of the application will be ignored.
6541        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6542            if (mExpectingBetter.containsKey(pkg.packageName)) {
6543                logCriticalInfo(Log.WARN,
6544                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6545            } else {
6546                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6547                if (known != null) {
6548                    if (DEBUG_PACKAGE_SCANNING) {
6549                        Log.d(TAG, "Examining " + pkg.codePath
6550                                + " and requiring known paths " + known.codePathString
6551                                + " & " + known.resourcePathString);
6552                    }
6553                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6554                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6555                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6556                                "Application package " + pkg.packageName
6557                                + " found at " + pkg.applicationInfo.getCodePath()
6558                                + " but expected at " + known.codePathString + "; ignoring.");
6559                    }
6560                }
6561            }
6562        }
6563
6564        // Initialize package source and resource directories
6565        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6566        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6567
6568        SharedUserSetting suid = null;
6569        PackageSetting pkgSetting = null;
6570
6571        if (!isSystemApp(pkg)) {
6572            // Only system apps can use these features.
6573            pkg.mOriginalPackages = null;
6574            pkg.mRealPackage = null;
6575            pkg.mAdoptPermissions = null;
6576        }
6577
6578        // writer
6579        synchronized (mPackages) {
6580            if (pkg.mSharedUserId != null) {
6581                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6582                if (suid == null) {
6583                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6584                            "Creating application package " + pkg.packageName
6585                            + " for shared user failed");
6586                }
6587                if (DEBUG_PACKAGE_SCANNING) {
6588                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6589                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6590                                + "): packages=" + suid.packages);
6591                }
6592            }
6593
6594            // Check if we are renaming from an original package name.
6595            PackageSetting origPackage = null;
6596            String realName = null;
6597            if (pkg.mOriginalPackages != null) {
6598                // This package may need to be renamed to a previously
6599                // installed name.  Let's check on that...
6600                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6601                if (pkg.mOriginalPackages.contains(renamed)) {
6602                    // This package had originally been installed as the
6603                    // original name, and we have already taken care of
6604                    // transitioning to the new one.  Just update the new
6605                    // one to continue using the old name.
6606                    realName = pkg.mRealPackage;
6607                    if (!pkg.packageName.equals(renamed)) {
6608                        // Callers into this function may have already taken
6609                        // care of renaming the package; only do it here if
6610                        // it is not already done.
6611                        pkg.setPackageName(renamed);
6612                    }
6613
6614                } else {
6615                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6616                        if ((origPackage = mSettings.peekPackageLPr(
6617                                pkg.mOriginalPackages.get(i))) != null) {
6618                            // We do have the package already installed under its
6619                            // original name...  should we use it?
6620                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6621                                // New package is not compatible with original.
6622                                origPackage = null;
6623                                continue;
6624                            } else if (origPackage.sharedUser != null) {
6625                                // Make sure uid is compatible between packages.
6626                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6627                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6628                                            + " to " + pkg.packageName + ": old uid "
6629                                            + origPackage.sharedUser.name
6630                                            + " differs from " + pkg.mSharedUserId);
6631                                    origPackage = null;
6632                                    continue;
6633                                }
6634                            } else {
6635                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6636                                        + pkg.packageName + " to old name " + origPackage.name);
6637                            }
6638                            break;
6639                        }
6640                    }
6641                }
6642            }
6643
6644            if (mTransferedPackages.contains(pkg.packageName)) {
6645                Slog.w(TAG, "Package " + pkg.packageName
6646                        + " was transferred to another, but its .apk remains");
6647            }
6648
6649            // Just create the setting, don't add it yet. For already existing packages
6650            // the PkgSetting exists already and doesn't have to be created.
6651            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6652                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6653                    pkg.applicationInfo.primaryCpuAbi,
6654                    pkg.applicationInfo.secondaryCpuAbi,
6655                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6656                    user, false);
6657            if (pkgSetting == null) {
6658                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6659                        "Creating application package " + pkg.packageName + " failed");
6660            }
6661
6662            if (pkgSetting.origPackage != null) {
6663                // If we are first transitioning from an original package,
6664                // fix up the new package's name now.  We need to do this after
6665                // looking up the package under its new name, so getPackageLP
6666                // can take care of fiddling things correctly.
6667                pkg.setPackageName(origPackage.name);
6668
6669                // File a report about this.
6670                String msg = "New package " + pkgSetting.realName
6671                        + " renamed to replace old package " + pkgSetting.name;
6672                reportSettingsProblem(Log.WARN, msg);
6673
6674                // Make a note of it.
6675                mTransferedPackages.add(origPackage.name);
6676
6677                // No longer need to retain this.
6678                pkgSetting.origPackage = null;
6679            }
6680
6681            if (realName != null) {
6682                // Make a note of it.
6683                mTransferedPackages.add(pkg.packageName);
6684            }
6685
6686            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6687                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6688            }
6689
6690            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6691                // Check all shared libraries and map to their actual file path.
6692                // We only do this here for apps not on a system dir, because those
6693                // are the only ones that can fail an install due to this.  We
6694                // will take care of the system apps by updating all of their
6695                // library paths after the scan is done.
6696                updateSharedLibrariesLPw(pkg, null);
6697            }
6698
6699            if (mFoundPolicyFile) {
6700                SELinuxMMAC.assignSeinfoValue(pkg);
6701            }
6702
6703            pkg.applicationInfo.uid = pkgSetting.appId;
6704            pkg.mExtras = pkgSetting;
6705            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6706                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6707                    // We just determined the app is signed correctly, so bring
6708                    // over the latest parsed certs.
6709                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6710                } else {
6711                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6712                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6713                                "Package " + pkg.packageName + " upgrade keys do not match the "
6714                                + "previously installed version");
6715                    } else {
6716                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6717                        String msg = "System package " + pkg.packageName
6718                            + " signature changed; retaining data.";
6719                        reportSettingsProblem(Log.WARN, msg);
6720                    }
6721                }
6722            } else {
6723                try {
6724                    verifySignaturesLP(pkgSetting, pkg);
6725                    // We just determined the app is signed correctly, so bring
6726                    // over the latest parsed certs.
6727                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6728                } catch (PackageManagerException e) {
6729                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6730                        throw e;
6731                    }
6732                    // The signature has changed, but this package is in the system
6733                    // image...  let's recover!
6734                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6735                    // However...  if this package is part of a shared user, but it
6736                    // doesn't match the signature of the shared user, let's fail.
6737                    // What this means is that you can't change the signatures
6738                    // associated with an overall shared user, which doesn't seem all
6739                    // that unreasonable.
6740                    if (pkgSetting.sharedUser != null) {
6741                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6742                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6743                            throw new PackageManagerException(
6744                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6745                                            "Signature mismatch for shared user : "
6746                                            + pkgSetting.sharedUser);
6747                        }
6748                    }
6749                    // File a report about this.
6750                    String msg = "System package " + pkg.packageName
6751                        + " signature changed; retaining data.";
6752                    reportSettingsProblem(Log.WARN, msg);
6753                }
6754            }
6755            // Verify that this new package doesn't have any content providers
6756            // that conflict with existing packages.  Only do this if the
6757            // package isn't already installed, since we don't want to break
6758            // things that are installed.
6759            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6760                final int N = pkg.providers.size();
6761                int i;
6762                for (i=0; i<N; i++) {
6763                    PackageParser.Provider p = pkg.providers.get(i);
6764                    if (p.info.authority != null) {
6765                        String names[] = p.info.authority.split(";");
6766                        for (int j = 0; j < names.length; j++) {
6767                            if (mProvidersByAuthority.containsKey(names[j])) {
6768                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6769                                final String otherPackageName =
6770                                        ((other != null && other.getComponentName() != null) ?
6771                                                other.getComponentName().getPackageName() : "?");
6772                                throw new PackageManagerException(
6773                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6774                                                "Can't install because provider name " + names[j]
6775                                                + " (in package " + pkg.applicationInfo.packageName
6776                                                + ") is already used by " + otherPackageName);
6777                            }
6778                        }
6779                    }
6780                }
6781            }
6782
6783            if (pkg.mAdoptPermissions != null) {
6784                // This package wants to adopt ownership of permissions from
6785                // another package.
6786                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6787                    final String origName = pkg.mAdoptPermissions.get(i);
6788                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6789                    if (orig != null) {
6790                        if (verifyPackageUpdateLPr(orig, pkg)) {
6791                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6792                                    + pkg.packageName);
6793                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6794                        }
6795                    }
6796                }
6797            }
6798        }
6799
6800        final String pkgName = pkg.packageName;
6801
6802        final long scanFileTime = scanFile.lastModified();
6803        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6804        pkg.applicationInfo.processName = fixProcessName(
6805                pkg.applicationInfo.packageName,
6806                pkg.applicationInfo.processName,
6807                pkg.applicationInfo.uid);
6808
6809        File dataPath;
6810        if (mPlatformPackage == pkg) {
6811            // The system package is special.
6812            dataPath = new File(Environment.getDataDirectory(), "system");
6813
6814            pkg.applicationInfo.dataDir = dataPath.getPath();
6815
6816        } else {
6817            // This is a normal package, need to make its data directory.
6818            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6819                    UserHandle.USER_OWNER, pkg.packageName);
6820
6821            boolean uidError = false;
6822            if (dataPath.exists()) {
6823                int currentUid = 0;
6824                try {
6825                    StructStat stat = Os.stat(dataPath.getPath());
6826                    currentUid = stat.st_uid;
6827                } catch (ErrnoException e) {
6828                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6829                }
6830
6831                // If we have mismatched owners for the data path, we have a problem.
6832                if (currentUid != pkg.applicationInfo.uid) {
6833                    boolean recovered = false;
6834                    if (currentUid == 0) {
6835                        // The directory somehow became owned by root.  Wow.
6836                        // This is probably because the system was stopped while
6837                        // installd was in the middle of messing with its libs
6838                        // directory.  Ask installd to fix that.
6839                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6840                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6841                        if (ret >= 0) {
6842                            recovered = true;
6843                            String msg = "Package " + pkg.packageName
6844                                    + " unexpectedly changed to uid 0; recovered to " +
6845                                    + pkg.applicationInfo.uid;
6846                            reportSettingsProblem(Log.WARN, msg);
6847                        }
6848                    }
6849                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6850                            || (scanFlags&SCAN_BOOTING) != 0)) {
6851                        // If this is a system app, we can at least delete its
6852                        // current data so the application will still work.
6853                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6854                        if (ret >= 0) {
6855                            // TODO: Kill the processes first
6856                            // Old data gone!
6857                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6858                                    ? "System package " : "Third party package ";
6859                            String msg = prefix + pkg.packageName
6860                                    + " has changed from uid: "
6861                                    + currentUid + " to "
6862                                    + pkg.applicationInfo.uid + "; old data erased";
6863                            reportSettingsProblem(Log.WARN, msg);
6864                            recovered = true;
6865
6866                            // And now re-install the app.
6867                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6868                                    pkg.applicationInfo.seinfo);
6869                            if (ret == -1) {
6870                                // Ack should not happen!
6871                                msg = prefix + pkg.packageName
6872                                        + " could not have data directory re-created after delete.";
6873                                reportSettingsProblem(Log.WARN, msg);
6874                                throw new PackageManagerException(
6875                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6876                            }
6877                        }
6878                        if (!recovered) {
6879                            mHasSystemUidErrors = true;
6880                        }
6881                    } else if (!recovered) {
6882                        // If we allow this install to proceed, we will be broken.
6883                        // Abort, abort!
6884                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6885                                "scanPackageLI");
6886                    }
6887                    if (!recovered) {
6888                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6889                            + pkg.applicationInfo.uid + "/fs_"
6890                            + currentUid;
6891                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6892                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6893                        String msg = "Package " + pkg.packageName
6894                                + " has mismatched uid: "
6895                                + currentUid + " on disk, "
6896                                + pkg.applicationInfo.uid + " in settings";
6897                        // writer
6898                        synchronized (mPackages) {
6899                            mSettings.mReadMessages.append(msg);
6900                            mSettings.mReadMessages.append('\n');
6901                            uidError = true;
6902                            if (!pkgSetting.uidError) {
6903                                reportSettingsProblem(Log.ERROR, msg);
6904                            }
6905                        }
6906                    }
6907                }
6908                pkg.applicationInfo.dataDir = dataPath.getPath();
6909                if (mShouldRestoreconData) {
6910                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6911                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6912                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6913                }
6914            } else {
6915                if (DEBUG_PACKAGE_SCANNING) {
6916                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6917                        Log.v(TAG, "Want this data dir: " + dataPath);
6918                }
6919                //invoke installer to do the actual installation
6920                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6921                        pkg.applicationInfo.seinfo);
6922                if (ret < 0) {
6923                    // Error from installer
6924                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6925                            "Unable to create data dirs [errorCode=" + ret + "]");
6926                }
6927
6928                if (dataPath.exists()) {
6929                    pkg.applicationInfo.dataDir = dataPath.getPath();
6930                } else {
6931                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6932                    pkg.applicationInfo.dataDir = null;
6933                }
6934            }
6935
6936            pkgSetting.uidError = uidError;
6937        }
6938
6939        final String path = scanFile.getPath();
6940        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6941
6942        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6943            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6944
6945            // Some system apps still use directory structure for native libraries
6946            // in which case we might end up not detecting abi solely based on apk
6947            // structure. Try to detect abi based on directory structure.
6948            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6949                    pkg.applicationInfo.primaryCpuAbi == null) {
6950                setBundledAppAbisAndRoots(pkg, pkgSetting);
6951                setNativeLibraryPaths(pkg);
6952            }
6953
6954        } else {
6955            if ((scanFlags & SCAN_MOVE) != 0) {
6956                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6957                // but we already have this packages package info in the PackageSetting. We just
6958                // use that and derive the native library path based on the new codepath.
6959                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6960                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6961            }
6962
6963            // Set native library paths again. For moves, the path will be updated based on the
6964            // ABIs we've determined above. For non-moves, the path will be updated based on the
6965            // ABIs we determined during compilation, but the path will depend on the final
6966            // package path (after the rename away from the stage path).
6967            setNativeLibraryPaths(pkg);
6968        }
6969
6970        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6971        final int[] userIds = sUserManager.getUserIds();
6972        synchronized (mInstallLock) {
6973            // Make sure all user data directories are ready to roll; we're okay
6974            // if they already exist
6975            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6976                for (int userId : userIds) {
6977                    if (userId != 0) {
6978                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6979                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6980                                pkg.applicationInfo.seinfo);
6981                    }
6982                }
6983            }
6984
6985            // Create a native library symlink only if we have native libraries
6986            // and if the native libraries are 32 bit libraries. We do not provide
6987            // this symlink for 64 bit libraries.
6988            if (pkg.applicationInfo.primaryCpuAbi != null &&
6989                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6990                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6991                for (int userId : userIds) {
6992                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6993                            nativeLibPath, userId) < 0) {
6994                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6995                                "Failed linking native library dir (user=" + userId + ")");
6996                    }
6997                }
6998            }
6999        }
7000
7001        // This is a special case for the "system" package, where the ABI is
7002        // dictated by the zygote configuration (and init.rc). We should keep track
7003        // of this ABI so that we can deal with "normal" applications that run under
7004        // the same UID correctly.
7005        if (mPlatformPackage == pkg) {
7006            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7007                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7008        }
7009
7010        // If there's a mismatch between the abi-override in the package setting
7011        // and the abiOverride specified for the install. Warn about this because we
7012        // would've already compiled the app without taking the package setting into
7013        // account.
7014        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7015            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7016                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7017                        " for package: " + pkg.packageName);
7018            }
7019        }
7020
7021        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7022        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7023        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7024
7025        // Copy the derived override back to the parsed package, so that we can
7026        // update the package settings accordingly.
7027        pkg.cpuAbiOverride = cpuAbiOverride;
7028
7029        if (DEBUG_ABI_SELECTION) {
7030            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7031                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7032                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7033        }
7034
7035        // Push the derived path down into PackageSettings so we know what to
7036        // clean up at uninstall time.
7037        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7038
7039        if (DEBUG_ABI_SELECTION) {
7040            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7041                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7042                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7043        }
7044
7045        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7046            // We don't do this here during boot because we can do it all
7047            // at once after scanning all existing packages.
7048            //
7049            // We also do this *before* we perform dexopt on this package, so that
7050            // we can avoid redundant dexopts, and also to make sure we've got the
7051            // code and package path correct.
7052            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7053                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7054        }
7055
7056        if ((scanFlags & SCAN_NO_DEX) == 0) {
7057            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7058                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7059            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7060                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7061            }
7062        }
7063        if (mFactoryTest && pkg.requestedPermissions.contains(
7064                android.Manifest.permission.FACTORY_TEST)) {
7065            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7066        }
7067
7068        ArrayList<PackageParser.Package> clientLibPkgs = null;
7069
7070        // writer
7071        synchronized (mPackages) {
7072            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7073                // Only system apps can add new shared libraries.
7074                if (pkg.libraryNames != null) {
7075                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7076                        String name = pkg.libraryNames.get(i);
7077                        boolean allowed = false;
7078                        if (pkg.isUpdatedSystemApp()) {
7079                            // New library entries can only be added through the
7080                            // system image.  This is important to get rid of a lot
7081                            // of nasty edge cases: for example if we allowed a non-
7082                            // system update of the app to add a library, then uninstalling
7083                            // the update would make the library go away, and assumptions
7084                            // we made such as through app install filtering would now
7085                            // have allowed apps on the device which aren't compatible
7086                            // with it.  Better to just have the restriction here, be
7087                            // conservative, and create many fewer cases that can negatively
7088                            // impact the user experience.
7089                            final PackageSetting sysPs = mSettings
7090                                    .getDisabledSystemPkgLPr(pkg.packageName);
7091                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7092                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7093                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7094                                        allowed = true;
7095                                        allowed = true;
7096                                        break;
7097                                    }
7098                                }
7099                            }
7100                        } else {
7101                            allowed = true;
7102                        }
7103                        if (allowed) {
7104                            if (!mSharedLibraries.containsKey(name)) {
7105                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7106                            } else if (!name.equals(pkg.packageName)) {
7107                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7108                                        + name + " already exists; skipping");
7109                            }
7110                        } else {
7111                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7112                                    + name + " that is not declared on system image; skipping");
7113                        }
7114                    }
7115                    if ((scanFlags&SCAN_BOOTING) == 0) {
7116                        // If we are not booting, we need to update any applications
7117                        // that are clients of our shared library.  If we are booting,
7118                        // this will all be done once the scan is complete.
7119                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7120                    }
7121                }
7122            }
7123        }
7124
7125        // We also need to dexopt any apps that are dependent on this library.  Note that
7126        // if these fail, we should abort the install since installing the library will
7127        // result in some apps being broken.
7128        if (clientLibPkgs != null) {
7129            if ((scanFlags & SCAN_NO_DEX) == 0) {
7130                for (int i = 0; i < clientLibPkgs.size(); i++) {
7131                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7132                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7133                            null /* instruction sets */, forceDex,
7134                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7135                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7136                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7137                                "scanPackageLI failed to dexopt clientLibPkgs");
7138                    }
7139                }
7140            }
7141        }
7142
7143        // Request the ActivityManager to kill the process(only for existing packages)
7144        // so that we do not end up in a confused state while the user is still using the older
7145        // version of the application while the new one gets installed.
7146        if ((scanFlags & SCAN_REPLACING) != 0) {
7147            killApplication(pkg.applicationInfo.packageName,
7148                        pkg.applicationInfo.uid, "replace pkg");
7149        }
7150
7151        // Also need to kill any apps that are dependent on the library.
7152        if (clientLibPkgs != null) {
7153            for (int i=0; i<clientLibPkgs.size(); i++) {
7154                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7155                killApplication(clientPkg.applicationInfo.packageName,
7156                        clientPkg.applicationInfo.uid, "update lib");
7157            }
7158        }
7159
7160        // Make sure we're not adding any bogus keyset info
7161        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7162        ksms.assertScannedPackageValid(pkg);
7163
7164        // writer
7165        synchronized (mPackages) {
7166            // We don't expect installation to fail beyond this point
7167
7168            // Add the new setting to mSettings
7169            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7170            // Add the new setting to mPackages
7171            mPackages.put(pkg.applicationInfo.packageName, pkg);
7172            // Make sure we don't accidentally delete its data.
7173            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7174            while (iter.hasNext()) {
7175                PackageCleanItem item = iter.next();
7176                if (pkgName.equals(item.packageName)) {
7177                    iter.remove();
7178                }
7179            }
7180
7181            // Take care of first install / last update times.
7182            if (currentTime != 0) {
7183                if (pkgSetting.firstInstallTime == 0) {
7184                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7185                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7186                    pkgSetting.lastUpdateTime = currentTime;
7187                }
7188            } else if (pkgSetting.firstInstallTime == 0) {
7189                // We need *something*.  Take time time stamp of the file.
7190                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7191            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7192                if (scanFileTime != pkgSetting.timeStamp) {
7193                    // A package on the system image has changed; consider this
7194                    // to be an update.
7195                    pkgSetting.lastUpdateTime = scanFileTime;
7196                }
7197            }
7198
7199            // Add the package's KeySets to the global KeySetManagerService
7200            ksms.addScannedPackageLPw(pkg);
7201
7202            int N = pkg.providers.size();
7203            StringBuilder r = null;
7204            int i;
7205            for (i=0; i<N; i++) {
7206                PackageParser.Provider p = pkg.providers.get(i);
7207                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7208                        p.info.processName, pkg.applicationInfo.uid);
7209                mProviders.addProvider(p);
7210                p.syncable = p.info.isSyncable;
7211                if (p.info.authority != null) {
7212                    String names[] = p.info.authority.split(";");
7213                    p.info.authority = null;
7214                    for (int j = 0; j < names.length; j++) {
7215                        if (j == 1 && p.syncable) {
7216                            // We only want the first authority for a provider to possibly be
7217                            // syncable, so if we already added this provider using a different
7218                            // authority clear the syncable flag. We copy the provider before
7219                            // changing it because the mProviders object contains a reference
7220                            // to a provider that we don't want to change.
7221                            // Only do this for the second authority since the resulting provider
7222                            // object can be the same for all future authorities for this provider.
7223                            p = new PackageParser.Provider(p);
7224                            p.syncable = false;
7225                        }
7226                        if (!mProvidersByAuthority.containsKey(names[j])) {
7227                            mProvidersByAuthority.put(names[j], p);
7228                            if (p.info.authority == null) {
7229                                p.info.authority = names[j];
7230                            } else {
7231                                p.info.authority = p.info.authority + ";" + names[j];
7232                            }
7233                            if (DEBUG_PACKAGE_SCANNING) {
7234                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7235                                    Log.d(TAG, "Registered content provider: " + names[j]
7236                                            + ", className = " + p.info.name + ", isSyncable = "
7237                                            + p.info.isSyncable);
7238                            }
7239                        } else {
7240                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7241                            Slog.w(TAG, "Skipping provider name " + names[j] +
7242                                    " (in package " + pkg.applicationInfo.packageName +
7243                                    "): name already used by "
7244                                    + ((other != null && other.getComponentName() != null)
7245                                            ? other.getComponentName().getPackageName() : "?"));
7246                        }
7247                    }
7248                }
7249                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7250                    if (r == null) {
7251                        r = new StringBuilder(256);
7252                    } else {
7253                        r.append(' ');
7254                    }
7255                    r.append(p.info.name);
7256                }
7257            }
7258            if (r != null) {
7259                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7260            }
7261
7262            N = pkg.services.size();
7263            r = null;
7264            for (i=0; i<N; i++) {
7265                PackageParser.Service s = pkg.services.get(i);
7266                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7267                        s.info.processName, pkg.applicationInfo.uid);
7268                mServices.addService(s);
7269                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7270                    if (r == null) {
7271                        r = new StringBuilder(256);
7272                    } else {
7273                        r.append(' ');
7274                    }
7275                    r.append(s.info.name);
7276                }
7277            }
7278            if (r != null) {
7279                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7280            }
7281
7282            N = pkg.receivers.size();
7283            r = null;
7284            for (i=0; i<N; i++) {
7285                PackageParser.Activity a = pkg.receivers.get(i);
7286                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7287                        a.info.processName, pkg.applicationInfo.uid);
7288                mReceivers.addActivity(a, "receiver");
7289                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7290                    if (r == null) {
7291                        r = new StringBuilder(256);
7292                    } else {
7293                        r.append(' ');
7294                    }
7295                    r.append(a.info.name);
7296                }
7297            }
7298            if (r != null) {
7299                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7300            }
7301
7302            N = pkg.activities.size();
7303            r = null;
7304            for (i=0; i<N; i++) {
7305                PackageParser.Activity a = pkg.activities.get(i);
7306                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7307                        a.info.processName, pkg.applicationInfo.uid);
7308                mActivities.addActivity(a, "activity");
7309                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7310                    if (r == null) {
7311                        r = new StringBuilder(256);
7312                    } else {
7313                        r.append(' ');
7314                    }
7315                    r.append(a.info.name);
7316                }
7317            }
7318            if (r != null) {
7319                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7320            }
7321
7322            N = pkg.permissionGroups.size();
7323            r = null;
7324            for (i=0; i<N; i++) {
7325                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7326                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7327                if (cur == null) {
7328                    mPermissionGroups.put(pg.info.name, pg);
7329                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7330                        if (r == null) {
7331                            r = new StringBuilder(256);
7332                        } else {
7333                            r.append(' ');
7334                        }
7335                        r.append(pg.info.name);
7336                    }
7337                } else {
7338                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7339                            + pg.info.packageName + " ignored: original from "
7340                            + cur.info.packageName);
7341                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7342                        if (r == null) {
7343                            r = new StringBuilder(256);
7344                        } else {
7345                            r.append(' ');
7346                        }
7347                        r.append("DUP:");
7348                        r.append(pg.info.name);
7349                    }
7350                }
7351            }
7352            if (r != null) {
7353                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7354            }
7355
7356            N = pkg.permissions.size();
7357            r = null;
7358            for (i=0; i<N; i++) {
7359                PackageParser.Permission p = pkg.permissions.get(i);
7360
7361                // Assume by default that we did not install this permission into the system.
7362                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7363
7364                // Now that permission groups have a special meaning, we ignore permission
7365                // groups for legacy apps to prevent unexpected behavior. In particular,
7366                // permissions for one app being granted to someone just becuase they happen
7367                // to be in a group defined by another app (before this had no implications).
7368                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7369                    p.group = mPermissionGroups.get(p.info.group);
7370                    // Warn for a permission in an unknown group.
7371                    if (p.info.group != null && p.group == null) {
7372                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7373                                + p.info.packageName + " in an unknown group " + p.info.group);
7374                    }
7375                }
7376
7377                ArrayMap<String, BasePermission> permissionMap =
7378                        p.tree ? mSettings.mPermissionTrees
7379                                : mSettings.mPermissions;
7380                BasePermission bp = permissionMap.get(p.info.name);
7381
7382                // Allow system apps to redefine non-system permissions
7383                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7384                    final boolean currentOwnerIsSystem = (bp.perm != null
7385                            && isSystemApp(bp.perm.owner));
7386                    if (isSystemApp(p.owner)) {
7387                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7388                            // It's a built-in permission and no owner, take ownership now
7389                            bp.packageSetting = pkgSetting;
7390                            bp.perm = p;
7391                            bp.uid = pkg.applicationInfo.uid;
7392                            bp.sourcePackage = p.info.packageName;
7393                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7394                        } else if (!currentOwnerIsSystem) {
7395                            String msg = "New decl " + p.owner + " of permission  "
7396                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7397                            reportSettingsProblem(Log.WARN, msg);
7398                            bp = null;
7399                        }
7400                    }
7401                }
7402
7403                if (bp == null) {
7404                    bp = new BasePermission(p.info.name, p.info.packageName,
7405                            BasePermission.TYPE_NORMAL);
7406                    permissionMap.put(p.info.name, bp);
7407                }
7408
7409                if (bp.perm == null) {
7410                    if (bp.sourcePackage == null
7411                            || bp.sourcePackage.equals(p.info.packageName)) {
7412                        BasePermission tree = findPermissionTreeLP(p.info.name);
7413                        if (tree == null
7414                                || tree.sourcePackage.equals(p.info.packageName)) {
7415                            bp.packageSetting = pkgSetting;
7416                            bp.perm = p;
7417                            bp.uid = pkg.applicationInfo.uid;
7418                            bp.sourcePackage = p.info.packageName;
7419                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7420                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7421                                if (r == null) {
7422                                    r = new StringBuilder(256);
7423                                } else {
7424                                    r.append(' ');
7425                                }
7426                                r.append(p.info.name);
7427                            }
7428                        } else {
7429                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7430                                    + p.info.packageName + " ignored: base tree "
7431                                    + tree.name + " is from package "
7432                                    + tree.sourcePackage);
7433                        }
7434                    } else {
7435                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7436                                + p.info.packageName + " ignored: original from "
7437                                + bp.sourcePackage);
7438                    }
7439                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7440                    if (r == null) {
7441                        r = new StringBuilder(256);
7442                    } else {
7443                        r.append(' ');
7444                    }
7445                    r.append("DUP:");
7446                    r.append(p.info.name);
7447                }
7448                if (bp.perm == p) {
7449                    bp.protectionLevel = p.info.protectionLevel;
7450                }
7451            }
7452
7453            if (r != null) {
7454                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7455            }
7456
7457            N = pkg.instrumentation.size();
7458            r = null;
7459            for (i=0; i<N; i++) {
7460                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7461                a.info.packageName = pkg.applicationInfo.packageName;
7462                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7463                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7464                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7465                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7466                a.info.dataDir = pkg.applicationInfo.dataDir;
7467
7468                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7469                // need other information about the application, like the ABI and what not ?
7470                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7471                mInstrumentation.put(a.getComponentName(), a);
7472                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7473                    if (r == null) {
7474                        r = new StringBuilder(256);
7475                    } else {
7476                        r.append(' ');
7477                    }
7478                    r.append(a.info.name);
7479                }
7480            }
7481            if (r != null) {
7482                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7483            }
7484
7485            if (pkg.protectedBroadcasts != null) {
7486                N = pkg.protectedBroadcasts.size();
7487                for (i=0; i<N; i++) {
7488                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7489                }
7490            }
7491
7492            pkgSetting.setTimeStamp(scanFileTime);
7493
7494            // Create idmap files for pairs of (packages, overlay packages).
7495            // Note: "android", ie framework-res.apk, is handled by native layers.
7496            if (pkg.mOverlayTarget != null) {
7497                // This is an overlay package.
7498                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7499                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7500                        mOverlays.put(pkg.mOverlayTarget,
7501                                new ArrayMap<String, PackageParser.Package>());
7502                    }
7503                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7504                    map.put(pkg.packageName, pkg);
7505                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7506                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7507                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7508                                "scanPackageLI failed to createIdmap");
7509                    }
7510                }
7511            } else if (mOverlays.containsKey(pkg.packageName) &&
7512                    !pkg.packageName.equals("android")) {
7513                // This is a regular package, with one or more known overlay packages.
7514                createIdmapsForPackageLI(pkg);
7515            }
7516        }
7517
7518        return pkg;
7519    }
7520
7521    /**
7522     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7523     * is derived purely on the basis of the contents of {@code scanFile} and
7524     * {@code cpuAbiOverride}.
7525     *
7526     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7527     */
7528    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7529                                 String cpuAbiOverride, boolean extractLibs)
7530            throws PackageManagerException {
7531        // TODO: We can probably be smarter about this stuff. For installed apps,
7532        // we can calculate this information at install time once and for all. For
7533        // system apps, we can probably assume that this information doesn't change
7534        // after the first boot scan. As things stand, we do lots of unnecessary work.
7535
7536        // Give ourselves some initial paths; we'll come back for another
7537        // pass once we've determined ABI below.
7538        setNativeLibraryPaths(pkg);
7539
7540        // We would never need to extract libs for forward-locked and external packages,
7541        // since the container service will do it for us. We shouldn't attempt to
7542        // extract libs from system app when it was not updated.
7543        if (pkg.isForwardLocked() || isExternal(pkg) ||
7544            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7545            extractLibs = false;
7546        }
7547
7548        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7549        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7550
7551        NativeLibraryHelper.Handle handle = null;
7552        try {
7553            handle = NativeLibraryHelper.Handle.create(scanFile);
7554            // TODO(multiArch): This can be null for apps that didn't go through the
7555            // usual installation process. We can calculate it again, like we
7556            // do during install time.
7557            //
7558            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7559            // unnecessary.
7560            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7561
7562            // Null out the abis so that they can be recalculated.
7563            pkg.applicationInfo.primaryCpuAbi = null;
7564            pkg.applicationInfo.secondaryCpuAbi = null;
7565            if (isMultiArch(pkg.applicationInfo)) {
7566                // Warn if we've set an abiOverride for multi-lib packages..
7567                // By definition, we need to copy both 32 and 64 bit libraries for
7568                // such packages.
7569                if (pkg.cpuAbiOverride != null
7570                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7571                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7572                }
7573
7574                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7575                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7576                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7577                    if (extractLibs) {
7578                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7579                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7580                                useIsaSpecificSubdirs);
7581                    } else {
7582                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7583                    }
7584                }
7585
7586                maybeThrowExceptionForMultiArchCopy(
7587                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7588
7589                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7590                    if (extractLibs) {
7591                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7592                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7593                                useIsaSpecificSubdirs);
7594                    } else {
7595                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7596                    }
7597                }
7598
7599                maybeThrowExceptionForMultiArchCopy(
7600                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7601
7602                if (abi64 >= 0) {
7603                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7604                }
7605
7606                if (abi32 >= 0) {
7607                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7608                    if (abi64 >= 0) {
7609                        pkg.applicationInfo.secondaryCpuAbi = abi;
7610                    } else {
7611                        pkg.applicationInfo.primaryCpuAbi = abi;
7612                    }
7613                }
7614            } else {
7615                String[] abiList = (cpuAbiOverride != null) ?
7616                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7617
7618                // Enable gross and lame hacks for apps that are built with old
7619                // SDK tools. We must scan their APKs for renderscript bitcode and
7620                // not launch them if it's present. Don't bother checking on devices
7621                // that don't have 64 bit support.
7622                boolean needsRenderScriptOverride = false;
7623                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7624                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7625                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7626                    needsRenderScriptOverride = true;
7627                }
7628
7629                final int copyRet;
7630                if (extractLibs) {
7631                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7632                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7633                } else {
7634                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7635                }
7636
7637                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7638                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7639                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7640                }
7641
7642                if (copyRet >= 0) {
7643                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7644                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7645                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7646                } else if (needsRenderScriptOverride) {
7647                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7648                }
7649            }
7650        } catch (IOException ioe) {
7651            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7652        } finally {
7653            IoUtils.closeQuietly(handle);
7654        }
7655
7656        // Now that we've calculated the ABIs and determined if it's an internal app,
7657        // we will go ahead and populate the nativeLibraryPath.
7658        setNativeLibraryPaths(pkg);
7659    }
7660
7661    /**
7662     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7663     * i.e, so that all packages can be run inside a single process if required.
7664     *
7665     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7666     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7667     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7668     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7669     * updating a package that belongs to a shared user.
7670     *
7671     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7672     * adds unnecessary complexity.
7673     */
7674    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7675            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7676        String requiredInstructionSet = null;
7677        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7678            requiredInstructionSet = VMRuntime.getInstructionSet(
7679                     scannedPackage.applicationInfo.primaryCpuAbi);
7680        }
7681
7682        PackageSetting requirer = null;
7683        for (PackageSetting ps : packagesForUser) {
7684            // If packagesForUser contains scannedPackage, we skip it. This will happen
7685            // when scannedPackage is an update of an existing package. Without this check,
7686            // we will never be able to change the ABI of any package belonging to a shared
7687            // user, even if it's compatible with other packages.
7688            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7689                if (ps.primaryCpuAbiString == null) {
7690                    continue;
7691                }
7692
7693                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7694                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7695                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7696                    // this but there's not much we can do.
7697                    String errorMessage = "Instruction set mismatch, "
7698                            + ((requirer == null) ? "[caller]" : requirer)
7699                            + " requires " + requiredInstructionSet + " whereas " + ps
7700                            + " requires " + instructionSet;
7701                    Slog.w(TAG, errorMessage);
7702                }
7703
7704                if (requiredInstructionSet == null) {
7705                    requiredInstructionSet = instructionSet;
7706                    requirer = ps;
7707                }
7708            }
7709        }
7710
7711        if (requiredInstructionSet != null) {
7712            String adjustedAbi;
7713            if (requirer != null) {
7714                // requirer != null implies that either scannedPackage was null or that scannedPackage
7715                // did not require an ABI, in which case we have to adjust scannedPackage to match
7716                // the ABI of the set (which is the same as requirer's ABI)
7717                adjustedAbi = requirer.primaryCpuAbiString;
7718                if (scannedPackage != null) {
7719                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7720                }
7721            } else {
7722                // requirer == null implies that we're updating all ABIs in the set to
7723                // match scannedPackage.
7724                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7725            }
7726
7727            for (PackageSetting ps : packagesForUser) {
7728                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7729                    if (ps.primaryCpuAbiString != null) {
7730                        continue;
7731                    }
7732
7733                    ps.primaryCpuAbiString = adjustedAbi;
7734                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7735                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7736                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7737
7738                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7739                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7740                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7741                            ps.primaryCpuAbiString = null;
7742                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7743                            return;
7744                        } else {
7745                            mInstaller.rmdex(ps.codePathString,
7746                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7747                        }
7748                    }
7749                }
7750            }
7751        }
7752    }
7753
7754    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7755        synchronized (mPackages) {
7756            mResolverReplaced = true;
7757            // Set up information for custom user intent resolution activity.
7758            mResolveActivity.applicationInfo = pkg.applicationInfo;
7759            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7760            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7761            mResolveActivity.processName = pkg.applicationInfo.packageName;
7762            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7763            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7764                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7765            mResolveActivity.theme = 0;
7766            mResolveActivity.exported = true;
7767            mResolveActivity.enabled = true;
7768            mResolveInfo.activityInfo = mResolveActivity;
7769            mResolveInfo.priority = 0;
7770            mResolveInfo.preferredOrder = 0;
7771            mResolveInfo.match = 0;
7772            mResolveComponentName = mCustomResolverComponentName;
7773            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7774                    mResolveComponentName);
7775        }
7776    }
7777
7778    private static String calculateBundledApkRoot(final String codePathString) {
7779        final File codePath = new File(codePathString);
7780        final File codeRoot;
7781        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7782            codeRoot = Environment.getRootDirectory();
7783        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7784            codeRoot = Environment.getOemDirectory();
7785        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7786            codeRoot = Environment.getVendorDirectory();
7787        } else {
7788            // Unrecognized code path; take its top real segment as the apk root:
7789            // e.g. /something/app/blah.apk => /something
7790            try {
7791                File f = codePath.getCanonicalFile();
7792                File parent = f.getParentFile();    // non-null because codePath is a file
7793                File tmp;
7794                while ((tmp = parent.getParentFile()) != null) {
7795                    f = parent;
7796                    parent = tmp;
7797                }
7798                codeRoot = f;
7799                Slog.w(TAG, "Unrecognized code path "
7800                        + codePath + " - using " + codeRoot);
7801            } catch (IOException e) {
7802                // Can't canonicalize the code path -- shenanigans?
7803                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7804                return Environment.getRootDirectory().getPath();
7805            }
7806        }
7807        return codeRoot.getPath();
7808    }
7809
7810    /**
7811     * Derive and set the location of native libraries for the given package,
7812     * which varies depending on where and how the package was installed.
7813     */
7814    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7815        final ApplicationInfo info = pkg.applicationInfo;
7816        final String codePath = pkg.codePath;
7817        final File codeFile = new File(codePath);
7818        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7819        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7820
7821        info.nativeLibraryRootDir = null;
7822        info.nativeLibraryRootRequiresIsa = false;
7823        info.nativeLibraryDir = null;
7824        info.secondaryNativeLibraryDir = null;
7825
7826        if (isApkFile(codeFile)) {
7827            // Monolithic install
7828            if (bundledApp) {
7829                // If "/system/lib64/apkname" exists, assume that is the per-package
7830                // native library directory to use; otherwise use "/system/lib/apkname".
7831                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7832                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7833                        getPrimaryInstructionSet(info));
7834
7835                // This is a bundled system app so choose the path based on the ABI.
7836                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7837                // is just the default path.
7838                final String apkName = deriveCodePathName(codePath);
7839                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7840                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7841                        apkName).getAbsolutePath();
7842
7843                if (info.secondaryCpuAbi != null) {
7844                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7845                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7846                            secondaryLibDir, apkName).getAbsolutePath();
7847                }
7848            } else if (asecApp) {
7849                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7850                        .getAbsolutePath();
7851            } else {
7852                final String apkName = deriveCodePathName(codePath);
7853                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7854                        .getAbsolutePath();
7855            }
7856
7857            info.nativeLibraryRootRequiresIsa = false;
7858            info.nativeLibraryDir = info.nativeLibraryRootDir;
7859        } else {
7860            // Cluster install
7861            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7862            info.nativeLibraryRootRequiresIsa = true;
7863
7864            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7865                    getPrimaryInstructionSet(info)).getAbsolutePath();
7866
7867            if (info.secondaryCpuAbi != null) {
7868                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7869                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7870            }
7871        }
7872    }
7873
7874    /**
7875     * Calculate the abis and roots for a bundled app. These can uniquely
7876     * be determined from the contents of the system partition, i.e whether
7877     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7878     * of this information, and instead assume that the system was built
7879     * sensibly.
7880     */
7881    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7882                                           PackageSetting pkgSetting) {
7883        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7884
7885        // If "/system/lib64/apkname" exists, assume that is the per-package
7886        // native library directory to use; otherwise use "/system/lib/apkname".
7887        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7888        setBundledAppAbi(pkg, apkRoot, apkName);
7889        // pkgSetting might be null during rescan following uninstall of updates
7890        // to a bundled app, so accommodate that possibility.  The settings in
7891        // that case will be established later from the parsed package.
7892        //
7893        // If the settings aren't null, sync them up with what we've just derived.
7894        // note that apkRoot isn't stored in the package settings.
7895        if (pkgSetting != null) {
7896            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7897            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7898        }
7899    }
7900
7901    /**
7902     * Deduces the ABI of a bundled app and sets the relevant fields on the
7903     * parsed pkg object.
7904     *
7905     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7906     *        under which system libraries are installed.
7907     * @param apkName the name of the installed package.
7908     */
7909    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7910        final File codeFile = new File(pkg.codePath);
7911
7912        final boolean has64BitLibs;
7913        final boolean has32BitLibs;
7914        if (isApkFile(codeFile)) {
7915            // Monolithic install
7916            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7917            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7918        } else {
7919            // Cluster install
7920            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7921            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7922                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7923                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7924                has64BitLibs = (new File(rootDir, isa)).exists();
7925            } else {
7926                has64BitLibs = false;
7927            }
7928            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7929                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7930                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7931                has32BitLibs = (new File(rootDir, isa)).exists();
7932            } else {
7933                has32BitLibs = false;
7934            }
7935        }
7936
7937        if (has64BitLibs && !has32BitLibs) {
7938            // The package has 64 bit libs, but not 32 bit libs. Its primary
7939            // ABI should be 64 bit. We can safely assume here that the bundled
7940            // native libraries correspond to the most preferred ABI in the list.
7941
7942            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7943            pkg.applicationInfo.secondaryCpuAbi = null;
7944        } else if (has32BitLibs && !has64BitLibs) {
7945            // The package has 32 bit libs but not 64 bit libs. Its primary
7946            // ABI should be 32 bit.
7947
7948            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7949            pkg.applicationInfo.secondaryCpuAbi = null;
7950        } else if (has32BitLibs && has64BitLibs) {
7951            // The application has both 64 and 32 bit bundled libraries. We check
7952            // here that the app declares multiArch support, and warn if it doesn't.
7953            //
7954            // We will be lenient here and record both ABIs. The primary will be the
7955            // ABI that's higher on the list, i.e, a device that's configured to prefer
7956            // 64 bit apps will see a 64 bit primary ABI,
7957
7958            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7959                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7960            }
7961
7962            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7963                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7964                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7965            } else {
7966                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7967                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7968            }
7969        } else {
7970            pkg.applicationInfo.primaryCpuAbi = null;
7971            pkg.applicationInfo.secondaryCpuAbi = null;
7972        }
7973    }
7974
7975    private void killApplication(String pkgName, int appId, String reason) {
7976        // Request the ActivityManager to kill the process(only for existing packages)
7977        // so that we do not end up in a confused state while the user is still using the older
7978        // version of the application while the new one gets installed.
7979        IActivityManager am = ActivityManagerNative.getDefault();
7980        if (am != null) {
7981            try {
7982                am.killApplicationWithAppId(pkgName, appId, reason);
7983            } catch (RemoteException e) {
7984            }
7985        }
7986    }
7987
7988    void removePackageLI(PackageSetting ps, boolean chatty) {
7989        if (DEBUG_INSTALL) {
7990            if (chatty)
7991                Log.d(TAG, "Removing package " + ps.name);
7992        }
7993
7994        // writer
7995        synchronized (mPackages) {
7996            mPackages.remove(ps.name);
7997            final PackageParser.Package pkg = ps.pkg;
7998            if (pkg != null) {
7999                cleanPackageDataStructuresLILPw(pkg, chatty);
8000            }
8001        }
8002    }
8003
8004    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8005        if (DEBUG_INSTALL) {
8006            if (chatty)
8007                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8008        }
8009
8010        // writer
8011        synchronized (mPackages) {
8012            mPackages.remove(pkg.applicationInfo.packageName);
8013            cleanPackageDataStructuresLILPw(pkg, chatty);
8014        }
8015    }
8016
8017    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8018        int N = pkg.providers.size();
8019        StringBuilder r = null;
8020        int i;
8021        for (i=0; i<N; i++) {
8022            PackageParser.Provider p = pkg.providers.get(i);
8023            mProviders.removeProvider(p);
8024            if (p.info.authority == null) {
8025
8026                /* There was another ContentProvider with this authority when
8027                 * this app was installed so this authority is null,
8028                 * Ignore it as we don't have to unregister the provider.
8029                 */
8030                continue;
8031            }
8032            String names[] = p.info.authority.split(";");
8033            for (int j = 0; j < names.length; j++) {
8034                if (mProvidersByAuthority.get(names[j]) == p) {
8035                    mProvidersByAuthority.remove(names[j]);
8036                    if (DEBUG_REMOVE) {
8037                        if (chatty)
8038                            Log.d(TAG, "Unregistered content provider: " + names[j]
8039                                    + ", className = " + p.info.name + ", isSyncable = "
8040                                    + p.info.isSyncable);
8041                    }
8042                }
8043            }
8044            if (DEBUG_REMOVE && chatty) {
8045                if (r == null) {
8046                    r = new StringBuilder(256);
8047                } else {
8048                    r.append(' ');
8049                }
8050                r.append(p.info.name);
8051            }
8052        }
8053        if (r != null) {
8054            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8055        }
8056
8057        N = pkg.services.size();
8058        r = null;
8059        for (i=0; i<N; i++) {
8060            PackageParser.Service s = pkg.services.get(i);
8061            mServices.removeService(s);
8062            if (chatty) {
8063                if (r == null) {
8064                    r = new StringBuilder(256);
8065                } else {
8066                    r.append(' ');
8067                }
8068                r.append(s.info.name);
8069            }
8070        }
8071        if (r != null) {
8072            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8073        }
8074
8075        N = pkg.receivers.size();
8076        r = null;
8077        for (i=0; i<N; i++) {
8078            PackageParser.Activity a = pkg.receivers.get(i);
8079            mReceivers.removeActivity(a, "receiver");
8080            if (DEBUG_REMOVE && chatty) {
8081                if (r == null) {
8082                    r = new StringBuilder(256);
8083                } else {
8084                    r.append(' ');
8085                }
8086                r.append(a.info.name);
8087            }
8088        }
8089        if (r != null) {
8090            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8091        }
8092
8093        N = pkg.activities.size();
8094        r = null;
8095        for (i=0; i<N; i++) {
8096            PackageParser.Activity a = pkg.activities.get(i);
8097            mActivities.removeActivity(a, "activity");
8098            if (DEBUG_REMOVE && chatty) {
8099                if (r == null) {
8100                    r = new StringBuilder(256);
8101                } else {
8102                    r.append(' ');
8103                }
8104                r.append(a.info.name);
8105            }
8106        }
8107        if (r != null) {
8108            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8109        }
8110
8111        N = pkg.permissions.size();
8112        r = null;
8113        for (i=0; i<N; i++) {
8114            PackageParser.Permission p = pkg.permissions.get(i);
8115            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8116            if (bp == null) {
8117                bp = mSettings.mPermissionTrees.get(p.info.name);
8118            }
8119            if (bp != null && bp.perm == p) {
8120                bp.perm = null;
8121                if (DEBUG_REMOVE && chatty) {
8122                    if (r == null) {
8123                        r = new StringBuilder(256);
8124                    } else {
8125                        r.append(' ');
8126                    }
8127                    r.append(p.info.name);
8128                }
8129            }
8130            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8131                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8132                if (appOpPerms != null) {
8133                    appOpPerms.remove(pkg.packageName);
8134                }
8135            }
8136        }
8137        if (r != null) {
8138            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8139        }
8140
8141        N = pkg.requestedPermissions.size();
8142        r = null;
8143        for (i=0; i<N; i++) {
8144            String perm = pkg.requestedPermissions.get(i);
8145            BasePermission bp = mSettings.mPermissions.get(perm);
8146            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8147                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8148                if (appOpPerms != null) {
8149                    appOpPerms.remove(pkg.packageName);
8150                    if (appOpPerms.isEmpty()) {
8151                        mAppOpPermissionPackages.remove(perm);
8152                    }
8153                }
8154            }
8155        }
8156        if (r != null) {
8157            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8158        }
8159
8160        N = pkg.instrumentation.size();
8161        r = null;
8162        for (i=0; i<N; i++) {
8163            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8164            mInstrumentation.remove(a.getComponentName());
8165            if (DEBUG_REMOVE && chatty) {
8166                if (r == null) {
8167                    r = new StringBuilder(256);
8168                } else {
8169                    r.append(' ');
8170                }
8171                r.append(a.info.name);
8172            }
8173        }
8174        if (r != null) {
8175            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8176        }
8177
8178        r = null;
8179        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8180            // Only system apps can hold shared libraries.
8181            if (pkg.libraryNames != null) {
8182                for (i=0; i<pkg.libraryNames.size(); i++) {
8183                    String name = pkg.libraryNames.get(i);
8184                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8185                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8186                        mSharedLibraries.remove(name);
8187                        if (DEBUG_REMOVE && chatty) {
8188                            if (r == null) {
8189                                r = new StringBuilder(256);
8190                            } else {
8191                                r.append(' ');
8192                            }
8193                            r.append(name);
8194                        }
8195                    }
8196                }
8197            }
8198        }
8199        if (r != null) {
8200            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8201        }
8202    }
8203
8204    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8205        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8206            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8207                return true;
8208            }
8209        }
8210        return false;
8211    }
8212
8213    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8214    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8215    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8216
8217    private void updatePermissionsLPw(String changingPkg,
8218            PackageParser.Package pkgInfo, int flags) {
8219        // Make sure there are no dangling permission trees.
8220        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8221        while (it.hasNext()) {
8222            final BasePermission bp = it.next();
8223            if (bp.packageSetting == null) {
8224                // We may not yet have parsed the package, so just see if
8225                // we still know about its settings.
8226                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8227            }
8228            if (bp.packageSetting == null) {
8229                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8230                        + " from package " + bp.sourcePackage);
8231                it.remove();
8232            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8233                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8234                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8235                            + " from package " + bp.sourcePackage);
8236                    flags |= UPDATE_PERMISSIONS_ALL;
8237                    it.remove();
8238                }
8239            }
8240        }
8241
8242        // Make sure all dynamic permissions have been assigned to a package,
8243        // and make sure there are no dangling permissions.
8244        it = mSettings.mPermissions.values().iterator();
8245        while (it.hasNext()) {
8246            final BasePermission bp = it.next();
8247            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8248                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8249                        + bp.name + " pkg=" + bp.sourcePackage
8250                        + " info=" + bp.pendingInfo);
8251                if (bp.packageSetting == null && bp.pendingInfo != null) {
8252                    final BasePermission tree = findPermissionTreeLP(bp.name);
8253                    if (tree != null && tree.perm != null) {
8254                        bp.packageSetting = tree.packageSetting;
8255                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8256                                new PermissionInfo(bp.pendingInfo));
8257                        bp.perm.info.packageName = tree.perm.info.packageName;
8258                        bp.perm.info.name = bp.name;
8259                        bp.uid = tree.uid;
8260                    }
8261                }
8262            }
8263            if (bp.packageSetting == null) {
8264                // We may not yet have parsed the package, so just see if
8265                // we still know about its settings.
8266                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8267            }
8268            if (bp.packageSetting == null) {
8269                Slog.w(TAG, "Removing dangling permission: " + bp.name
8270                        + " from package " + bp.sourcePackage);
8271                it.remove();
8272            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8273                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8274                    Slog.i(TAG, "Removing old permission: " + bp.name
8275                            + " from package " + bp.sourcePackage);
8276                    flags |= UPDATE_PERMISSIONS_ALL;
8277                    it.remove();
8278                }
8279            }
8280        }
8281
8282        // Now update the permissions for all packages, in particular
8283        // replace the granted permissions of the system packages.
8284        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8285            for (PackageParser.Package pkg : mPackages.values()) {
8286                if (pkg != pkgInfo) {
8287                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8288                            changingPkg);
8289                }
8290            }
8291        }
8292
8293        if (pkgInfo != null) {
8294            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8295        }
8296    }
8297
8298    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8299            String packageOfInterest) {
8300        // IMPORTANT: There are two types of permissions: install and runtime.
8301        // Install time permissions are granted when the app is installed to
8302        // all device users and users added in the future. Runtime permissions
8303        // are granted at runtime explicitly to specific users. Normal and signature
8304        // protected permissions are install time permissions. Dangerous permissions
8305        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8306        // otherwise they are runtime permissions. This function does not manage
8307        // runtime permissions except for the case an app targeting Lollipop MR1
8308        // being upgraded to target a newer SDK, in which case dangerous permissions
8309        // are transformed from install time to runtime ones.
8310
8311        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8312        if (ps == null) {
8313            return;
8314        }
8315
8316        PermissionsState permissionsState = ps.getPermissionsState();
8317        PermissionsState origPermissions = permissionsState;
8318
8319        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8320
8321        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8322
8323        boolean changedInstallPermission = false;
8324
8325        if (replace) {
8326            ps.installPermissionsFixed = false;
8327            if (!ps.isSharedUser()) {
8328                origPermissions = new PermissionsState(permissionsState);
8329                permissionsState.reset();
8330            }
8331        }
8332
8333        permissionsState.setGlobalGids(mGlobalGids);
8334
8335        final int N = pkg.requestedPermissions.size();
8336        for (int i=0; i<N; i++) {
8337            final String name = pkg.requestedPermissions.get(i);
8338            final BasePermission bp = mSettings.mPermissions.get(name);
8339
8340            if (DEBUG_INSTALL) {
8341                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8342            }
8343
8344            if (bp == null || bp.packageSetting == null) {
8345                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8346                    Slog.w(TAG, "Unknown permission " + name
8347                            + " in package " + pkg.packageName);
8348                }
8349                continue;
8350            }
8351
8352            final String perm = bp.name;
8353            boolean allowedSig = false;
8354            int grant = GRANT_DENIED;
8355
8356            // Keep track of app op permissions.
8357            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8358                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8359                if (pkgs == null) {
8360                    pkgs = new ArraySet<>();
8361                    mAppOpPermissionPackages.put(bp.name, pkgs);
8362                }
8363                pkgs.add(pkg.packageName);
8364            }
8365
8366            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8367            switch (level) {
8368                case PermissionInfo.PROTECTION_NORMAL: {
8369                    // For all apps normal permissions are install time ones.
8370                    grant = GRANT_INSTALL;
8371                } break;
8372
8373                case PermissionInfo.PROTECTION_DANGEROUS: {
8374                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8375                        // For legacy apps dangerous permissions are install time ones.
8376                        grant = GRANT_INSTALL_LEGACY;
8377                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8378                        // For legacy apps that became modern, install becomes runtime.
8379                        grant = GRANT_UPGRADE;
8380                    } else {
8381                        // For modern apps keep runtime permissions unchanged.
8382                        grant = GRANT_RUNTIME;
8383                    }
8384                } break;
8385
8386                case PermissionInfo.PROTECTION_SIGNATURE: {
8387                    // For all apps signature permissions are install time ones.
8388                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8389                    if (allowedSig) {
8390                        grant = GRANT_INSTALL;
8391                    }
8392                } break;
8393            }
8394
8395            if (DEBUG_INSTALL) {
8396                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8397            }
8398
8399            if (grant != GRANT_DENIED) {
8400                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8401                    // If this is an existing, non-system package, then
8402                    // we can't add any new permissions to it.
8403                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8404                        // Except...  if this is a permission that was added
8405                        // to the platform (note: need to only do this when
8406                        // updating the platform).
8407                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8408                            grant = GRANT_DENIED;
8409                        }
8410                    }
8411                }
8412
8413                switch (grant) {
8414                    case GRANT_INSTALL: {
8415                        // Revoke this as runtime permission to handle the case of
8416                        // a runtime permission being downgraded to an install one.
8417                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8418                            if (origPermissions.getRuntimePermissionState(
8419                                    bp.name, userId) != null) {
8420                                // Revoke the runtime permission and clear the flags.
8421                                origPermissions.revokeRuntimePermission(bp, userId);
8422                                origPermissions.updatePermissionFlags(bp, userId,
8423                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8424                                // If we revoked a permission permission, we have to write.
8425                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8426                                        changedRuntimePermissionUserIds, userId);
8427                            }
8428                        }
8429                        // Grant an install permission.
8430                        if (permissionsState.grantInstallPermission(bp) !=
8431                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8432                            changedInstallPermission = true;
8433                        }
8434                    } break;
8435
8436                    case GRANT_INSTALL_LEGACY: {
8437                        // Grant an install permission.
8438                        if (permissionsState.grantInstallPermission(bp) !=
8439                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8440                            changedInstallPermission = true;
8441                        }
8442                    } break;
8443
8444                    case GRANT_RUNTIME: {
8445                        // Grant previously granted runtime permissions.
8446                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8447                            PermissionState permissionState = origPermissions
8448                                    .getRuntimePermissionState(bp.name, userId);
8449                            final int flags = permissionState != null
8450                                    ? permissionState.getFlags() : 0;
8451                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8452                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8453                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8454                                    // If we cannot put the permission as it was, we have to write.
8455                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8456                                            changedRuntimePermissionUserIds, userId);
8457                                }
8458                            }
8459                            // Propagate the permission flags.
8460                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8461                        }
8462                    } break;
8463
8464                    case GRANT_UPGRADE: {
8465                        // Grant runtime permissions for a previously held install permission.
8466                        PermissionState permissionState = origPermissions
8467                                .getInstallPermissionState(bp.name);
8468                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8469
8470                        if (origPermissions.revokeInstallPermission(bp)
8471                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8472                            // We will be transferring the permission flags, so clear them.
8473                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8474                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8475                            changedInstallPermission = true;
8476                        }
8477
8478                        // If the permission is not to be promoted to runtime we ignore it and
8479                        // also its other flags as they are not applicable to install permissions.
8480                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8481                            for (int userId : currentUserIds) {
8482                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8483                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8484                                    // Transfer the permission flags.
8485                                    permissionsState.updatePermissionFlags(bp, userId,
8486                                            flags, flags);
8487                                    // If we granted the permission, we have to write.
8488                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8489                                            changedRuntimePermissionUserIds, userId);
8490                                }
8491                            }
8492                        }
8493                    } break;
8494
8495                    default: {
8496                        if (packageOfInterest == null
8497                                || packageOfInterest.equals(pkg.packageName)) {
8498                            Slog.w(TAG, "Not granting permission " + perm
8499                                    + " to package " + pkg.packageName
8500                                    + " because it was previously installed without");
8501                        }
8502                    } break;
8503                }
8504            } else {
8505                if (permissionsState.revokeInstallPermission(bp) !=
8506                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8507                    // Also drop the permission flags.
8508                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8509                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8510                    changedInstallPermission = true;
8511                    Slog.i(TAG, "Un-granting permission " + perm
8512                            + " from package " + pkg.packageName
8513                            + " (protectionLevel=" + bp.protectionLevel
8514                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8515                            + ")");
8516                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8517                    // Don't print warning for app op permissions, since it is fine for them
8518                    // not to be granted, there is a UI for the user to decide.
8519                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8520                        Slog.w(TAG, "Not granting permission " + perm
8521                                + " to package " + pkg.packageName
8522                                + " (protectionLevel=" + bp.protectionLevel
8523                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8524                                + ")");
8525                    }
8526                }
8527            }
8528        }
8529
8530        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8531                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8532            // This is the first that we have heard about this package, so the
8533            // permissions we have now selected are fixed until explicitly
8534            // changed.
8535            ps.installPermissionsFixed = true;
8536        }
8537
8538        // Persist the runtime permissions state for users with changes.
8539        for (int userId : changedRuntimePermissionUserIds) {
8540            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8541        }
8542    }
8543
8544    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8545        boolean allowed = false;
8546        final int NP = PackageParser.NEW_PERMISSIONS.length;
8547        for (int ip=0; ip<NP; ip++) {
8548            final PackageParser.NewPermissionInfo npi
8549                    = PackageParser.NEW_PERMISSIONS[ip];
8550            if (npi.name.equals(perm)
8551                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8552                allowed = true;
8553                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8554                        + pkg.packageName);
8555                break;
8556            }
8557        }
8558        return allowed;
8559    }
8560
8561    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8562            BasePermission bp, PermissionsState origPermissions) {
8563        boolean allowed;
8564        allowed = (compareSignatures(
8565                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8566                        == PackageManager.SIGNATURE_MATCH)
8567                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8568                        == PackageManager.SIGNATURE_MATCH);
8569        if (!allowed && (bp.protectionLevel
8570                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8571            if (isSystemApp(pkg)) {
8572                // For updated system applications, a system permission
8573                // is granted only if it had been defined by the original application.
8574                if (pkg.isUpdatedSystemApp()) {
8575                    final PackageSetting sysPs = mSettings
8576                            .getDisabledSystemPkgLPr(pkg.packageName);
8577                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8578                        // If the original was granted this permission, we take
8579                        // that grant decision as read and propagate it to the
8580                        // update.
8581                        if (sysPs.isPrivileged()) {
8582                            allowed = true;
8583                        }
8584                    } else {
8585                        // The system apk may have been updated with an older
8586                        // version of the one on the data partition, but which
8587                        // granted a new system permission that it didn't have
8588                        // before.  In this case we do want to allow the app to
8589                        // now get the new permission if the ancestral apk is
8590                        // privileged to get it.
8591                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8592                            for (int j=0;
8593                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8594                                if (perm.equals(
8595                                        sysPs.pkg.requestedPermissions.get(j))) {
8596                                    allowed = true;
8597                                    break;
8598                                }
8599                            }
8600                        }
8601                    }
8602                } else {
8603                    allowed = isPrivilegedApp(pkg);
8604                }
8605            }
8606        }
8607        if (!allowed) {
8608            if (!allowed && (bp.protectionLevel
8609                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8610                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8611                // If this was a previously normal/dangerous permission that got moved
8612                // to a system permission as part of the runtime permission redesign, then
8613                // we still want to blindly grant it to old apps.
8614                allowed = true;
8615            }
8616            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8617                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8618                // If this permission is to be granted to the system installer and
8619                // this app is an installer, then it gets the permission.
8620                allowed = true;
8621            }
8622            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8623                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8624                // If this permission is to be granted to the system verifier and
8625                // this app is a verifier, then it gets the permission.
8626                allowed = true;
8627            }
8628            if (!allowed && (bp.protectionLevel
8629                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8630                    && isSystemApp(pkg)) {
8631                // Any pre-installed system app is allowed to get this permission.
8632                allowed = true;
8633            }
8634            if (!allowed && (bp.protectionLevel
8635                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8636                // For development permissions, a development permission
8637                // is granted only if it was already granted.
8638                allowed = origPermissions.hasInstallPermission(perm);
8639            }
8640        }
8641        return allowed;
8642    }
8643
8644    final class ActivityIntentResolver
8645            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8646        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8647                boolean defaultOnly, int userId) {
8648            if (!sUserManager.exists(userId)) return null;
8649            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8650            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8651        }
8652
8653        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8654                int userId) {
8655            if (!sUserManager.exists(userId)) return null;
8656            mFlags = flags;
8657            return super.queryIntent(intent, resolvedType,
8658                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8659        }
8660
8661        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8662                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8663            if (!sUserManager.exists(userId)) return null;
8664            if (packageActivities == null) {
8665                return null;
8666            }
8667            mFlags = flags;
8668            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8669            final int N = packageActivities.size();
8670            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8671                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8672
8673            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8674            for (int i = 0; i < N; ++i) {
8675                intentFilters = packageActivities.get(i).intents;
8676                if (intentFilters != null && intentFilters.size() > 0) {
8677                    PackageParser.ActivityIntentInfo[] array =
8678                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8679                    intentFilters.toArray(array);
8680                    listCut.add(array);
8681                }
8682            }
8683            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8684        }
8685
8686        public final void addActivity(PackageParser.Activity a, String type) {
8687            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8688            mActivities.put(a.getComponentName(), a);
8689            if (DEBUG_SHOW_INFO)
8690                Log.v(
8691                TAG, "  " + type + " " +
8692                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8693            if (DEBUG_SHOW_INFO)
8694                Log.v(TAG, "    Class=" + a.info.name);
8695            final int NI = a.intents.size();
8696            for (int j=0; j<NI; j++) {
8697                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8698                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8699                    intent.setPriority(0);
8700                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8701                            + a.className + " with priority > 0, forcing to 0");
8702                }
8703                if (DEBUG_SHOW_INFO) {
8704                    Log.v(TAG, "    IntentFilter:");
8705                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8706                }
8707                if (!intent.debugCheck()) {
8708                    Log.w(TAG, "==> For Activity " + a.info.name);
8709                }
8710                addFilter(intent);
8711            }
8712        }
8713
8714        public final void removeActivity(PackageParser.Activity a, String type) {
8715            mActivities.remove(a.getComponentName());
8716            if (DEBUG_SHOW_INFO) {
8717                Log.v(TAG, "  " + type + " "
8718                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8719                                : a.info.name) + ":");
8720                Log.v(TAG, "    Class=" + a.info.name);
8721            }
8722            final int NI = a.intents.size();
8723            for (int j=0; j<NI; j++) {
8724                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8725                if (DEBUG_SHOW_INFO) {
8726                    Log.v(TAG, "    IntentFilter:");
8727                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8728                }
8729                removeFilter(intent);
8730            }
8731        }
8732
8733        @Override
8734        protected boolean allowFilterResult(
8735                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8736            ActivityInfo filterAi = filter.activity.info;
8737            for (int i=dest.size()-1; i>=0; i--) {
8738                ActivityInfo destAi = dest.get(i).activityInfo;
8739                if (destAi.name == filterAi.name
8740                        && destAi.packageName == filterAi.packageName) {
8741                    return false;
8742                }
8743            }
8744            return true;
8745        }
8746
8747        @Override
8748        protected ActivityIntentInfo[] newArray(int size) {
8749            return new ActivityIntentInfo[size];
8750        }
8751
8752        @Override
8753        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8754            if (!sUserManager.exists(userId)) return true;
8755            PackageParser.Package p = filter.activity.owner;
8756            if (p != null) {
8757                PackageSetting ps = (PackageSetting)p.mExtras;
8758                if (ps != null) {
8759                    // System apps are never considered stopped for purposes of
8760                    // filtering, because there may be no way for the user to
8761                    // actually re-launch them.
8762                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8763                            && ps.getStopped(userId);
8764                }
8765            }
8766            return false;
8767        }
8768
8769        @Override
8770        protected boolean isPackageForFilter(String packageName,
8771                PackageParser.ActivityIntentInfo info) {
8772            return packageName.equals(info.activity.owner.packageName);
8773        }
8774
8775        @Override
8776        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8777                int match, int userId) {
8778            if (!sUserManager.exists(userId)) return null;
8779            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8780                return null;
8781            }
8782            final PackageParser.Activity activity = info.activity;
8783            if (mSafeMode && (activity.info.applicationInfo.flags
8784                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8785                return null;
8786            }
8787            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8788            if (ps == null) {
8789                return null;
8790            }
8791            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8792                    ps.readUserState(userId), userId);
8793            if (ai == null) {
8794                return null;
8795            }
8796            final ResolveInfo res = new ResolveInfo();
8797            res.activityInfo = ai;
8798            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8799                res.filter = info;
8800            }
8801            if (info != null) {
8802                res.handleAllWebDataURI = info.handleAllWebDataURI();
8803            }
8804            res.priority = info.getPriority();
8805            res.preferredOrder = activity.owner.mPreferredOrder;
8806            //System.out.println("Result: " + res.activityInfo.className +
8807            //                   " = " + res.priority);
8808            res.match = match;
8809            res.isDefault = info.hasDefault;
8810            res.labelRes = info.labelRes;
8811            res.nonLocalizedLabel = info.nonLocalizedLabel;
8812            if (userNeedsBadging(userId)) {
8813                res.noResourceId = true;
8814            } else {
8815                res.icon = info.icon;
8816            }
8817            res.iconResourceId = info.icon;
8818            res.system = res.activityInfo.applicationInfo.isSystemApp();
8819            return res;
8820        }
8821
8822        @Override
8823        protected void sortResults(List<ResolveInfo> results) {
8824            Collections.sort(results, mResolvePrioritySorter);
8825        }
8826
8827        @Override
8828        protected void dumpFilter(PrintWriter out, String prefix,
8829                PackageParser.ActivityIntentInfo filter) {
8830            out.print(prefix); out.print(
8831                    Integer.toHexString(System.identityHashCode(filter.activity)));
8832                    out.print(' ');
8833                    filter.activity.printComponentShortName(out);
8834                    out.print(" filter ");
8835                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8836        }
8837
8838        @Override
8839        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8840            return filter.activity;
8841        }
8842
8843        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8844            PackageParser.Activity activity = (PackageParser.Activity)label;
8845            out.print(prefix); out.print(
8846                    Integer.toHexString(System.identityHashCode(activity)));
8847                    out.print(' ');
8848                    activity.printComponentShortName(out);
8849            if (count > 1) {
8850                out.print(" ("); out.print(count); out.print(" filters)");
8851            }
8852            out.println();
8853        }
8854
8855//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8856//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8857//            final List<ResolveInfo> retList = Lists.newArrayList();
8858//            while (i.hasNext()) {
8859//                final ResolveInfo resolveInfo = i.next();
8860//                if (isEnabledLP(resolveInfo.activityInfo)) {
8861//                    retList.add(resolveInfo);
8862//                }
8863//            }
8864//            return retList;
8865//        }
8866
8867        // Keys are String (activity class name), values are Activity.
8868        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8869                = new ArrayMap<ComponentName, PackageParser.Activity>();
8870        private int mFlags;
8871    }
8872
8873    private final class ServiceIntentResolver
8874            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8875        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8876                boolean defaultOnly, int userId) {
8877            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8878            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8879        }
8880
8881        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8882                int userId) {
8883            if (!sUserManager.exists(userId)) return null;
8884            mFlags = flags;
8885            return super.queryIntent(intent, resolvedType,
8886                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8887        }
8888
8889        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8890                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8891            if (!sUserManager.exists(userId)) return null;
8892            if (packageServices == null) {
8893                return null;
8894            }
8895            mFlags = flags;
8896            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8897            final int N = packageServices.size();
8898            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8899                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8900
8901            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8902            for (int i = 0; i < N; ++i) {
8903                intentFilters = packageServices.get(i).intents;
8904                if (intentFilters != null && intentFilters.size() > 0) {
8905                    PackageParser.ServiceIntentInfo[] array =
8906                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8907                    intentFilters.toArray(array);
8908                    listCut.add(array);
8909                }
8910            }
8911            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8912        }
8913
8914        public final void addService(PackageParser.Service s) {
8915            mServices.put(s.getComponentName(), s);
8916            if (DEBUG_SHOW_INFO) {
8917                Log.v(TAG, "  "
8918                        + (s.info.nonLocalizedLabel != null
8919                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8920                Log.v(TAG, "    Class=" + s.info.name);
8921            }
8922            final int NI = s.intents.size();
8923            int j;
8924            for (j=0; j<NI; j++) {
8925                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8926                if (DEBUG_SHOW_INFO) {
8927                    Log.v(TAG, "    IntentFilter:");
8928                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8929                }
8930                if (!intent.debugCheck()) {
8931                    Log.w(TAG, "==> For Service " + s.info.name);
8932                }
8933                addFilter(intent);
8934            }
8935        }
8936
8937        public final void removeService(PackageParser.Service s) {
8938            mServices.remove(s.getComponentName());
8939            if (DEBUG_SHOW_INFO) {
8940                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8941                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8942                Log.v(TAG, "    Class=" + s.info.name);
8943            }
8944            final int NI = s.intents.size();
8945            int j;
8946            for (j=0; j<NI; j++) {
8947                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8948                if (DEBUG_SHOW_INFO) {
8949                    Log.v(TAG, "    IntentFilter:");
8950                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8951                }
8952                removeFilter(intent);
8953            }
8954        }
8955
8956        @Override
8957        protected boolean allowFilterResult(
8958                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8959            ServiceInfo filterSi = filter.service.info;
8960            for (int i=dest.size()-1; i>=0; i--) {
8961                ServiceInfo destAi = dest.get(i).serviceInfo;
8962                if (destAi.name == filterSi.name
8963                        && destAi.packageName == filterSi.packageName) {
8964                    return false;
8965                }
8966            }
8967            return true;
8968        }
8969
8970        @Override
8971        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8972            return new PackageParser.ServiceIntentInfo[size];
8973        }
8974
8975        @Override
8976        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8977            if (!sUserManager.exists(userId)) return true;
8978            PackageParser.Package p = filter.service.owner;
8979            if (p != null) {
8980                PackageSetting ps = (PackageSetting)p.mExtras;
8981                if (ps != null) {
8982                    // System apps are never considered stopped for purposes of
8983                    // filtering, because there may be no way for the user to
8984                    // actually re-launch them.
8985                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8986                            && ps.getStopped(userId);
8987                }
8988            }
8989            return false;
8990        }
8991
8992        @Override
8993        protected boolean isPackageForFilter(String packageName,
8994                PackageParser.ServiceIntentInfo info) {
8995            return packageName.equals(info.service.owner.packageName);
8996        }
8997
8998        @Override
8999        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9000                int match, int userId) {
9001            if (!sUserManager.exists(userId)) return null;
9002            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9003            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9004                return null;
9005            }
9006            final PackageParser.Service service = info.service;
9007            if (mSafeMode && (service.info.applicationInfo.flags
9008                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9009                return null;
9010            }
9011            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9012            if (ps == null) {
9013                return null;
9014            }
9015            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9016                    ps.readUserState(userId), userId);
9017            if (si == null) {
9018                return null;
9019            }
9020            final ResolveInfo res = new ResolveInfo();
9021            res.serviceInfo = si;
9022            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9023                res.filter = filter;
9024            }
9025            res.priority = info.getPriority();
9026            res.preferredOrder = service.owner.mPreferredOrder;
9027            res.match = match;
9028            res.isDefault = info.hasDefault;
9029            res.labelRes = info.labelRes;
9030            res.nonLocalizedLabel = info.nonLocalizedLabel;
9031            res.icon = info.icon;
9032            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9033            return res;
9034        }
9035
9036        @Override
9037        protected void sortResults(List<ResolveInfo> results) {
9038            Collections.sort(results, mResolvePrioritySorter);
9039        }
9040
9041        @Override
9042        protected void dumpFilter(PrintWriter out, String prefix,
9043                PackageParser.ServiceIntentInfo filter) {
9044            out.print(prefix); out.print(
9045                    Integer.toHexString(System.identityHashCode(filter.service)));
9046                    out.print(' ');
9047                    filter.service.printComponentShortName(out);
9048                    out.print(" filter ");
9049                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9050        }
9051
9052        @Override
9053        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9054            return filter.service;
9055        }
9056
9057        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9058            PackageParser.Service service = (PackageParser.Service)label;
9059            out.print(prefix); out.print(
9060                    Integer.toHexString(System.identityHashCode(service)));
9061                    out.print(' ');
9062                    service.printComponentShortName(out);
9063            if (count > 1) {
9064                out.print(" ("); out.print(count); out.print(" filters)");
9065            }
9066            out.println();
9067        }
9068
9069//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9070//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9071//            final List<ResolveInfo> retList = Lists.newArrayList();
9072//            while (i.hasNext()) {
9073//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9074//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9075//                    retList.add(resolveInfo);
9076//                }
9077//            }
9078//            return retList;
9079//        }
9080
9081        // Keys are String (activity class name), values are Activity.
9082        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9083                = new ArrayMap<ComponentName, PackageParser.Service>();
9084        private int mFlags;
9085    };
9086
9087    private final class ProviderIntentResolver
9088            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9089        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9090                boolean defaultOnly, int userId) {
9091            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9092            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9093        }
9094
9095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9096                int userId) {
9097            if (!sUserManager.exists(userId))
9098                return null;
9099            mFlags = flags;
9100            return super.queryIntent(intent, resolvedType,
9101                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9102        }
9103
9104        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9105                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9106            if (!sUserManager.exists(userId))
9107                return null;
9108            if (packageProviders == null) {
9109                return null;
9110            }
9111            mFlags = flags;
9112            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9113            final int N = packageProviders.size();
9114            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9115                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9116
9117            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9118            for (int i = 0; i < N; ++i) {
9119                intentFilters = packageProviders.get(i).intents;
9120                if (intentFilters != null && intentFilters.size() > 0) {
9121                    PackageParser.ProviderIntentInfo[] array =
9122                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9123                    intentFilters.toArray(array);
9124                    listCut.add(array);
9125                }
9126            }
9127            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9128        }
9129
9130        public final void addProvider(PackageParser.Provider p) {
9131            if (mProviders.containsKey(p.getComponentName())) {
9132                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9133                return;
9134            }
9135
9136            mProviders.put(p.getComponentName(), p);
9137            if (DEBUG_SHOW_INFO) {
9138                Log.v(TAG, "  "
9139                        + (p.info.nonLocalizedLabel != null
9140                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9141                Log.v(TAG, "    Class=" + p.info.name);
9142            }
9143            final int NI = p.intents.size();
9144            int j;
9145            for (j = 0; j < NI; j++) {
9146                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9147                if (DEBUG_SHOW_INFO) {
9148                    Log.v(TAG, "    IntentFilter:");
9149                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9150                }
9151                if (!intent.debugCheck()) {
9152                    Log.w(TAG, "==> For Provider " + p.info.name);
9153                }
9154                addFilter(intent);
9155            }
9156        }
9157
9158        public final void removeProvider(PackageParser.Provider p) {
9159            mProviders.remove(p.getComponentName());
9160            if (DEBUG_SHOW_INFO) {
9161                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9162                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9163                Log.v(TAG, "    Class=" + p.info.name);
9164            }
9165            final int NI = p.intents.size();
9166            int j;
9167            for (j = 0; j < NI; j++) {
9168                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9169                if (DEBUG_SHOW_INFO) {
9170                    Log.v(TAG, "    IntentFilter:");
9171                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9172                }
9173                removeFilter(intent);
9174            }
9175        }
9176
9177        @Override
9178        protected boolean allowFilterResult(
9179                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9180            ProviderInfo filterPi = filter.provider.info;
9181            for (int i = dest.size() - 1; i >= 0; i--) {
9182                ProviderInfo destPi = dest.get(i).providerInfo;
9183                if (destPi.name == filterPi.name
9184                        && destPi.packageName == filterPi.packageName) {
9185                    return false;
9186                }
9187            }
9188            return true;
9189        }
9190
9191        @Override
9192        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9193            return new PackageParser.ProviderIntentInfo[size];
9194        }
9195
9196        @Override
9197        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9198            if (!sUserManager.exists(userId))
9199                return true;
9200            PackageParser.Package p = filter.provider.owner;
9201            if (p != null) {
9202                PackageSetting ps = (PackageSetting) p.mExtras;
9203                if (ps != null) {
9204                    // System apps are never considered stopped for purposes of
9205                    // filtering, because there may be no way for the user to
9206                    // actually re-launch them.
9207                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9208                            && ps.getStopped(userId);
9209                }
9210            }
9211            return false;
9212        }
9213
9214        @Override
9215        protected boolean isPackageForFilter(String packageName,
9216                PackageParser.ProviderIntentInfo info) {
9217            return packageName.equals(info.provider.owner.packageName);
9218        }
9219
9220        @Override
9221        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9222                int match, int userId) {
9223            if (!sUserManager.exists(userId))
9224                return null;
9225            final PackageParser.ProviderIntentInfo info = filter;
9226            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9227                return null;
9228            }
9229            final PackageParser.Provider provider = info.provider;
9230            if (mSafeMode && (provider.info.applicationInfo.flags
9231                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9232                return null;
9233            }
9234            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9235            if (ps == null) {
9236                return null;
9237            }
9238            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9239                    ps.readUserState(userId), userId);
9240            if (pi == null) {
9241                return null;
9242            }
9243            final ResolveInfo res = new ResolveInfo();
9244            res.providerInfo = pi;
9245            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9246                res.filter = filter;
9247            }
9248            res.priority = info.getPriority();
9249            res.preferredOrder = provider.owner.mPreferredOrder;
9250            res.match = match;
9251            res.isDefault = info.hasDefault;
9252            res.labelRes = info.labelRes;
9253            res.nonLocalizedLabel = info.nonLocalizedLabel;
9254            res.icon = info.icon;
9255            res.system = res.providerInfo.applicationInfo.isSystemApp();
9256            return res;
9257        }
9258
9259        @Override
9260        protected void sortResults(List<ResolveInfo> results) {
9261            Collections.sort(results, mResolvePrioritySorter);
9262        }
9263
9264        @Override
9265        protected void dumpFilter(PrintWriter out, String prefix,
9266                PackageParser.ProviderIntentInfo filter) {
9267            out.print(prefix);
9268            out.print(
9269                    Integer.toHexString(System.identityHashCode(filter.provider)));
9270            out.print(' ');
9271            filter.provider.printComponentShortName(out);
9272            out.print(" filter ");
9273            out.println(Integer.toHexString(System.identityHashCode(filter)));
9274        }
9275
9276        @Override
9277        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9278            return filter.provider;
9279        }
9280
9281        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9282            PackageParser.Provider provider = (PackageParser.Provider)label;
9283            out.print(prefix); out.print(
9284                    Integer.toHexString(System.identityHashCode(provider)));
9285                    out.print(' ');
9286                    provider.printComponentShortName(out);
9287            if (count > 1) {
9288                out.print(" ("); out.print(count); out.print(" filters)");
9289            }
9290            out.println();
9291        }
9292
9293        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9294                = new ArrayMap<ComponentName, PackageParser.Provider>();
9295        private int mFlags;
9296    };
9297
9298    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9299            new Comparator<ResolveInfo>() {
9300        public int compare(ResolveInfo r1, ResolveInfo r2) {
9301            int v1 = r1.priority;
9302            int v2 = r2.priority;
9303            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9304            if (v1 != v2) {
9305                return (v1 > v2) ? -1 : 1;
9306            }
9307            v1 = r1.preferredOrder;
9308            v2 = r2.preferredOrder;
9309            if (v1 != v2) {
9310                return (v1 > v2) ? -1 : 1;
9311            }
9312            if (r1.isDefault != r2.isDefault) {
9313                return r1.isDefault ? -1 : 1;
9314            }
9315            v1 = r1.match;
9316            v2 = r2.match;
9317            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9318            if (v1 != v2) {
9319                return (v1 > v2) ? -1 : 1;
9320            }
9321            if (r1.system != r2.system) {
9322                return r1.system ? -1 : 1;
9323            }
9324            return 0;
9325        }
9326    };
9327
9328    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9329            new Comparator<ProviderInfo>() {
9330        public int compare(ProviderInfo p1, ProviderInfo p2) {
9331            final int v1 = p1.initOrder;
9332            final int v2 = p2.initOrder;
9333            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9334        }
9335    };
9336
9337    final void sendPackageBroadcast(final String action, final String pkg,
9338            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9339            final int[] userIds) {
9340        mHandler.post(new Runnable() {
9341            @Override
9342            public void run() {
9343                try {
9344                    final IActivityManager am = ActivityManagerNative.getDefault();
9345                    if (am == null) return;
9346                    final int[] resolvedUserIds;
9347                    if (userIds == null) {
9348                        resolvedUserIds = am.getRunningUserIds();
9349                    } else {
9350                        resolvedUserIds = userIds;
9351                    }
9352                    for (int id : resolvedUserIds) {
9353                        final Intent intent = new Intent(action,
9354                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9355                        if (extras != null) {
9356                            intent.putExtras(extras);
9357                        }
9358                        if (targetPkg != null) {
9359                            intent.setPackage(targetPkg);
9360                        }
9361                        // Modify the UID when posting to other users
9362                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9363                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9364                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9365                            intent.putExtra(Intent.EXTRA_UID, uid);
9366                        }
9367                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9368                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9369                        if (DEBUG_BROADCASTS) {
9370                            RuntimeException here = new RuntimeException("here");
9371                            here.fillInStackTrace();
9372                            Slog.d(TAG, "Sending to user " + id + ": "
9373                                    + intent.toShortString(false, true, false, false)
9374                                    + " " + intent.getExtras(), here);
9375                        }
9376                        am.broadcastIntent(null, intent, null, finishedReceiver,
9377                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9378                                null, finishedReceiver != null, false, id);
9379                    }
9380                } catch (RemoteException ex) {
9381                }
9382            }
9383        });
9384    }
9385
9386    /**
9387     * Check if the external storage media is available. This is true if there
9388     * is a mounted external storage medium or if the external storage is
9389     * emulated.
9390     */
9391    private boolean isExternalMediaAvailable() {
9392        return mMediaMounted || Environment.isExternalStorageEmulated();
9393    }
9394
9395    @Override
9396    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9397        // writer
9398        synchronized (mPackages) {
9399            if (!isExternalMediaAvailable()) {
9400                // If the external storage is no longer mounted at this point,
9401                // the caller may not have been able to delete all of this
9402                // packages files and can not delete any more.  Bail.
9403                return null;
9404            }
9405            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9406            if (lastPackage != null) {
9407                pkgs.remove(lastPackage);
9408            }
9409            if (pkgs.size() > 0) {
9410                return pkgs.get(0);
9411            }
9412        }
9413        return null;
9414    }
9415
9416    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9417        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9418                userId, andCode ? 1 : 0, packageName);
9419        if (mSystemReady) {
9420            msg.sendToTarget();
9421        } else {
9422            if (mPostSystemReadyMessages == null) {
9423                mPostSystemReadyMessages = new ArrayList<>();
9424            }
9425            mPostSystemReadyMessages.add(msg);
9426        }
9427    }
9428
9429    void startCleaningPackages() {
9430        // reader
9431        synchronized (mPackages) {
9432            if (!isExternalMediaAvailable()) {
9433                return;
9434            }
9435            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9436                return;
9437            }
9438        }
9439        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9440        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9441        IActivityManager am = ActivityManagerNative.getDefault();
9442        if (am != null) {
9443            try {
9444                am.startService(null, intent, null, mContext.getOpPackageName(),
9445                        UserHandle.USER_OWNER);
9446            } catch (RemoteException e) {
9447            }
9448        }
9449    }
9450
9451    @Override
9452    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9453            int installFlags, String installerPackageName, VerificationParams verificationParams,
9454            String packageAbiOverride) {
9455        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9456                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9457    }
9458
9459    @Override
9460    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9461            int installFlags, String installerPackageName, VerificationParams verificationParams,
9462            String packageAbiOverride, int userId) {
9463        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9464
9465        final int callingUid = Binder.getCallingUid();
9466        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9467
9468        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9469            try {
9470                if (observer != null) {
9471                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9472                }
9473            } catch (RemoteException re) {
9474            }
9475            return;
9476        }
9477
9478        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9479            installFlags |= PackageManager.INSTALL_FROM_ADB;
9480
9481        } else {
9482            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9483            // about installerPackageName.
9484
9485            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9486            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9487        }
9488
9489        UserHandle user;
9490        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9491            user = UserHandle.ALL;
9492        } else {
9493            user = new UserHandle(userId);
9494        }
9495
9496        // Only system components can circumvent runtime permissions when installing.
9497        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9498                && mContext.checkCallingOrSelfPermission(Manifest.permission
9499                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9500            throw new SecurityException("You need the "
9501                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9502                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9503        }
9504
9505        verificationParams.setInstallerUid(callingUid);
9506
9507        final File originFile = new File(originPath);
9508        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9509
9510        final Message msg = mHandler.obtainMessage(INIT_COPY);
9511        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9512                null, verificationParams, user, packageAbiOverride, null);
9513        mHandler.sendMessage(msg);
9514    }
9515
9516    void installStage(String packageName, File stagedDir, String stagedCid,
9517            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9518            String installerPackageName, int installerUid, UserHandle user) {
9519        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9520                params.referrerUri, installerUid, null);
9521        verifParams.setInstallerUid(installerUid);
9522
9523        final OriginInfo origin;
9524        if (stagedDir != null) {
9525            origin = OriginInfo.fromStagedFile(stagedDir);
9526        } else {
9527            origin = OriginInfo.fromStagedContainer(stagedCid);
9528        }
9529
9530        final Message msg = mHandler.obtainMessage(INIT_COPY);
9531        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9532                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9533                params.grantedRuntimePermissions);
9534        mHandler.sendMessage(msg);
9535    }
9536
9537    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9538        Bundle extras = new Bundle(1);
9539        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9540
9541        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9542                packageName, extras, null, null, new int[] {userId});
9543        try {
9544            IActivityManager am = ActivityManagerNative.getDefault();
9545            final boolean isSystem =
9546                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9547            if (isSystem && am.isUserRunning(userId, false)) {
9548                // The just-installed/enabled app is bundled on the system, so presumed
9549                // to be able to run automatically without needing an explicit launch.
9550                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9551                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9552                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9553                        .setPackage(packageName);
9554                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9555                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9556            }
9557        } catch (RemoteException e) {
9558            // shouldn't happen
9559            Slog.w(TAG, "Unable to bootstrap installed package", e);
9560        }
9561    }
9562
9563    @Override
9564    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9565            int userId) {
9566        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9567        PackageSetting pkgSetting;
9568        final int uid = Binder.getCallingUid();
9569        enforceCrossUserPermission(uid, userId, true, true,
9570                "setApplicationHiddenSetting for user " + userId);
9571
9572        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9573            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9574            return false;
9575        }
9576
9577        long callingId = Binder.clearCallingIdentity();
9578        try {
9579            boolean sendAdded = false;
9580            boolean sendRemoved = false;
9581            // writer
9582            synchronized (mPackages) {
9583                pkgSetting = mSettings.mPackages.get(packageName);
9584                if (pkgSetting == null) {
9585                    return false;
9586                }
9587                if (pkgSetting.getHidden(userId) != hidden) {
9588                    pkgSetting.setHidden(hidden, userId);
9589                    mSettings.writePackageRestrictionsLPr(userId);
9590                    if (hidden) {
9591                        sendRemoved = true;
9592                    } else {
9593                        sendAdded = true;
9594                    }
9595                }
9596            }
9597            if (sendAdded) {
9598                sendPackageAddedForUser(packageName, pkgSetting, userId);
9599                return true;
9600            }
9601            if (sendRemoved) {
9602                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9603                        "hiding pkg");
9604                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9605                return true;
9606            }
9607        } finally {
9608            Binder.restoreCallingIdentity(callingId);
9609        }
9610        return false;
9611    }
9612
9613    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9614            int userId) {
9615        final PackageRemovedInfo info = new PackageRemovedInfo();
9616        info.removedPackage = packageName;
9617        info.removedUsers = new int[] {userId};
9618        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9619        info.sendBroadcast(false, false, false);
9620    }
9621
9622    /**
9623     * Returns true if application is not found or there was an error. Otherwise it returns
9624     * the hidden state of the package for the given user.
9625     */
9626    @Override
9627    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9628        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9629        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9630                false, "getApplicationHidden for user " + userId);
9631        PackageSetting pkgSetting;
9632        long callingId = Binder.clearCallingIdentity();
9633        try {
9634            // writer
9635            synchronized (mPackages) {
9636                pkgSetting = mSettings.mPackages.get(packageName);
9637                if (pkgSetting == null) {
9638                    return true;
9639                }
9640                return pkgSetting.getHidden(userId);
9641            }
9642        } finally {
9643            Binder.restoreCallingIdentity(callingId);
9644        }
9645    }
9646
9647    /**
9648     * @hide
9649     */
9650    @Override
9651    public int installExistingPackageAsUser(String packageName, int userId) {
9652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9653                null);
9654        PackageSetting pkgSetting;
9655        final int uid = Binder.getCallingUid();
9656        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9657                + userId);
9658        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9659            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9660        }
9661
9662        long callingId = Binder.clearCallingIdentity();
9663        try {
9664            boolean sendAdded = false;
9665
9666            // writer
9667            synchronized (mPackages) {
9668                pkgSetting = mSettings.mPackages.get(packageName);
9669                if (pkgSetting == null) {
9670                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9671                }
9672                if (!pkgSetting.getInstalled(userId)) {
9673                    pkgSetting.setInstalled(true, userId);
9674                    pkgSetting.setHidden(false, userId);
9675                    mSettings.writePackageRestrictionsLPr(userId);
9676                    sendAdded = true;
9677                }
9678            }
9679
9680            if (sendAdded) {
9681                sendPackageAddedForUser(packageName, pkgSetting, userId);
9682            }
9683        } finally {
9684            Binder.restoreCallingIdentity(callingId);
9685        }
9686
9687        return PackageManager.INSTALL_SUCCEEDED;
9688    }
9689
9690    boolean isUserRestricted(int userId, String restrictionKey) {
9691        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9692        if (restrictions.getBoolean(restrictionKey, false)) {
9693            Log.w(TAG, "User is restricted: " + restrictionKey);
9694            return true;
9695        }
9696        return false;
9697    }
9698
9699    @Override
9700    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9701        mContext.enforceCallingOrSelfPermission(
9702                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9703                "Only package verification agents can verify applications");
9704
9705        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9706        final PackageVerificationResponse response = new PackageVerificationResponse(
9707                verificationCode, Binder.getCallingUid());
9708        msg.arg1 = id;
9709        msg.obj = response;
9710        mHandler.sendMessage(msg);
9711    }
9712
9713    @Override
9714    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9715            long millisecondsToDelay) {
9716        mContext.enforceCallingOrSelfPermission(
9717                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9718                "Only package verification agents can extend verification timeouts");
9719
9720        final PackageVerificationState state = mPendingVerification.get(id);
9721        final PackageVerificationResponse response = new PackageVerificationResponse(
9722                verificationCodeAtTimeout, Binder.getCallingUid());
9723
9724        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9725            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9726        }
9727        if (millisecondsToDelay < 0) {
9728            millisecondsToDelay = 0;
9729        }
9730        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9731                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9732            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9733        }
9734
9735        if ((state != null) && !state.timeoutExtended()) {
9736            state.extendTimeout();
9737
9738            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9739            msg.arg1 = id;
9740            msg.obj = response;
9741            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9742        }
9743    }
9744
9745    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9746            int verificationCode, UserHandle user) {
9747        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9748        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9749        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9750        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9751        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9752
9753        mContext.sendBroadcastAsUser(intent, user,
9754                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9755    }
9756
9757    private ComponentName matchComponentForVerifier(String packageName,
9758            List<ResolveInfo> receivers) {
9759        ActivityInfo targetReceiver = null;
9760
9761        final int NR = receivers.size();
9762        for (int i = 0; i < NR; i++) {
9763            final ResolveInfo info = receivers.get(i);
9764            if (info.activityInfo == null) {
9765                continue;
9766            }
9767
9768            if (packageName.equals(info.activityInfo.packageName)) {
9769                targetReceiver = info.activityInfo;
9770                break;
9771            }
9772        }
9773
9774        if (targetReceiver == null) {
9775            return null;
9776        }
9777
9778        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9779    }
9780
9781    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9782            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9783        if (pkgInfo.verifiers.length == 0) {
9784            return null;
9785        }
9786
9787        final int N = pkgInfo.verifiers.length;
9788        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9789        for (int i = 0; i < N; i++) {
9790            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9791
9792            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9793                    receivers);
9794            if (comp == null) {
9795                continue;
9796            }
9797
9798            final int verifierUid = getUidForVerifier(verifierInfo);
9799            if (verifierUid == -1) {
9800                continue;
9801            }
9802
9803            if (DEBUG_VERIFY) {
9804                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9805                        + " with the correct signature");
9806            }
9807            sufficientVerifiers.add(comp);
9808            verificationState.addSufficientVerifier(verifierUid);
9809        }
9810
9811        return sufficientVerifiers;
9812    }
9813
9814    private int getUidForVerifier(VerifierInfo verifierInfo) {
9815        synchronized (mPackages) {
9816            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9817            if (pkg == null) {
9818                return -1;
9819            } else if (pkg.mSignatures.length != 1) {
9820                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9821                        + " has more than one signature; ignoring");
9822                return -1;
9823            }
9824
9825            /*
9826             * If the public key of the package's signature does not match
9827             * our expected public key, then this is a different package and
9828             * we should skip.
9829             */
9830
9831            final byte[] expectedPublicKey;
9832            try {
9833                final Signature verifierSig = pkg.mSignatures[0];
9834                final PublicKey publicKey = verifierSig.getPublicKey();
9835                expectedPublicKey = publicKey.getEncoded();
9836            } catch (CertificateException e) {
9837                return -1;
9838            }
9839
9840            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9841
9842            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9843                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9844                        + " does not have the expected public key; ignoring");
9845                return -1;
9846            }
9847
9848            return pkg.applicationInfo.uid;
9849        }
9850    }
9851
9852    @Override
9853    public void finishPackageInstall(int token) {
9854        enforceSystemOrRoot("Only the system is allowed to finish installs");
9855
9856        if (DEBUG_INSTALL) {
9857            Slog.v(TAG, "BM finishing package install for " + token);
9858        }
9859
9860        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9861        mHandler.sendMessage(msg);
9862    }
9863
9864    /**
9865     * Get the verification agent timeout.
9866     *
9867     * @return verification timeout in milliseconds
9868     */
9869    private long getVerificationTimeout() {
9870        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9871                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9872                DEFAULT_VERIFICATION_TIMEOUT);
9873    }
9874
9875    /**
9876     * Get the default verification agent response code.
9877     *
9878     * @return default verification response code
9879     */
9880    private int getDefaultVerificationResponse() {
9881        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9882                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9883                DEFAULT_VERIFICATION_RESPONSE);
9884    }
9885
9886    /**
9887     * Check whether or not package verification has been enabled.
9888     *
9889     * @return true if verification should be performed
9890     */
9891    private boolean isVerificationEnabled(int userId, int installFlags) {
9892        if (!DEFAULT_VERIFY_ENABLE) {
9893            return false;
9894        }
9895
9896        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9897
9898        // Check if installing from ADB
9899        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9900            // Do not run verification in a test harness environment
9901            if (ActivityManager.isRunningInTestHarness()) {
9902                return false;
9903            }
9904            if (ensureVerifyAppsEnabled) {
9905                return true;
9906            }
9907            // Check if the developer does not want package verification for ADB installs
9908            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9909                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9910                return false;
9911            }
9912        }
9913
9914        if (ensureVerifyAppsEnabled) {
9915            return true;
9916        }
9917
9918        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9919                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9920    }
9921
9922    @Override
9923    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9924            throws RemoteException {
9925        mContext.enforceCallingOrSelfPermission(
9926                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9927                "Only intentfilter verification agents can verify applications");
9928
9929        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9930        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9931                Binder.getCallingUid(), verificationCode, failedDomains);
9932        msg.arg1 = id;
9933        msg.obj = response;
9934        mHandler.sendMessage(msg);
9935    }
9936
9937    @Override
9938    public int getIntentVerificationStatus(String packageName, int userId) {
9939        synchronized (mPackages) {
9940            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9941        }
9942    }
9943
9944    @Override
9945    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9946        mContext.enforceCallingOrSelfPermission(
9947                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9948
9949        boolean result = false;
9950        synchronized (mPackages) {
9951            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9952        }
9953        if (result) {
9954            scheduleWritePackageRestrictionsLocked(userId);
9955        }
9956        return result;
9957    }
9958
9959    @Override
9960    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9961        synchronized (mPackages) {
9962            return mSettings.getIntentFilterVerificationsLPr(packageName);
9963        }
9964    }
9965
9966    @Override
9967    public List<IntentFilter> getAllIntentFilters(String packageName) {
9968        if (TextUtils.isEmpty(packageName)) {
9969            return Collections.<IntentFilter>emptyList();
9970        }
9971        synchronized (mPackages) {
9972            PackageParser.Package pkg = mPackages.get(packageName);
9973            if (pkg == null || pkg.activities == null) {
9974                return Collections.<IntentFilter>emptyList();
9975            }
9976            final int count = pkg.activities.size();
9977            ArrayList<IntentFilter> result = new ArrayList<>();
9978            for (int n=0; n<count; n++) {
9979                PackageParser.Activity activity = pkg.activities.get(n);
9980                if (activity.intents != null || activity.intents.size() > 0) {
9981                    result.addAll(activity.intents);
9982                }
9983            }
9984            return result;
9985        }
9986    }
9987
9988    @Override
9989    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9990        mContext.enforceCallingOrSelfPermission(
9991                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9992
9993        synchronized (mPackages) {
9994            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9995            if (packageName != null) {
9996                result |= updateIntentVerificationStatus(packageName,
9997                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9998                        userId);
9999                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10000                        packageName, userId);
10001            }
10002            return result;
10003        }
10004    }
10005
10006    @Override
10007    public String getDefaultBrowserPackageName(int userId) {
10008        synchronized (mPackages) {
10009            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10010        }
10011    }
10012
10013    /**
10014     * Get the "allow unknown sources" setting.
10015     *
10016     * @return the current "allow unknown sources" setting
10017     */
10018    private int getUnknownSourcesSettings() {
10019        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10020                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10021                -1);
10022    }
10023
10024    @Override
10025    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10026        final int uid = Binder.getCallingUid();
10027        // writer
10028        synchronized (mPackages) {
10029            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10030            if (targetPackageSetting == null) {
10031                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10032            }
10033
10034            PackageSetting installerPackageSetting;
10035            if (installerPackageName != null) {
10036                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10037                if (installerPackageSetting == null) {
10038                    throw new IllegalArgumentException("Unknown installer package: "
10039                            + installerPackageName);
10040                }
10041            } else {
10042                installerPackageSetting = null;
10043            }
10044
10045            Signature[] callerSignature;
10046            Object obj = mSettings.getUserIdLPr(uid);
10047            if (obj != null) {
10048                if (obj instanceof SharedUserSetting) {
10049                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10050                } else if (obj instanceof PackageSetting) {
10051                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10052                } else {
10053                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10054                }
10055            } else {
10056                throw new SecurityException("Unknown calling uid " + uid);
10057            }
10058
10059            // Verify: can't set installerPackageName to a package that is
10060            // not signed with the same cert as the caller.
10061            if (installerPackageSetting != null) {
10062                if (compareSignatures(callerSignature,
10063                        installerPackageSetting.signatures.mSignatures)
10064                        != PackageManager.SIGNATURE_MATCH) {
10065                    throw new SecurityException(
10066                            "Caller does not have same cert as new installer package "
10067                            + installerPackageName);
10068                }
10069            }
10070
10071            // Verify: if target already has an installer package, it must
10072            // be signed with the same cert as the caller.
10073            if (targetPackageSetting.installerPackageName != null) {
10074                PackageSetting setting = mSettings.mPackages.get(
10075                        targetPackageSetting.installerPackageName);
10076                // If the currently set package isn't valid, then it's always
10077                // okay to change it.
10078                if (setting != null) {
10079                    if (compareSignatures(callerSignature,
10080                            setting.signatures.mSignatures)
10081                            != PackageManager.SIGNATURE_MATCH) {
10082                        throw new SecurityException(
10083                                "Caller does not have same cert as old installer package "
10084                                + targetPackageSetting.installerPackageName);
10085                    }
10086                }
10087            }
10088
10089            // Okay!
10090            targetPackageSetting.installerPackageName = installerPackageName;
10091            scheduleWriteSettingsLocked();
10092        }
10093    }
10094
10095    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10096        // Queue up an async operation since the package installation may take a little while.
10097        mHandler.post(new Runnable() {
10098            public void run() {
10099                mHandler.removeCallbacks(this);
10100                 // Result object to be returned
10101                PackageInstalledInfo res = new PackageInstalledInfo();
10102                res.returnCode = currentStatus;
10103                res.uid = -1;
10104                res.pkg = null;
10105                res.removedInfo = new PackageRemovedInfo();
10106                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10107                    args.doPreInstall(res.returnCode);
10108                    synchronized (mInstallLock) {
10109                        installPackageLI(args, res);
10110                    }
10111                    args.doPostInstall(res.returnCode, res.uid);
10112                }
10113
10114                // A restore should be performed at this point if (a) the install
10115                // succeeded, (b) the operation is not an update, and (c) the new
10116                // package has not opted out of backup participation.
10117                final boolean update = res.removedInfo.removedPackage != null;
10118                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10119                boolean doRestore = !update
10120                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10121
10122                // Set up the post-install work request bookkeeping.  This will be used
10123                // and cleaned up by the post-install event handling regardless of whether
10124                // there's a restore pass performed.  Token values are >= 1.
10125                int token;
10126                if (mNextInstallToken < 0) mNextInstallToken = 1;
10127                token = mNextInstallToken++;
10128
10129                PostInstallData data = new PostInstallData(args, res);
10130                mRunningInstalls.put(token, data);
10131                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10132
10133                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10134                    // Pass responsibility to the Backup Manager.  It will perform a
10135                    // restore if appropriate, then pass responsibility back to the
10136                    // Package Manager to run the post-install observer callbacks
10137                    // and broadcasts.
10138                    IBackupManager bm = IBackupManager.Stub.asInterface(
10139                            ServiceManager.getService(Context.BACKUP_SERVICE));
10140                    if (bm != null) {
10141                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10142                                + " to BM for possible restore");
10143                        try {
10144                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10145                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10146                            } else {
10147                                doRestore = false;
10148                            }
10149                        } catch (RemoteException e) {
10150                            // can't happen; the backup manager is local
10151                        } catch (Exception e) {
10152                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10153                            doRestore = false;
10154                        }
10155                    } else {
10156                        Slog.e(TAG, "Backup Manager not found!");
10157                        doRestore = false;
10158                    }
10159                }
10160
10161                if (!doRestore) {
10162                    // No restore possible, or the Backup Manager was mysteriously not
10163                    // available -- just fire the post-install work request directly.
10164                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10165                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10166                    mHandler.sendMessage(msg);
10167                }
10168            }
10169        });
10170    }
10171
10172    private abstract class HandlerParams {
10173        private static final int MAX_RETRIES = 4;
10174
10175        /**
10176         * Number of times startCopy() has been attempted and had a non-fatal
10177         * error.
10178         */
10179        private int mRetries = 0;
10180
10181        /** User handle for the user requesting the information or installation. */
10182        private final UserHandle mUser;
10183
10184        HandlerParams(UserHandle user) {
10185            mUser = user;
10186        }
10187
10188        UserHandle getUser() {
10189            return mUser;
10190        }
10191
10192        final boolean startCopy() {
10193            boolean res;
10194            try {
10195                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10196
10197                if (++mRetries > MAX_RETRIES) {
10198                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10199                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10200                    handleServiceError();
10201                    return false;
10202                } else {
10203                    handleStartCopy();
10204                    res = true;
10205                }
10206            } catch (RemoteException e) {
10207                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10208                mHandler.sendEmptyMessage(MCS_RECONNECT);
10209                res = false;
10210            }
10211            handleReturnCode();
10212            return res;
10213        }
10214
10215        final void serviceError() {
10216            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10217            handleServiceError();
10218            handleReturnCode();
10219        }
10220
10221        abstract void handleStartCopy() throws RemoteException;
10222        abstract void handleServiceError();
10223        abstract void handleReturnCode();
10224    }
10225
10226    class MeasureParams extends HandlerParams {
10227        private final PackageStats mStats;
10228        private boolean mSuccess;
10229
10230        private final IPackageStatsObserver mObserver;
10231
10232        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10233            super(new UserHandle(stats.userHandle));
10234            mObserver = observer;
10235            mStats = stats;
10236        }
10237
10238        @Override
10239        public String toString() {
10240            return "MeasureParams{"
10241                + Integer.toHexString(System.identityHashCode(this))
10242                + " " + mStats.packageName + "}";
10243        }
10244
10245        @Override
10246        void handleStartCopy() throws RemoteException {
10247            synchronized (mInstallLock) {
10248                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10249            }
10250
10251            if (mSuccess) {
10252                final boolean mounted;
10253                if (Environment.isExternalStorageEmulated()) {
10254                    mounted = true;
10255                } else {
10256                    final String status = Environment.getExternalStorageState();
10257                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10258                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10259                }
10260
10261                if (mounted) {
10262                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10263
10264                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10265                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10266
10267                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10268                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10269
10270                    // Always subtract cache size, since it's a subdirectory
10271                    mStats.externalDataSize -= mStats.externalCacheSize;
10272
10273                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10274                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10275
10276                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10277                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10278                }
10279            }
10280        }
10281
10282        @Override
10283        void handleReturnCode() {
10284            if (mObserver != null) {
10285                try {
10286                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10287                } catch (RemoteException e) {
10288                    Slog.i(TAG, "Observer no longer exists.");
10289                }
10290            }
10291        }
10292
10293        @Override
10294        void handleServiceError() {
10295            Slog.e(TAG, "Could not measure application " + mStats.packageName
10296                            + " external storage");
10297        }
10298    }
10299
10300    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10301            throws RemoteException {
10302        long result = 0;
10303        for (File path : paths) {
10304            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10305        }
10306        return result;
10307    }
10308
10309    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10310        for (File path : paths) {
10311            try {
10312                mcs.clearDirectory(path.getAbsolutePath());
10313            } catch (RemoteException e) {
10314            }
10315        }
10316    }
10317
10318    static class OriginInfo {
10319        /**
10320         * Location where install is coming from, before it has been
10321         * copied/renamed into place. This could be a single monolithic APK
10322         * file, or a cluster directory. This location may be untrusted.
10323         */
10324        final File file;
10325        final String cid;
10326
10327        /**
10328         * Flag indicating that {@link #file} or {@link #cid} has already been
10329         * staged, meaning downstream users don't need to defensively copy the
10330         * contents.
10331         */
10332        final boolean staged;
10333
10334        /**
10335         * Flag indicating that {@link #file} or {@link #cid} is an already
10336         * installed app that is being moved.
10337         */
10338        final boolean existing;
10339
10340        final String resolvedPath;
10341        final File resolvedFile;
10342
10343        static OriginInfo fromNothing() {
10344            return new OriginInfo(null, null, false, false);
10345        }
10346
10347        static OriginInfo fromUntrustedFile(File file) {
10348            return new OriginInfo(file, null, false, false);
10349        }
10350
10351        static OriginInfo fromExistingFile(File file) {
10352            return new OriginInfo(file, null, false, true);
10353        }
10354
10355        static OriginInfo fromStagedFile(File file) {
10356            return new OriginInfo(file, null, true, false);
10357        }
10358
10359        static OriginInfo fromStagedContainer(String cid) {
10360            return new OriginInfo(null, cid, true, false);
10361        }
10362
10363        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10364            this.file = file;
10365            this.cid = cid;
10366            this.staged = staged;
10367            this.existing = existing;
10368
10369            if (cid != null) {
10370                resolvedPath = PackageHelper.getSdDir(cid);
10371                resolvedFile = new File(resolvedPath);
10372            } else if (file != null) {
10373                resolvedPath = file.getAbsolutePath();
10374                resolvedFile = file;
10375            } else {
10376                resolvedPath = null;
10377                resolvedFile = null;
10378            }
10379        }
10380    }
10381
10382    class MoveInfo {
10383        final int moveId;
10384        final String fromUuid;
10385        final String toUuid;
10386        final String packageName;
10387        final String dataAppName;
10388        final int appId;
10389        final String seinfo;
10390
10391        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10392                String dataAppName, int appId, String seinfo) {
10393            this.moveId = moveId;
10394            this.fromUuid = fromUuid;
10395            this.toUuid = toUuid;
10396            this.packageName = packageName;
10397            this.dataAppName = dataAppName;
10398            this.appId = appId;
10399            this.seinfo = seinfo;
10400        }
10401    }
10402
10403    class InstallParams extends HandlerParams {
10404        final OriginInfo origin;
10405        final MoveInfo move;
10406        final IPackageInstallObserver2 observer;
10407        int installFlags;
10408        final String installerPackageName;
10409        final String volumeUuid;
10410        final VerificationParams verificationParams;
10411        private InstallArgs mArgs;
10412        private int mRet;
10413        final String packageAbiOverride;
10414        final String[] grantedRuntimePermissions;
10415
10416
10417        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10418                int installFlags, String installerPackageName, String volumeUuid,
10419                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10420                String[] grantedPermissions) {
10421            super(user);
10422            this.origin = origin;
10423            this.move = move;
10424            this.observer = observer;
10425            this.installFlags = installFlags;
10426            this.installerPackageName = installerPackageName;
10427            this.volumeUuid = volumeUuid;
10428            this.verificationParams = verificationParams;
10429            this.packageAbiOverride = packageAbiOverride;
10430            this.grantedRuntimePermissions = grantedPermissions;
10431        }
10432
10433        @Override
10434        public String toString() {
10435            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10436                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10437        }
10438
10439        public ManifestDigest getManifestDigest() {
10440            if (verificationParams == null) {
10441                return null;
10442            }
10443            return verificationParams.getManifestDigest();
10444        }
10445
10446        private int installLocationPolicy(PackageInfoLite pkgLite) {
10447            String packageName = pkgLite.packageName;
10448            int installLocation = pkgLite.installLocation;
10449            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10450            // reader
10451            synchronized (mPackages) {
10452                PackageParser.Package pkg = mPackages.get(packageName);
10453                if (pkg != null) {
10454                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10455                        // Check for downgrading.
10456                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10457                            try {
10458                                checkDowngrade(pkg, pkgLite);
10459                            } catch (PackageManagerException e) {
10460                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10461                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10462                            }
10463                        }
10464                        // Check for updated system application.
10465                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10466                            if (onSd) {
10467                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10468                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10469                            }
10470                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10471                        } else {
10472                            if (onSd) {
10473                                // Install flag overrides everything.
10474                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10475                            }
10476                            // If current upgrade specifies particular preference
10477                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10478                                // Application explicitly specified internal.
10479                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10480                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10481                                // App explictly prefers external. Let policy decide
10482                            } else {
10483                                // Prefer previous location
10484                                if (isExternal(pkg)) {
10485                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10486                                }
10487                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10488                            }
10489                        }
10490                    } else {
10491                        // Invalid install. Return error code
10492                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10493                    }
10494                }
10495            }
10496            // All the special cases have been taken care of.
10497            // Return result based on recommended install location.
10498            if (onSd) {
10499                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10500            }
10501            return pkgLite.recommendedInstallLocation;
10502        }
10503
10504        /*
10505         * Invoke remote method to get package information and install
10506         * location values. Override install location based on default
10507         * policy if needed and then create install arguments based
10508         * on the install location.
10509         */
10510        public void handleStartCopy() throws RemoteException {
10511            int ret = PackageManager.INSTALL_SUCCEEDED;
10512
10513            // If we're already staged, we've firmly committed to an install location
10514            if (origin.staged) {
10515                if (origin.file != null) {
10516                    installFlags |= PackageManager.INSTALL_INTERNAL;
10517                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10518                } else if (origin.cid != null) {
10519                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10520                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10521                } else {
10522                    throw new IllegalStateException("Invalid stage location");
10523                }
10524            }
10525
10526            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10527            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10528
10529            PackageInfoLite pkgLite = null;
10530
10531            if (onInt && onSd) {
10532                // Check if both bits are set.
10533                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10534                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10535            } else {
10536                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10537                        packageAbiOverride);
10538
10539                /*
10540                 * If we have too little free space, try to free cache
10541                 * before giving up.
10542                 */
10543                if (!origin.staged && pkgLite.recommendedInstallLocation
10544                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10545                    // TODO: focus freeing disk space on the target device
10546                    final StorageManager storage = StorageManager.from(mContext);
10547                    final long lowThreshold = storage.getStorageLowBytes(
10548                            Environment.getDataDirectory());
10549
10550                    final long sizeBytes = mContainerService.calculateInstalledSize(
10551                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10552
10553                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10554                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10555                                installFlags, packageAbiOverride);
10556                    }
10557
10558                    /*
10559                     * The cache free must have deleted the file we
10560                     * downloaded to install.
10561                     *
10562                     * TODO: fix the "freeCache" call to not delete
10563                     *       the file we care about.
10564                     */
10565                    if (pkgLite.recommendedInstallLocation
10566                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10567                        pkgLite.recommendedInstallLocation
10568                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10569                    }
10570                }
10571            }
10572
10573            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10574                int loc = pkgLite.recommendedInstallLocation;
10575                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10576                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10577                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10578                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10579                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10580                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10581                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10582                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10583                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10584                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10585                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10586                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10587                } else {
10588                    // Override with defaults if needed.
10589                    loc = installLocationPolicy(pkgLite);
10590                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10591                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10592                    } else if (!onSd && !onInt) {
10593                        // Override install location with flags
10594                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10595                            // Set the flag to install on external media.
10596                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10597                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10598                        } else {
10599                            // Make sure the flag for installing on external
10600                            // media is unset
10601                            installFlags |= PackageManager.INSTALL_INTERNAL;
10602                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10603                        }
10604                    }
10605                }
10606            }
10607
10608            final InstallArgs args = createInstallArgs(this);
10609            mArgs = args;
10610
10611            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10612                 /*
10613                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10614                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10615                 */
10616                int userIdentifier = getUser().getIdentifier();
10617                if (userIdentifier == UserHandle.USER_ALL
10618                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10619                    userIdentifier = UserHandle.USER_OWNER;
10620                }
10621
10622                /*
10623                 * Determine if we have any installed package verifiers. If we
10624                 * do, then we'll defer to them to verify the packages.
10625                 */
10626                final int requiredUid = mRequiredVerifierPackage == null ? -1
10627                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10628                if (!origin.existing && requiredUid != -1
10629                        && isVerificationEnabled(userIdentifier, installFlags)) {
10630                    final Intent verification = new Intent(
10631                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10632                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10633                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10634                            PACKAGE_MIME_TYPE);
10635                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10636
10637                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10638                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10639                            0 /* TODO: Which userId? */);
10640
10641                    if (DEBUG_VERIFY) {
10642                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10643                                + verification.toString() + " with " + pkgLite.verifiers.length
10644                                + " optional verifiers");
10645                    }
10646
10647                    final int verificationId = mPendingVerificationToken++;
10648
10649                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10650
10651                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10652                            installerPackageName);
10653
10654                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10655                            installFlags);
10656
10657                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10658                            pkgLite.packageName);
10659
10660                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10661                            pkgLite.versionCode);
10662
10663                    if (verificationParams != null) {
10664                        if (verificationParams.getVerificationURI() != null) {
10665                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10666                                 verificationParams.getVerificationURI());
10667                        }
10668                        if (verificationParams.getOriginatingURI() != null) {
10669                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10670                                  verificationParams.getOriginatingURI());
10671                        }
10672                        if (verificationParams.getReferrer() != null) {
10673                            verification.putExtra(Intent.EXTRA_REFERRER,
10674                                  verificationParams.getReferrer());
10675                        }
10676                        if (verificationParams.getOriginatingUid() >= 0) {
10677                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10678                                  verificationParams.getOriginatingUid());
10679                        }
10680                        if (verificationParams.getInstallerUid() >= 0) {
10681                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10682                                  verificationParams.getInstallerUid());
10683                        }
10684                    }
10685
10686                    final PackageVerificationState verificationState = new PackageVerificationState(
10687                            requiredUid, args);
10688
10689                    mPendingVerification.append(verificationId, verificationState);
10690
10691                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10692                            receivers, verificationState);
10693
10694                    // Apps installed for "all" users use the device owner to verify the app
10695                    UserHandle verifierUser = getUser();
10696                    if (verifierUser == UserHandle.ALL) {
10697                        verifierUser = UserHandle.OWNER;
10698                    }
10699
10700                    /*
10701                     * If any sufficient verifiers were listed in the package
10702                     * manifest, attempt to ask them.
10703                     */
10704                    if (sufficientVerifiers != null) {
10705                        final int N = sufficientVerifiers.size();
10706                        if (N == 0) {
10707                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10708                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10709                        } else {
10710                            for (int i = 0; i < N; i++) {
10711                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10712
10713                                final Intent sufficientIntent = new Intent(verification);
10714                                sufficientIntent.setComponent(verifierComponent);
10715                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10716                            }
10717                        }
10718                    }
10719
10720                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10721                            mRequiredVerifierPackage, receivers);
10722                    if (ret == PackageManager.INSTALL_SUCCEEDED
10723                            && mRequiredVerifierPackage != null) {
10724                        /*
10725                         * Send the intent to the required verification agent,
10726                         * but only start the verification timeout after the
10727                         * target BroadcastReceivers have run.
10728                         */
10729                        verification.setComponent(requiredVerifierComponent);
10730                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10731                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10732                                new BroadcastReceiver() {
10733                                    @Override
10734                                    public void onReceive(Context context, Intent intent) {
10735                                        final Message msg = mHandler
10736                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10737                                        msg.arg1 = verificationId;
10738                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10739                                    }
10740                                }, null, 0, null, null);
10741
10742                        /*
10743                         * We don't want the copy to proceed until verification
10744                         * succeeds, so null out this field.
10745                         */
10746                        mArgs = null;
10747                    }
10748                } else {
10749                    /*
10750                     * No package verification is enabled, so immediately start
10751                     * the remote call to initiate copy using temporary file.
10752                     */
10753                    ret = args.copyApk(mContainerService, true);
10754                }
10755            }
10756
10757            mRet = ret;
10758        }
10759
10760        @Override
10761        void handleReturnCode() {
10762            // If mArgs is null, then MCS couldn't be reached. When it
10763            // reconnects, it will try again to install. At that point, this
10764            // will succeed.
10765            if (mArgs != null) {
10766                processPendingInstall(mArgs, mRet);
10767            }
10768        }
10769
10770        @Override
10771        void handleServiceError() {
10772            mArgs = createInstallArgs(this);
10773            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10774        }
10775
10776        public boolean isForwardLocked() {
10777            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10778        }
10779    }
10780
10781    /**
10782     * Used during creation of InstallArgs
10783     *
10784     * @param installFlags package installation flags
10785     * @return true if should be installed on external storage
10786     */
10787    private static boolean installOnExternalAsec(int installFlags) {
10788        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10789            return false;
10790        }
10791        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10792            return true;
10793        }
10794        return false;
10795    }
10796
10797    /**
10798     * Used during creation of InstallArgs
10799     *
10800     * @param installFlags package installation flags
10801     * @return true if should be installed as forward locked
10802     */
10803    private static boolean installForwardLocked(int installFlags) {
10804        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10805    }
10806
10807    private InstallArgs createInstallArgs(InstallParams params) {
10808        if (params.move != null) {
10809            return new MoveInstallArgs(params);
10810        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10811            return new AsecInstallArgs(params);
10812        } else {
10813            return new FileInstallArgs(params);
10814        }
10815    }
10816
10817    /**
10818     * Create args that describe an existing installed package. Typically used
10819     * when cleaning up old installs, or used as a move source.
10820     */
10821    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10822            String resourcePath, String[] instructionSets) {
10823        final boolean isInAsec;
10824        if (installOnExternalAsec(installFlags)) {
10825            /* Apps on SD card are always in ASEC containers. */
10826            isInAsec = true;
10827        } else if (installForwardLocked(installFlags)
10828                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10829            /*
10830             * Forward-locked apps are only in ASEC containers if they're the
10831             * new style
10832             */
10833            isInAsec = true;
10834        } else {
10835            isInAsec = false;
10836        }
10837
10838        if (isInAsec) {
10839            return new AsecInstallArgs(codePath, instructionSets,
10840                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10841        } else {
10842            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10843        }
10844    }
10845
10846    static abstract class InstallArgs {
10847        /** @see InstallParams#origin */
10848        final OriginInfo origin;
10849        /** @see InstallParams#move */
10850        final MoveInfo move;
10851
10852        final IPackageInstallObserver2 observer;
10853        // Always refers to PackageManager flags only
10854        final int installFlags;
10855        final String installerPackageName;
10856        final String volumeUuid;
10857        final ManifestDigest manifestDigest;
10858        final UserHandle user;
10859        final String abiOverride;
10860        final String[] installGrantPermissions;
10861
10862        // The list of instruction sets supported by this app. This is currently
10863        // only used during the rmdex() phase to clean up resources. We can get rid of this
10864        // if we move dex files under the common app path.
10865        /* nullable */ String[] instructionSets;
10866
10867        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10868                int installFlags, String installerPackageName, String volumeUuid,
10869                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10870                String abiOverride, String[] installGrantPermissions) {
10871            this.origin = origin;
10872            this.move = move;
10873            this.installFlags = installFlags;
10874            this.observer = observer;
10875            this.installerPackageName = installerPackageName;
10876            this.volumeUuid = volumeUuid;
10877            this.manifestDigest = manifestDigest;
10878            this.user = user;
10879            this.instructionSets = instructionSets;
10880            this.abiOverride = abiOverride;
10881            this.installGrantPermissions = installGrantPermissions;
10882        }
10883
10884        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10885        abstract int doPreInstall(int status);
10886
10887        /**
10888         * Rename package into final resting place. All paths on the given
10889         * scanned package should be updated to reflect the rename.
10890         */
10891        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10892        abstract int doPostInstall(int status, int uid);
10893
10894        /** @see PackageSettingBase#codePathString */
10895        abstract String getCodePath();
10896        /** @see PackageSettingBase#resourcePathString */
10897        abstract String getResourcePath();
10898
10899        // Need installer lock especially for dex file removal.
10900        abstract void cleanUpResourcesLI();
10901        abstract boolean doPostDeleteLI(boolean delete);
10902
10903        /**
10904         * Called before the source arguments are copied. This is used mostly
10905         * for MoveParams when it needs to read the source file to put it in the
10906         * destination.
10907         */
10908        int doPreCopy() {
10909            return PackageManager.INSTALL_SUCCEEDED;
10910        }
10911
10912        /**
10913         * Called after the source arguments are copied. This is used mostly for
10914         * MoveParams when it needs to read the source file to put it in the
10915         * destination.
10916         *
10917         * @return
10918         */
10919        int doPostCopy(int uid) {
10920            return PackageManager.INSTALL_SUCCEEDED;
10921        }
10922
10923        protected boolean isFwdLocked() {
10924            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10925        }
10926
10927        protected boolean isExternalAsec() {
10928            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10929        }
10930
10931        UserHandle getUser() {
10932            return user;
10933        }
10934    }
10935
10936    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10937        if (!allCodePaths.isEmpty()) {
10938            if (instructionSets == null) {
10939                throw new IllegalStateException("instructionSet == null");
10940            }
10941            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10942            for (String codePath : allCodePaths) {
10943                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10944                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10945                    if (retCode < 0) {
10946                        Slog.w(TAG, "Couldn't remove dex file for package: "
10947                                + " at location " + codePath + ", retcode=" + retCode);
10948                        // we don't consider this to be a failure of the core package deletion
10949                    }
10950                }
10951            }
10952        }
10953    }
10954
10955    /**
10956     * Logic to handle installation of non-ASEC applications, including copying
10957     * and renaming logic.
10958     */
10959    class FileInstallArgs extends InstallArgs {
10960        private File codeFile;
10961        private File resourceFile;
10962
10963        // Example topology:
10964        // /data/app/com.example/base.apk
10965        // /data/app/com.example/split_foo.apk
10966        // /data/app/com.example/lib/arm/libfoo.so
10967        // /data/app/com.example/lib/arm64/libfoo.so
10968        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10969
10970        /** New install */
10971        FileInstallArgs(InstallParams params) {
10972            super(params.origin, params.move, params.observer, params.installFlags,
10973                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10974                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10975                    params.grantedRuntimePermissions);
10976            if (isFwdLocked()) {
10977                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10978            }
10979        }
10980
10981        /** Existing install */
10982        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10983            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10984                    null, null);
10985            this.codeFile = (codePath != null) ? new File(codePath) : null;
10986            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10987        }
10988
10989        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10990            if (origin.staged) {
10991                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10992                codeFile = origin.file;
10993                resourceFile = origin.file;
10994                return PackageManager.INSTALL_SUCCEEDED;
10995            }
10996
10997            try {
10998                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10999                codeFile = tempDir;
11000                resourceFile = tempDir;
11001            } catch (IOException e) {
11002                Slog.w(TAG, "Failed to create copy file: " + e);
11003                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11004            }
11005
11006            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11007                @Override
11008                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11009                    if (!FileUtils.isValidExtFilename(name)) {
11010                        throw new IllegalArgumentException("Invalid filename: " + name);
11011                    }
11012                    try {
11013                        final File file = new File(codeFile, name);
11014                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11015                                O_RDWR | O_CREAT, 0644);
11016                        Os.chmod(file.getAbsolutePath(), 0644);
11017                        return new ParcelFileDescriptor(fd);
11018                    } catch (ErrnoException e) {
11019                        throw new RemoteException("Failed to open: " + e.getMessage());
11020                    }
11021                }
11022            };
11023
11024            int ret = PackageManager.INSTALL_SUCCEEDED;
11025            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11026            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11027                Slog.e(TAG, "Failed to copy package");
11028                return ret;
11029            }
11030
11031            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11032            NativeLibraryHelper.Handle handle = null;
11033            try {
11034                handle = NativeLibraryHelper.Handle.create(codeFile);
11035                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11036                        abiOverride);
11037            } catch (IOException e) {
11038                Slog.e(TAG, "Copying native libraries failed", e);
11039                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11040            } finally {
11041                IoUtils.closeQuietly(handle);
11042            }
11043
11044            return ret;
11045        }
11046
11047        int doPreInstall(int status) {
11048            if (status != PackageManager.INSTALL_SUCCEEDED) {
11049                cleanUp();
11050            }
11051            return status;
11052        }
11053
11054        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11055            if (status != PackageManager.INSTALL_SUCCEEDED) {
11056                cleanUp();
11057                return false;
11058            }
11059
11060            final File targetDir = codeFile.getParentFile();
11061            final File beforeCodeFile = codeFile;
11062            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11063
11064            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11065            try {
11066                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11067            } catch (ErrnoException e) {
11068                Slog.w(TAG, "Failed to rename", e);
11069                return false;
11070            }
11071
11072            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11073                Slog.w(TAG, "Failed to restorecon");
11074                return false;
11075            }
11076
11077            // Reflect the rename internally
11078            codeFile = afterCodeFile;
11079            resourceFile = afterCodeFile;
11080
11081            // Reflect the rename in scanned details
11082            pkg.codePath = afterCodeFile.getAbsolutePath();
11083            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11084                    pkg.baseCodePath);
11085            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11086                    pkg.splitCodePaths);
11087
11088            // Reflect the rename in app info
11089            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11090            pkg.applicationInfo.setCodePath(pkg.codePath);
11091            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11092            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11093            pkg.applicationInfo.setResourcePath(pkg.codePath);
11094            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11095            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11096
11097            return true;
11098        }
11099
11100        int doPostInstall(int status, int uid) {
11101            if (status != PackageManager.INSTALL_SUCCEEDED) {
11102                cleanUp();
11103            }
11104            return status;
11105        }
11106
11107        @Override
11108        String getCodePath() {
11109            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11110        }
11111
11112        @Override
11113        String getResourcePath() {
11114            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11115        }
11116
11117        private boolean cleanUp() {
11118            if (codeFile == null || !codeFile.exists()) {
11119                return false;
11120            }
11121
11122            if (codeFile.isDirectory()) {
11123                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11124            } else {
11125                codeFile.delete();
11126            }
11127
11128            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11129                resourceFile.delete();
11130            }
11131
11132            return true;
11133        }
11134
11135        void cleanUpResourcesLI() {
11136            // Try enumerating all code paths before deleting
11137            List<String> allCodePaths = Collections.EMPTY_LIST;
11138            if (codeFile != null && codeFile.exists()) {
11139                try {
11140                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11141                    allCodePaths = pkg.getAllCodePaths();
11142                } catch (PackageParserException e) {
11143                    // Ignored; we tried our best
11144                }
11145            }
11146
11147            cleanUp();
11148            removeDexFiles(allCodePaths, instructionSets);
11149        }
11150
11151        boolean doPostDeleteLI(boolean delete) {
11152            // XXX err, shouldn't we respect the delete flag?
11153            cleanUpResourcesLI();
11154            return true;
11155        }
11156    }
11157
11158    private boolean isAsecExternal(String cid) {
11159        final String asecPath = PackageHelper.getSdFilesystem(cid);
11160        return !asecPath.startsWith(mAsecInternalPath);
11161    }
11162
11163    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11164            PackageManagerException {
11165        if (copyRet < 0) {
11166            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11167                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11168                throw new PackageManagerException(copyRet, message);
11169            }
11170        }
11171    }
11172
11173    /**
11174     * Extract the MountService "container ID" from the full code path of an
11175     * .apk.
11176     */
11177    static String cidFromCodePath(String fullCodePath) {
11178        int eidx = fullCodePath.lastIndexOf("/");
11179        String subStr1 = fullCodePath.substring(0, eidx);
11180        int sidx = subStr1.lastIndexOf("/");
11181        return subStr1.substring(sidx+1, eidx);
11182    }
11183
11184    /**
11185     * Logic to handle installation of ASEC applications, including copying and
11186     * renaming logic.
11187     */
11188    class AsecInstallArgs extends InstallArgs {
11189        static final String RES_FILE_NAME = "pkg.apk";
11190        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11191
11192        String cid;
11193        String packagePath;
11194        String resourcePath;
11195
11196        /** New install */
11197        AsecInstallArgs(InstallParams params) {
11198            super(params.origin, params.move, params.observer, params.installFlags,
11199                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11200                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11201                    params.grantedRuntimePermissions);
11202        }
11203
11204        /** Existing install */
11205        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11206                        boolean isExternal, boolean isForwardLocked) {
11207            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11208                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11209                    instructionSets, null, null);
11210            // Hackily pretend we're still looking at a full code path
11211            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11212                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11213            }
11214
11215            // Extract cid from fullCodePath
11216            int eidx = fullCodePath.lastIndexOf("/");
11217            String subStr1 = fullCodePath.substring(0, eidx);
11218            int sidx = subStr1.lastIndexOf("/");
11219            cid = subStr1.substring(sidx+1, eidx);
11220            setMountPath(subStr1);
11221        }
11222
11223        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11224            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11225                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11226                    instructionSets, null, null);
11227            this.cid = cid;
11228            setMountPath(PackageHelper.getSdDir(cid));
11229        }
11230
11231        void createCopyFile() {
11232            cid = mInstallerService.allocateExternalStageCidLegacy();
11233        }
11234
11235        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11236            if (origin.staged) {
11237                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11238                cid = origin.cid;
11239                setMountPath(PackageHelper.getSdDir(cid));
11240                return PackageManager.INSTALL_SUCCEEDED;
11241            }
11242
11243            if (temp) {
11244                createCopyFile();
11245            } else {
11246                /*
11247                 * Pre-emptively destroy the container since it's destroyed if
11248                 * copying fails due to it existing anyway.
11249                 */
11250                PackageHelper.destroySdDir(cid);
11251            }
11252
11253            final String newMountPath = imcs.copyPackageToContainer(
11254                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11255                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11256
11257            if (newMountPath != null) {
11258                setMountPath(newMountPath);
11259                return PackageManager.INSTALL_SUCCEEDED;
11260            } else {
11261                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11262            }
11263        }
11264
11265        @Override
11266        String getCodePath() {
11267            return packagePath;
11268        }
11269
11270        @Override
11271        String getResourcePath() {
11272            return resourcePath;
11273        }
11274
11275        int doPreInstall(int status) {
11276            if (status != PackageManager.INSTALL_SUCCEEDED) {
11277                // Destroy container
11278                PackageHelper.destroySdDir(cid);
11279            } else {
11280                boolean mounted = PackageHelper.isContainerMounted(cid);
11281                if (!mounted) {
11282                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11283                            Process.SYSTEM_UID);
11284                    if (newMountPath != null) {
11285                        setMountPath(newMountPath);
11286                    } else {
11287                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11288                    }
11289                }
11290            }
11291            return status;
11292        }
11293
11294        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11295            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11296            String newMountPath = null;
11297            if (PackageHelper.isContainerMounted(cid)) {
11298                // Unmount the container
11299                if (!PackageHelper.unMountSdDir(cid)) {
11300                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11301                    return false;
11302                }
11303            }
11304            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11305                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11306                        " which might be stale. Will try to clean up.");
11307                // Clean up the stale container and proceed to recreate.
11308                if (!PackageHelper.destroySdDir(newCacheId)) {
11309                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11310                    return false;
11311                }
11312                // Successfully cleaned up stale container. Try to rename again.
11313                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11314                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11315                            + " inspite of cleaning it up.");
11316                    return false;
11317                }
11318            }
11319            if (!PackageHelper.isContainerMounted(newCacheId)) {
11320                Slog.w(TAG, "Mounting container " + newCacheId);
11321                newMountPath = PackageHelper.mountSdDir(newCacheId,
11322                        getEncryptKey(), Process.SYSTEM_UID);
11323            } else {
11324                newMountPath = PackageHelper.getSdDir(newCacheId);
11325            }
11326            if (newMountPath == null) {
11327                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11328                return false;
11329            }
11330            Log.i(TAG, "Succesfully renamed " + cid +
11331                    " to " + newCacheId +
11332                    " at new path: " + newMountPath);
11333            cid = newCacheId;
11334
11335            final File beforeCodeFile = new File(packagePath);
11336            setMountPath(newMountPath);
11337            final File afterCodeFile = new File(packagePath);
11338
11339            // Reflect the rename in scanned details
11340            pkg.codePath = afterCodeFile.getAbsolutePath();
11341            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11342                    pkg.baseCodePath);
11343            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11344                    pkg.splitCodePaths);
11345
11346            // Reflect the rename in app info
11347            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11348            pkg.applicationInfo.setCodePath(pkg.codePath);
11349            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11350            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11351            pkg.applicationInfo.setResourcePath(pkg.codePath);
11352            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11353            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11354
11355            return true;
11356        }
11357
11358        private void setMountPath(String mountPath) {
11359            final File mountFile = new File(mountPath);
11360
11361            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11362            if (monolithicFile.exists()) {
11363                packagePath = monolithicFile.getAbsolutePath();
11364                if (isFwdLocked()) {
11365                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11366                } else {
11367                    resourcePath = packagePath;
11368                }
11369            } else {
11370                packagePath = mountFile.getAbsolutePath();
11371                resourcePath = packagePath;
11372            }
11373        }
11374
11375        int doPostInstall(int status, int uid) {
11376            if (status != PackageManager.INSTALL_SUCCEEDED) {
11377                cleanUp();
11378            } else {
11379                final int groupOwner;
11380                final String protectedFile;
11381                if (isFwdLocked()) {
11382                    groupOwner = UserHandle.getSharedAppGid(uid);
11383                    protectedFile = RES_FILE_NAME;
11384                } else {
11385                    groupOwner = -1;
11386                    protectedFile = null;
11387                }
11388
11389                if (uid < Process.FIRST_APPLICATION_UID
11390                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11391                    Slog.e(TAG, "Failed to finalize " + cid);
11392                    PackageHelper.destroySdDir(cid);
11393                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11394                }
11395
11396                boolean mounted = PackageHelper.isContainerMounted(cid);
11397                if (!mounted) {
11398                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11399                }
11400            }
11401            return status;
11402        }
11403
11404        private void cleanUp() {
11405            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11406
11407            // Destroy secure container
11408            PackageHelper.destroySdDir(cid);
11409        }
11410
11411        private List<String> getAllCodePaths() {
11412            final File codeFile = new File(getCodePath());
11413            if (codeFile != null && codeFile.exists()) {
11414                try {
11415                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11416                    return pkg.getAllCodePaths();
11417                } catch (PackageParserException e) {
11418                    // Ignored; we tried our best
11419                }
11420            }
11421            return Collections.EMPTY_LIST;
11422        }
11423
11424        void cleanUpResourcesLI() {
11425            // Enumerate all code paths before deleting
11426            cleanUpResourcesLI(getAllCodePaths());
11427        }
11428
11429        private void cleanUpResourcesLI(List<String> allCodePaths) {
11430            cleanUp();
11431            removeDexFiles(allCodePaths, instructionSets);
11432        }
11433
11434        String getPackageName() {
11435            return getAsecPackageName(cid);
11436        }
11437
11438        boolean doPostDeleteLI(boolean delete) {
11439            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11440            final List<String> allCodePaths = getAllCodePaths();
11441            boolean mounted = PackageHelper.isContainerMounted(cid);
11442            if (mounted) {
11443                // Unmount first
11444                if (PackageHelper.unMountSdDir(cid)) {
11445                    mounted = false;
11446                }
11447            }
11448            if (!mounted && delete) {
11449                cleanUpResourcesLI(allCodePaths);
11450            }
11451            return !mounted;
11452        }
11453
11454        @Override
11455        int doPreCopy() {
11456            if (isFwdLocked()) {
11457                if (!PackageHelper.fixSdPermissions(cid,
11458                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11459                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11460                }
11461            }
11462
11463            return PackageManager.INSTALL_SUCCEEDED;
11464        }
11465
11466        @Override
11467        int doPostCopy(int uid) {
11468            if (isFwdLocked()) {
11469                if (uid < Process.FIRST_APPLICATION_UID
11470                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11471                                RES_FILE_NAME)) {
11472                    Slog.e(TAG, "Failed to finalize " + cid);
11473                    PackageHelper.destroySdDir(cid);
11474                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11475                }
11476            }
11477
11478            return PackageManager.INSTALL_SUCCEEDED;
11479        }
11480    }
11481
11482    /**
11483     * Logic to handle movement of existing installed applications.
11484     */
11485    class MoveInstallArgs extends InstallArgs {
11486        private File codeFile;
11487        private File resourceFile;
11488
11489        /** New install */
11490        MoveInstallArgs(InstallParams params) {
11491            super(params.origin, params.move, params.observer, params.installFlags,
11492                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11493                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11494                    params.grantedRuntimePermissions);
11495        }
11496
11497        int copyApk(IMediaContainerService imcs, boolean temp) {
11498            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11499                    + move.fromUuid + " to " + move.toUuid);
11500            synchronized (mInstaller) {
11501                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11502                        move.dataAppName, move.appId, move.seinfo) != 0) {
11503                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11504                }
11505            }
11506
11507            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11508            resourceFile = codeFile;
11509            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11510
11511            return PackageManager.INSTALL_SUCCEEDED;
11512        }
11513
11514        int doPreInstall(int status) {
11515            if (status != PackageManager.INSTALL_SUCCEEDED) {
11516                cleanUp(move.toUuid);
11517            }
11518            return status;
11519        }
11520
11521        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11522            if (status != PackageManager.INSTALL_SUCCEEDED) {
11523                cleanUp(move.toUuid);
11524                return false;
11525            }
11526
11527            // Reflect the move in app info
11528            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11529            pkg.applicationInfo.setCodePath(pkg.codePath);
11530            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11531            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11532            pkg.applicationInfo.setResourcePath(pkg.codePath);
11533            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11534            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11535
11536            return true;
11537        }
11538
11539        int doPostInstall(int status, int uid) {
11540            if (status == PackageManager.INSTALL_SUCCEEDED) {
11541                cleanUp(move.fromUuid);
11542            } else {
11543                cleanUp(move.toUuid);
11544            }
11545            return status;
11546        }
11547
11548        @Override
11549        String getCodePath() {
11550            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11551        }
11552
11553        @Override
11554        String getResourcePath() {
11555            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11556        }
11557
11558        private boolean cleanUp(String volumeUuid) {
11559            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11560                    move.dataAppName);
11561            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11562            synchronized (mInstallLock) {
11563                // Clean up both app data and code
11564                removeDataDirsLI(volumeUuid, move.packageName);
11565                if (codeFile.isDirectory()) {
11566                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11567                } else {
11568                    codeFile.delete();
11569                }
11570            }
11571            return true;
11572        }
11573
11574        void cleanUpResourcesLI() {
11575            throw new UnsupportedOperationException();
11576        }
11577
11578        boolean doPostDeleteLI(boolean delete) {
11579            throw new UnsupportedOperationException();
11580        }
11581    }
11582
11583    static String getAsecPackageName(String packageCid) {
11584        int idx = packageCid.lastIndexOf("-");
11585        if (idx == -1) {
11586            return packageCid;
11587        }
11588        return packageCid.substring(0, idx);
11589    }
11590
11591    // Utility method used to create code paths based on package name and available index.
11592    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11593        String idxStr = "";
11594        int idx = 1;
11595        // Fall back to default value of idx=1 if prefix is not
11596        // part of oldCodePath
11597        if (oldCodePath != null) {
11598            String subStr = oldCodePath;
11599            // Drop the suffix right away
11600            if (suffix != null && subStr.endsWith(suffix)) {
11601                subStr = subStr.substring(0, subStr.length() - suffix.length());
11602            }
11603            // If oldCodePath already contains prefix find out the
11604            // ending index to either increment or decrement.
11605            int sidx = subStr.lastIndexOf(prefix);
11606            if (sidx != -1) {
11607                subStr = subStr.substring(sidx + prefix.length());
11608                if (subStr != null) {
11609                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11610                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11611                    }
11612                    try {
11613                        idx = Integer.parseInt(subStr);
11614                        if (idx <= 1) {
11615                            idx++;
11616                        } else {
11617                            idx--;
11618                        }
11619                    } catch(NumberFormatException e) {
11620                    }
11621                }
11622            }
11623        }
11624        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11625        return prefix + idxStr;
11626    }
11627
11628    private File getNextCodePath(File targetDir, String packageName) {
11629        int suffix = 1;
11630        File result;
11631        do {
11632            result = new File(targetDir, packageName + "-" + suffix);
11633            suffix++;
11634        } while (result.exists());
11635        return result;
11636    }
11637
11638    // Utility method that returns the relative package path with respect
11639    // to the installation directory. Like say for /data/data/com.test-1.apk
11640    // string com.test-1 is returned.
11641    static String deriveCodePathName(String codePath) {
11642        if (codePath == null) {
11643            return null;
11644        }
11645        final File codeFile = new File(codePath);
11646        final String name = codeFile.getName();
11647        if (codeFile.isDirectory()) {
11648            return name;
11649        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11650            final int lastDot = name.lastIndexOf('.');
11651            return name.substring(0, lastDot);
11652        } else {
11653            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11654            return null;
11655        }
11656    }
11657
11658    class PackageInstalledInfo {
11659        String name;
11660        int uid;
11661        // The set of users that originally had this package installed.
11662        int[] origUsers;
11663        // The set of users that now have this package installed.
11664        int[] newUsers;
11665        PackageParser.Package pkg;
11666        int returnCode;
11667        String returnMsg;
11668        PackageRemovedInfo removedInfo;
11669
11670        public void setError(int code, String msg) {
11671            returnCode = code;
11672            returnMsg = msg;
11673            Slog.w(TAG, msg);
11674        }
11675
11676        public void setError(String msg, PackageParserException e) {
11677            returnCode = e.error;
11678            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11679            Slog.w(TAG, msg, e);
11680        }
11681
11682        public void setError(String msg, PackageManagerException e) {
11683            returnCode = e.error;
11684            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11685            Slog.w(TAG, msg, e);
11686        }
11687
11688        // In some error cases we want to convey more info back to the observer
11689        String origPackage;
11690        String origPermission;
11691    }
11692
11693    /*
11694     * Install a non-existing package.
11695     */
11696    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11697            UserHandle user, String installerPackageName, String volumeUuid,
11698            PackageInstalledInfo res) {
11699        // Remember this for later, in case we need to rollback this install
11700        String pkgName = pkg.packageName;
11701
11702        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11703        final boolean dataDirExists = Environment
11704                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11705        synchronized(mPackages) {
11706            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11707                // A package with the same name is already installed, though
11708                // it has been renamed to an older name.  The package we
11709                // are trying to install should be installed as an update to
11710                // the existing one, but that has not been requested, so bail.
11711                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11712                        + " without first uninstalling package running as "
11713                        + mSettings.mRenamedPackages.get(pkgName));
11714                return;
11715            }
11716            if (mPackages.containsKey(pkgName)) {
11717                // Don't allow installation over an existing package with the same name.
11718                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11719                        + " without first uninstalling.");
11720                return;
11721            }
11722        }
11723
11724        try {
11725            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11726                    System.currentTimeMillis(), user);
11727
11728            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11729            // delete the partially installed application. the data directory will have to be
11730            // restored if it was already existing
11731            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11732                // remove package from internal structures.  Note that we want deletePackageX to
11733                // delete the package data and cache directories that it created in
11734                // scanPackageLocked, unless those directories existed before we even tried to
11735                // install.
11736                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11737                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11738                                res.removedInfo, true);
11739            }
11740
11741        } catch (PackageManagerException e) {
11742            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11743        }
11744    }
11745
11746    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11747        // Can't rotate keys during boot or if sharedUser.
11748        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11749                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11750            return false;
11751        }
11752        // app is using upgradeKeySets; make sure all are valid
11753        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11754        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11755        for (int i = 0; i < upgradeKeySets.length; i++) {
11756            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11757                Slog.wtf(TAG, "Package "
11758                         + (oldPs.name != null ? oldPs.name : "<null>")
11759                         + " contains upgrade-key-set reference to unknown key-set: "
11760                         + upgradeKeySets[i]
11761                         + " reverting to signatures check.");
11762                return false;
11763            }
11764        }
11765        return true;
11766    }
11767
11768    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11769        // Upgrade keysets are being used.  Determine if new package has a superset of the
11770        // required keys.
11771        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11772        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11773        for (int i = 0; i < upgradeKeySets.length; i++) {
11774            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11775            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11776                return true;
11777            }
11778        }
11779        return false;
11780    }
11781
11782    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11783            UserHandle user, String installerPackageName, String volumeUuid,
11784            PackageInstalledInfo res) {
11785        final PackageParser.Package oldPackage;
11786        final String pkgName = pkg.packageName;
11787        final int[] allUsers;
11788        final boolean[] perUserInstalled;
11789
11790        // First find the old package info and check signatures
11791        synchronized(mPackages) {
11792            oldPackage = mPackages.get(pkgName);
11793            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11794            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11795            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11796                if(!checkUpgradeKeySetLP(ps, pkg)) {
11797                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11798                            "New package not signed by keys specified by upgrade-keysets: "
11799                            + pkgName);
11800                    return;
11801                }
11802            } else {
11803                // default to original signature matching
11804                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11805                    != PackageManager.SIGNATURE_MATCH) {
11806                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11807                            "New package has a different signature: " + pkgName);
11808                    return;
11809                }
11810            }
11811
11812            // In case of rollback, remember per-user/profile install state
11813            allUsers = sUserManager.getUserIds();
11814            perUserInstalled = new boolean[allUsers.length];
11815            for (int i = 0; i < allUsers.length; i++) {
11816                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11817            }
11818        }
11819
11820        boolean sysPkg = (isSystemApp(oldPackage));
11821        if (sysPkg) {
11822            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11823                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11824        } else {
11825            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11826                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11827        }
11828    }
11829
11830    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11831            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11832            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11833            String volumeUuid, PackageInstalledInfo res) {
11834        String pkgName = deletedPackage.packageName;
11835        boolean deletedPkg = true;
11836        boolean updatedSettings = false;
11837
11838        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11839                + deletedPackage);
11840        long origUpdateTime;
11841        if (pkg.mExtras != null) {
11842            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11843        } else {
11844            origUpdateTime = 0;
11845        }
11846
11847        // First delete the existing package while retaining the data directory
11848        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11849                res.removedInfo, true)) {
11850            // If the existing package wasn't successfully deleted
11851            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11852            deletedPkg = false;
11853        } else {
11854            // Successfully deleted the old package; proceed with replace.
11855
11856            // If deleted package lived in a container, give users a chance to
11857            // relinquish resources before killing.
11858            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11859                if (DEBUG_INSTALL) {
11860                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11861                }
11862                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11863                final ArrayList<String> pkgList = new ArrayList<String>(1);
11864                pkgList.add(deletedPackage.applicationInfo.packageName);
11865                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11866            }
11867
11868            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11869            try {
11870                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11871                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11872                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11873                        perUserInstalled, res, user);
11874                updatedSettings = true;
11875            } catch (PackageManagerException e) {
11876                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11877            }
11878        }
11879
11880        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11881            // remove package from internal structures.  Note that we want deletePackageX to
11882            // delete the package data and cache directories that it created in
11883            // scanPackageLocked, unless those directories existed before we even tried to
11884            // install.
11885            if(updatedSettings) {
11886                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11887                deletePackageLI(
11888                        pkgName, null, true, allUsers, perUserInstalled,
11889                        PackageManager.DELETE_KEEP_DATA,
11890                                res.removedInfo, true);
11891            }
11892            // Since we failed to install the new package we need to restore the old
11893            // package that we deleted.
11894            if (deletedPkg) {
11895                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11896                File restoreFile = new File(deletedPackage.codePath);
11897                // Parse old package
11898                boolean oldExternal = isExternal(deletedPackage);
11899                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11900                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11901                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11902                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11903                try {
11904                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11905                } catch (PackageManagerException e) {
11906                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11907                            + e.getMessage());
11908                    return;
11909                }
11910                // Restore of old package succeeded. Update permissions.
11911                // writer
11912                synchronized (mPackages) {
11913                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11914                            UPDATE_PERMISSIONS_ALL);
11915                    // can downgrade to reader
11916                    mSettings.writeLPr();
11917                }
11918                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11919            }
11920        }
11921    }
11922
11923    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11924            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11925            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11926            String volumeUuid, PackageInstalledInfo res) {
11927        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11928                + ", old=" + deletedPackage);
11929        boolean disabledSystem = false;
11930        boolean updatedSettings = false;
11931        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11932        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11933                != 0) {
11934            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11935        }
11936        String packageName = deletedPackage.packageName;
11937        if (packageName == null) {
11938            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11939                    "Attempt to delete null packageName.");
11940            return;
11941        }
11942        PackageParser.Package oldPkg;
11943        PackageSetting oldPkgSetting;
11944        // reader
11945        synchronized (mPackages) {
11946            oldPkg = mPackages.get(packageName);
11947            oldPkgSetting = mSettings.mPackages.get(packageName);
11948            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11949                    (oldPkgSetting == null)) {
11950                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11951                        "Couldn't find package:" + packageName + " information");
11952                return;
11953            }
11954        }
11955
11956        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11957
11958        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11959        res.removedInfo.removedPackage = packageName;
11960        // Remove existing system package
11961        removePackageLI(oldPkgSetting, true);
11962        // writer
11963        synchronized (mPackages) {
11964            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11965            if (!disabledSystem && deletedPackage != null) {
11966                // We didn't need to disable the .apk as a current system package,
11967                // which means we are replacing another update that is already
11968                // installed.  We need to make sure to delete the older one's .apk.
11969                res.removedInfo.args = createInstallArgsForExisting(0,
11970                        deletedPackage.applicationInfo.getCodePath(),
11971                        deletedPackage.applicationInfo.getResourcePath(),
11972                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11973            } else {
11974                res.removedInfo.args = null;
11975            }
11976        }
11977
11978        // Successfully disabled the old package. Now proceed with re-installation
11979        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11980
11981        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11982        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11983
11984        PackageParser.Package newPackage = null;
11985        try {
11986            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11987            if (newPackage.mExtras != null) {
11988                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11989                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11990                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11991
11992                // is the update attempting to change shared user? that isn't going to work...
11993                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11994                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11995                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11996                            + " to " + newPkgSetting.sharedUser);
11997                    updatedSettings = true;
11998                }
11999            }
12000
12001            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12002                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12003                        perUserInstalled, res, user);
12004                updatedSettings = true;
12005            }
12006
12007        } catch (PackageManagerException e) {
12008            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12009        }
12010
12011        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12012            // Re installation failed. Restore old information
12013            // Remove new pkg information
12014            if (newPackage != null) {
12015                removeInstalledPackageLI(newPackage, true);
12016            }
12017            // Add back the old system package
12018            try {
12019                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12020            } catch (PackageManagerException e) {
12021                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12022            }
12023            // Restore the old system information in Settings
12024            synchronized (mPackages) {
12025                if (disabledSystem) {
12026                    mSettings.enableSystemPackageLPw(packageName);
12027                }
12028                if (updatedSettings) {
12029                    mSettings.setInstallerPackageName(packageName,
12030                            oldPkgSetting.installerPackageName);
12031                }
12032                mSettings.writeLPr();
12033            }
12034        }
12035    }
12036
12037    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12038            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12039            UserHandle user) {
12040        String pkgName = newPackage.packageName;
12041        synchronized (mPackages) {
12042            //write settings. the installStatus will be incomplete at this stage.
12043            //note that the new package setting would have already been
12044            //added to mPackages. It hasn't been persisted yet.
12045            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12046            mSettings.writeLPr();
12047        }
12048
12049        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12050
12051        synchronized (mPackages) {
12052            updatePermissionsLPw(newPackage.packageName, newPackage,
12053                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12054                            ? UPDATE_PERMISSIONS_ALL : 0));
12055            // For system-bundled packages, we assume that installing an upgraded version
12056            // of the package implies that the user actually wants to run that new code,
12057            // so we enable the package.
12058            PackageSetting ps = mSettings.mPackages.get(pkgName);
12059            if (ps != null) {
12060                if (isSystemApp(newPackage)) {
12061                    // NB: implicit assumption that system package upgrades apply to all users
12062                    if (DEBUG_INSTALL) {
12063                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12064                    }
12065                    if (res.origUsers != null) {
12066                        for (int userHandle : res.origUsers) {
12067                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12068                                    userHandle, installerPackageName);
12069                        }
12070                    }
12071                    // Also convey the prior install/uninstall state
12072                    if (allUsers != null && perUserInstalled != null) {
12073                        for (int i = 0; i < allUsers.length; i++) {
12074                            if (DEBUG_INSTALL) {
12075                                Slog.d(TAG, "    user " + allUsers[i]
12076                                        + " => " + perUserInstalled[i]);
12077                            }
12078                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12079                        }
12080                        // these install state changes will be persisted in the
12081                        // upcoming call to mSettings.writeLPr().
12082                    }
12083                }
12084                // It's implied that when a user requests installation, they want the app to be
12085                // installed and enabled.
12086                int userId = user.getIdentifier();
12087                if (userId != UserHandle.USER_ALL) {
12088                    ps.setInstalled(true, userId);
12089                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12090                }
12091            }
12092            res.name = pkgName;
12093            res.uid = newPackage.applicationInfo.uid;
12094            res.pkg = newPackage;
12095            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12096            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12097            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12098            //to update install status
12099            mSettings.writeLPr();
12100        }
12101    }
12102
12103    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12104        final int installFlags = args.installFlags;
12105        final String installerPackageName = args.installerPackageName;
12106        final String volumeUuid = args.volumeUuid;
12107        final File tmpPackageFile = new File(args.getCodePath());
12108        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12109        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12110                || (args.volumeUuid != null));
12111        boolean replace = false;
12112        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12113        if (args.move != null) {
12114            // moving a complete application; perfom an initial scan on the new install location
12115            scanFlags |= SCAN_INITIAL;
12116        }
12117        // Result object to be returned
12118        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12119
12120        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12121        // Retrieve PackageSettings and parse package
12122        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12123                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12124                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12125        PackageParser pp = new PackageParser();
12126        pp.setSeparateProcesses(mSeparateProcesses);
12127        pp.setDisplayMetrics(mMetrics);
12128
12129        final PackageParser.Package pkg;
12130        try {
12131            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12132        } catch (PackageParserException e) {
12133            res.setError("Failed parse during installPackageLI", e);
12134            return;
12135        }
12136
12137        // Mark that we have an install time CPU ABI override.
12138        pkg.cpuAbiOverride = args.abiOverride;
12139
12140        String pkgName = res.name = pkg.packageName;
12141        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12142            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12143                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12144                return;
12145            }
12146        }
12147
12148        try {
12149            pp.collectCertificates(pkg, parseFlags);
12150            pp.collectManifestDigest(pkg);
12151        } catch (PackageParserException e) {
12152            res.setError("Failed collect during installPackageLI", e);
12153            return;
12154        }
12155
12156        /* If the installer passed in a manifest digest, compare it now. */
12157        if (args.manifestDigest != null) {
12158            if (DEBUG_INSTALL) {
12159                final String parsedManifest = pkg.manifestDigest == null ? "null"
12160                        : pkg.manifestDigest.toString();
12161                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12162                        + parsedManifest);
12163            }
12164
12165            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12166                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12167                return;
12168            }
12169        } else if (DEBUG_INSTALL) {
12170            final String parsedManifest = pkg.manifestDigest == null
12171                    ? "null" : pkg.manifestDigest.toString();
12172            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12173        }
12174
12175        // Get rid of all references to package scan path via parser.
12176        pp = null;
12177        String oldCodePath = null;
12178        boolean systemApp = false;
12179        synchronized (mPackages) {
12180            // Check if installing already existing package
12181            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12182                String oldName = mSettings.mRenamedPackages.get(pkgName);
12183                if (pkg.mOriginalPackages != null
12184                        && pkg.mOriginalPackages.contains(oldName)
12185                        && mPackages.containsKey(oldName)) {
12186                    // This package is derived from an original package,
12187                    // and this device has been updating from that original
12188                    // name.  We must continue using the original name, so
12189                    // rename the new package here.
12190                    pkg.setPackageName(oldName);
12191                    pkgName = pkg.packageName;
12192                    replace = true;
12193                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12194                            + oldName + " pkgName=" + pkgName);
12195                } else if (mPackages.containsKey(pkgName)) {
12196                    // This package, under its official name, already exists
12197                    // on the device; we should replace it.
12198                    replace = true;
12199                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12200                }
12201
12202                // Prevent apps opting out from runtime permissions
12203                if (replace) {
12204                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12205                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12206                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12207                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12208                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12209                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12210                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12211                                        + " doesn't support runtime permissions but the old"
12212                                        + " target SDK " + oldTargetSdk + " does.");
12213                        return;
12214                    }
12215                }
12216            }
12217
12218            PackageSetting ps = mSettings.mPackages.get(pkgName);
12219            if (ps != null) {
12220                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12221
12222                // Quick sanity check that we're signed correctly if updating;
12223                // we'll check this again later when scanning, but we want to
12224                // bail early here before tripping over redefined permissions.
12225                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12226                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12227                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12228                                + pkg.packageName + " upgrade keys do not match the "
12229                                + "previously installed version");
12230                        return;
12231                    }
12232                } else {
12233                    try {
12234                        verifySignaturesLP(ps, pkg);
12235                    } catch (PackageManagerException e) {
12236                        res.setError(e.error, e.getMessage());
12237                        return;
12238                    }
12239                }
12240
12241                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12242                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12243                    systemApp = (ps.pkg.applicationInfo.flags &
12244                            ApplicationInfo.FLAG_SYSTEM) != 0;
12245                }
12246                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12247            }
12248
12249            // Check whether the newly-scanned package wants to define an already-defined perm
12250            int N = pkg.permissions.size();
12251            for (int i = N-1; i >= 0; i--) {
12252                PackageParser.Permission perm = pkg.permissions.get(i);
12253                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12254                if (bp != null) {
12255                    // If the defining package is signed with our cert, it's okay.  This
12256                    // also includes the "updating the same package" case, of course.
12257                    // "updating same package" could also involve key-rotation.
12258                    final boolean sigsOk;
12259                    if (bp.sourcePackage.equals(pkg.packageName)
12260                            && (bp.packageSetting instanceof PackageSetting)
12261                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12262                                    scanFlags))) {
12263                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12264                    } else {
12265                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12266                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12267                    }
12268                    if (!sigsOk) {
12269                        // If the owning package is the system itself, we log but allow
12270                        // install to proceed; we fail the install on all other permission
12271                        // redefinitions.
12272                        if (!bp.sourcePackage.equals("android")) {
12273                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12274                                    + pkg.packageName + " attempting to redeclare permission "
12275                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12276                            res.origPermission = perm.info.name;
12277                            res.origPackage = bp.sourcePackage;
12278                            return;
12279                        } else {
12280                            Slog.w(TAG, "Package " + pkg.packageName
12281                                    + " attempting to redeclare system permission "
12282                                    + perm.info.name + "; ignoring new declaration");
12283                            pkg.permissions.remove(i);
12284                        }
12285                    }
12286                }
12287            }
12288
12289        }
12290
12291        if (systemApp && onExternal) {
12292            // Disable updates to system apps on sdcard
12293            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12294                    "Cannot install updates to system apps on sdcard");
12295            return;
12296        }
12297
12298        if (args.move != null) {
12299            // We did an in-place move, so dex is ready to roll
12300            scanFlags |= SCAN_NO_DEX;
12301            scanFlags |= SCAN_MOVE;
12302
12303            synchronized (mPackages) {
12304                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12305                if (ps == null) {
12306                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12307                            "Missing settings for moved package " + pkgName);
12308                }
12309
12310                // We moved the entire application as-is, so bring over the
12311                // previously derived ABI information.
12312                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12313                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12314            }
12315
12316        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12317            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12318            scanFlags |= SCAN_NO_DEX;
12319
12320            try {
12321                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12322                        true /* extract libs */);
12323            } catch (PackageManagerException pme) {
12324                Slog.e(TAG, "Error deriving application ABI", pme);
12325                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12326                return;
12327            }
12328
12329            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12330            int result = mPackageDexOptimizer
12331                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12332                            false /* defer */, false /* inclDependencies */);
12333            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12334                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12335                return;
12336            }
12337        }
12338
12339        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12340            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12341            return;
12342        }
12343
12344        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12345
12346        if (replace) {
12347            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12348                    installerPackageName, volumeUuid, res);
12349        } else {
12350            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12351                    args.user, installerPackageName, volumeUuid, res);
12352        }
12353        synchronized (mPackages) {
12354            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12355            if (ps != null) {
12356                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12357            }
12358        }
12359    }
12360
12361    private void startIntentFilterVerifications(int userId, boolean replacing,
12362            PackageParser.Package pkg) {
12363        if (mIntentFilterVerifierComponent == null) {
12364            Slog.w(TAG, "No IntentFilter verification will not be done as "
12365                    + "there is no IntentFilterVerifier available!");
12366            return;
12367        }
12368
12369        final int verifierUid = getPackageUid(
12370                mIntentFilterVerifierComponent.getPackageName(),
12371                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12372
12373        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12374        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12375        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12376        mHandler.sendMessage(msg);
12377    }
12378
12379    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12380            PackageParser.Package pkg) {
12381        int size = pkg.activities.size();
12382        if (size == 0) {
12383            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12384                    "No activity, so no need to verify any IntentFilter!");
12385            return;
12386        }
12387
12388        final boolean hasDomainURLs = hasDomainURLs(pkg);
12389        if (!hasDomainURLs) {
12390            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12391                    "No domain URLs, so no need to verify any IntentFilter!");
12392            return;
12393        }
12394
12395        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12396                + " if any IntentFilter from the " + size
12397                + " Activities needs verification ...");
12398
12399        int count = 0;
12400        final String packageName = pkg.packageName;
12401
12402        synchronized (mPackages) {
12403            // If this is a new install and we see that we've already run verification for this
12404            // package, we have nothing to do: it means the state was restored from backup.
12405            if (!replacing) {
12406                IntentFilterVerificationInfo ivi =
12407                        mSettings.getIntentFilterVerificationLPr(packageName);
12408                if (ivi != null) {
12409                    if (DEBUG_DOMAIN_VERIFICATION) {
12410                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12411                                + ivi.getStatusString());
12412                    }
12413                    return;
12414                }
12415            }
12416
12417            // If any filters need to be verified, then all need to be.
12418            boolean needToVerify = false;
12419            for (PackageParser.Activity a : pkg.activities) {
12420                for (ActivityIntentInfo filter : a.intents) {
12421                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12422                        if (DEBUG_DOMAIN_VERIFICATION) {
12423                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12424                        }
12425                        needToVerify = true;
12426                        break;
12427                    }
12428                }
12429            }
12430
12431            if (needToVerify) {
12432                final int verificationId = mIntentFilterVerificationToken++;
12433                for (PackageParser.Activity a : pkg.activities) {
12434                    for (ActivityIntentInfo filter : a.intents) {
12435                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12436                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12437                                    "Verification needed for IntentFilter:" + filter.toString());
12438                            mIntentFilterVerifier.addOneIntentFilterVerification(
12439                                    verifierUid, userId, verificationId, filter, packageName);
12440                            count++;
12441                        }
12442                    }
12443                }
12444            }
12445        }
12446
12447        if (count > 0) {
12448            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12449                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12450                    +  " for userId:" + userId);
12451            mIntentFilterVerifier.startVerifications(userId);
12452        } else {
12453            if (DEBUG_DOMAIN_VERIFICATION) {
12454                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12455            }
12456        }
12457    }
12458
12459    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12460        final ComponentName cn  = filter.activity.getComponentName();
12461        final String packageName = cn.getPackageName();
12462
12463        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12464                packageName);
12465        if (ivi == null) {
12466            return true;
12467        }
12468        int status = ivi.getStatus();
12469        switch (status) {
12470            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12471            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12472                return true;
12473
12474            default:
12475                // Nothing to do
12476                return false;
12477        }
12478    }
12479
12480    private static boolean isMultiArch(PackageSetting ps) {
12481        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12482    }
12483
12484    private static boolean isMultiArch(ApplicationInfo info) {
12485        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12486    }
12487
12488    private static boolean isExternal(PackageParser.Package pkg) {
12489        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12490    }
12491
12492    private static boolean isExternal(PackageSetting ps) {
12493        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12494    }
12495
12496    private static boolean isExternal(ApplicationInfo info) {
12497        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12498    }
12499
12500    private static boolean isSystemApp(PackageParser.Package pkg) {
12501        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12502    }
12503
12504    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12505        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12506    }
12507
12508    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12509        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12510    }
12511
12512    private static boolean isSystemApp(PackageSetting ps) {
12513        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12514    }
12515
12516    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12517        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12518    }
12519
12520    private int packageFlagsToInstallFlags(PackageSetting ps) {
12521        int installFlags = 0;
12522        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12523            // This existing package was an external ASEC install when we have
12524            // the external flag without a UUID
12525            installFlags |= PackageManager.INSTALL_EXTERNAL;
12526        }
12527        if (ps.isForwardLocked()) {
12528            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12529        }
12530        return installFlags;
12531    }
12532
12533    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12534        if (isExternal(pkg)) {
12535            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12536                return mSettings.getExternalVersion();
12537            } else {
12538                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12539            }
12540        } else {
12541            return mSettings.getInternalVersion();
12542        }
12543    }
12544
12545    private void deleteTempPackageFiles() {
12546        final FilenameFilter filter = new FilenameFilter() {
12547            public boolean accept(File dir, String name) {
12548                return name.startsWith("vmdl") && name.endsWith(".tmp");
12549            }
12550        };
12551        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12552            file.delete();
12553        }
12554    }
12555
12556    @Override
12557    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12558            int flags) {
12559        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12560                flags);
12561    }
12562
12563    @Override
12564    public void deletePackage(final String packageName,
12565            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12566        mContext.enforceCallingOrSelfPermission(
12567                android.Manifest.permission.DELETE_PACKAGES, null);
12568        Preconditions.checkNotNull(packageName);
12569        Preconditions.checkNotNull(observer);
12570        final int uid = Binder.getCallingUid();
12571        if (UserHandle.getUserId(uid) != userId) {
12572            mContext.enforceCallingPermission(
12573                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12574                    "deletePackage for user " + userId);
12575        }
12576        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12577            try {
12578                observer.onPackageDeleted(packageName,
12579                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12580            } catch (RemoteException re) {
12581            }
12582            return;
12583        }
12584
12585        boolean uninstallBlocked = false;
12586        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12587            int[] users = sUserManager.getUserIds();
12588            for (int i = 0; i < users.length; ++i) {
12589                if (getBlockUninstallForUser(packageName, users[i])) {
12590                    uninstallBlocked = true;
12591                    break;
12592                }
12593            }
12594        } else {
12595            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12596        }
12597        if (uninstallBlocked) {
12598            try {
12599                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12600                        null);
12601            } catch (RemoteException re) {
12602            }
12603            return;
12604        }
12605
12606        if (DEBUG_REMOVE) {
12607            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12608        }
12609        // Queue up an async operation since the package deletion may take a little while.
12610        mHandler.post(new Runnable() {
12611            public void run() {
12612                mHandler.removeCallbacks(this);
12613                final int returnCode = deletePackageX(packageName, userId, flags);
12614                if (observer != null) {
12615                    try {
12616                        observer.onPackageDeleted(packageName, returnCode, null);
12617                    } catch (RemoteException e) {
12618                        Log.i(TAG, "Observer no longer exists.");
12619                    } //end catch
12620                } //end if
12621            } //end run
12622        });
12623    }
12624
12625    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12626        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12627                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12628        try {
12629            if (dpm != null) {
12630                if (dpm.isDeviceOwner(packageName)) {
12631                    return true;
12632                }
12633                int[] users;
12634                if (userId == UserHandle.USER_ALL) {
12635                    users = sUserManager.getUserIds();
12636                } else {
12637                    users = new int[]{userId};
12638                }
12639                for (int i = 0; i < users.length; ++i) {
12640                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12641                        return true;
12642                    }
12643                }
12644            }
12645        } catch (RemoteException e) {
12646        }
12647        return false;
12648    }
12649
12650    /**
12651     *  This method is an internal method that could be get invoked either
12652     *  to delete an installed package or to clean up a failed installation.
12653     *  After deleting an installed package, a broadcast is sent to notify any
12654     *  listeners that the package has been installed. For cleaning up a failed
12655     *  installation, the broadcast is not necessary since the package's
12656     *  installation wouldn't have sent the initial broadcast either
12657     *  The key steps in deleting a package are
12658     *  deleting the package information in internal structures like mPackages,
12659     *  deleting the packages base directories through installd
12660     *  updating mSettings to reflect current status
12661     *  persisting settings for later use
12662     *  sending a broadcast if necessary
12663     */
12664    private int deletePackageX(String packageName, int userId, int flags) {
12665        final PackageRemovedInfo info = new PackageRemovedInfo();
12666        final boolean res;
12667
12668        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12669                ? UserHandle.ALL : new UserHandle(userId);
12670
12671        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12672            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12673            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12674        }
12675
12676        boolean removedForAllUsers = false;
12677        boolean systemUpdate = false;
12678
12679        // for the uninstall-updates case and restricted profiles, remember the per-
12680        // userhandle installed state
12681        int[] allUsers;
12682        boolean[] perUserInstalled;
12683        synchronized (mPackages) {
12684            PackageSetting ps = mSettings.mPackages.get(packageName);
12685            allUsers = sUserManager.getUserIds();
12686            perUserInstalled = new boolean[allUsers.length];
12687            for (int i = 0; i < allUsers.length; i++) {
12688                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12689            }
12690        }
12691
12692        synchronized (mInstallLock) {
12693            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12694            res = deletePackageLI(packageName, removeForUser,
12695                    true, allUsers, perUserInstalled,
12696                    flags | REMOVE_CHATTY, info, true);
12697            systemUpdate = info.isRemovedPackageSystemUpdate;
12698            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12699                removedForAllUsers = true;
12700            }
12701            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12702                    + " removedForAllUsers=" + removedForAllUsers);
12703        }
12704
12705        if (res) {
12706            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12707
12708            // If the removed package was a system update, the old system package
12709            // was re-enabled; we need to broadcast this information
12710            if (systemUpdate) {
12711                Bundle extras = new Bundle(1);
12712                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12713                        ? info.removedAppId : info.uid);
12714                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12715
12716                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12717                        extras, null, null, null);
12718                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12719                        extras, null, null, null);
12720                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12721                        null, packageName, null, null);
12722            }
12723        }
12724        // Force a gc here.
12725        Runtime.getRuntime().gc();
12726        // Delete the resources here after sending the broadcast to let
12727        // other processes clean up before deleting resources.
12728        if (info.args != null) {
12729            synchronized (mInstallLock) {
12730                info.args.doPostDeleteLI(true);
12731            }
12732        }
12733
12734        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12735    }
12736
12737    class PackageRemovedInfo {
12738        String removedPackage;
12739        int uid = -1;
12740        int removedAppId = -1;
12741        int[] removedUsers = null;
12742        boolean isRemovedPackageSystemUpdate = false;
12743        // Clean up resources deleted packages.
12744        InstallArgs args = null;
12745
12746        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12747            Bundle extras = new Bundle(1);
12748            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12749            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12750            if (replacing) {
12751                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12752            }
12753            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12754            if (removedPackage != null) {
12755                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12756                        extras, null, null, removedUsers);
12757                if (fullRemove && !replacing) {
12758                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12759                            extras, null, null, removedUsers);
12760                }
12761            }
12762            if (removedAppId >= 0) {
12763                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12764                        removedUsers);
12765            }
12766        }
12767    }
12768
12769    /*
12770     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12771     * flag is not set, the data directory is removed as well.
12772     * make sure this flag is set for partially installed apps. If not its meaningless to
12773     * delete a partially installed application.
12774     */
12775    private void removePackageDataLI(PackageSetting ps,
12776            int[] allUserHandles, boolean[] perUserInstalled,
12777            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12778        String packageName = ps.name;
12779        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12780        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12781        // Retrieve object to delete permissions for shared user later on
12782        final PackageSetting deletedPs;
12783        // reader
12784        synchronized (mPackages) {
12785            deletedPs = mSettings.mPackages.get(packageName);
12786            if (outInfo != null) {
12787                outInfo.removedPackage = packageName;
12788                outInfo.removedUsers = deletedPs != null
12789                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12790                        : null;
12791            }
12792        }
12793        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12794            removeDataDirsLI(ps.volumeUuid, packageName);
12795            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12796        }
12797        // writer
12798        synchronized (mPackages) {
12799            if (deletedPs != null) {
12800                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12801                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12802                    clearDefaultBrowserIfNeeded(packageName);
12803                    if (outInfo != null) {
12804                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12805                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12806                    }
12807                    updatePermissionsLPw(deletedPs.name, null, 0);
12808                    if (deletedPs.sharedUser != null) {
12809                        // Remove permissions associated with package. Since runtime
12810                        // permissions are per user we have to kill the removed package
12811                        // or packages running under the shared user of the removed
12812                        // package if revoking the permissions requested only by the removed
12813                        // package is successful and this causes a change in gids.
12814                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12815                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12816                                    userId);
12817                            if (userIdToKill == UserHandle.USER_ALL
12818                                    || userIdToKill >= UserHandle.USER_OWNER) {
12819                                // If gids changed for this user, kill all affected packages.
12820                                mHandler.post(new Runnable() {
12821                                    @Override
12822                                    public void run() {
12823                                        // This has to happen with no lock held.
12824                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12825                                                KILL_APP_REASON_GIDS_CHANGED);
12826                                    }
12827                                });
12828                                break;
12829                            }
12830                        }
12831                    }
12832                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12833                }
12834                // make sure to preserve per-user disabled state if this removal was just
12835                // a downgrade of a system app to the factory package
12836                if (allUserHandles != null && perUserInstalled != null) {
12837                    if (DEBUG_REMOVE) {
12838                        Slog.d(TAG, "Propagating install state across downgrade");
12839                    }
12840                    for (int i = 0; i < allUserHandles.length; i++) {
12841                        if (DEBUG_REMOVE) {
12842                            Slog.d(TAG, "    user " + allUserHandles[i]
12843                                    + " => " + perUserInstalled[i]);
12844                        }
12845                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12846                    }
12847                }
12848            }
12849            // can downgrade to reader
12850            if (writeSettings) {
12851                // Save settings now
12852                mSettings.writeLPr();
12853            }
12854        }
12855        if (outInfo != null) {
12856            // A user ID was deleted here. Go through all users and remove it
12857            // from KeyStore.
12858            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12859        }
12860    }
12861
12862    static boolean locationIsPrivileged(File path) {
12863        try {
12864            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12865                    .getCanonicalPath();
12866            return path.getCanonicalPath().startsWith(privilegedAppDir);
12867        } catch (IOException e) {
12868            Slog.e(TAG, "Unable to access code path " + path);
12869        }
12870        return false;
12871    }
12872
12873    /*
12874     * Tries to delete system package.
12875     */
12876    private boolean deleteSystemPackageLI(PackageSetting newPs,
12877            int[] allUserHandles, boolean[] perUserInstalled,
12878            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12879        final boolean applyUserRestrictions
12880                = (allUserHandles != null) && (perUserInstalled != null);
12881        PackageSetting disabledPs = null;
12882        // Confirm if the system package has been updated
12883        // An updated system app can be deleted. This will also have to restore
12884        // the system pkg from system partition
12885        // reader
12886        synchronized (mPackages) {
12887            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12888        }
12889        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12890                + " disabledPs=" + disabledPs);
12891        if (disabledPs == null) {
12892            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12893            return false;
12894        } else if (DEBUG_REMOVE) {
12895            Slog.d(TAG, "Deleting system pkg from data partition");
12896        }
12897        if (DEBUG_REMOVE) {
12898            if (applyUserRestrictions) {
12899                Slog.d(TAG, "Remembering install states:");
12900                for (int i = 0; i < allUserHandles.length; i++) {
12901                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12902                }
12903            }
12904        }
12905        // Delete the updated package
12906        outInfo.isRemovedPackageSystemUpdate = true;
12907        if (disabledPs.versionCode < newPs.versionCode) {
12908            // Delete data for downgrades
12909            flags &= ~PackageManager.DELETE_KEEP_DATA;
12910        } else {
12911            // Preserve data by setting flag
12912            flags |= PackageManager.DELETE_KEEP_DATA;
12913        }
12914        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12915                allUserHandles, perUserInstalled, outInfo, writeSettings);
12916        if (!ret) {
12917            return false;
12918        }
12919        // writer
12920        synchronized (mPackages) {
12921            // Reinstate the old system package
12922            mSettings.enableSystemPackageLPw(newPs.name);
12923            // Remove any native libraries from the upgraded package.
12924            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12925        }
12926        // Install the system package
12927        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12928        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12929        if (locationIsPrivileged(disabledPs.codePath)) {
12930            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12931        }
12932
12933        final PackageParser.Package newPkg;
12934        try {
12935            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12936        } catch (PackageManagerException e) {
12937            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12938            return false;
12939        }
12940
12941        // writer
12942        synchronized (mPackages) {
12943            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12944
12945            updatePermissionsLPw(newPkg.packageName, newPkg,
12946                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12947
12948            if (applyUserRestrictions) {
12949                if (DEBUG_REMOVE) {
12950                    Slog.d(TAG, "Propagating install state across reinstall");
12951                }
12952                for (int i = 0; i < allUserHandles.length; i++) {
12953                    if (DEBUG_REMOVE) {
12954                        Slog.d(TAG, "    user " + allUserHandles[i]
12955                                + " => " + perUserInstalled[i]);
12956                    }
12957                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12958
12959                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12960                }
12961                // Regardless of writeSettings we need to ensure that this restriction
12962                // state propagation is persisted
12963                mSettings.writeAllUsersPackageRestrictionsLPr();
12964            }
12965            // can downgrade to reader here
12966            if (writeSettings) {
12967                mSettings.writeLPr();
12968            }
12969        }
12970        return true;
12971    }
12972
12973    private boolean deleteInstalledPackageLI(PackageSetting ps,
12974            boolean deleteCodeAndResources, int flags,
12975            int[] allUserHandles, boolean[] perUserInstalled,
12976            PackageRemovedInfo outInfo, boolean writeSettings) {
12977        if (outInfo != null) {
12978            outInfo.uid = ps.appId;
12979        }
12980
12981        // Delete package data from internal structures and also remove data if flag is set
12982        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12983
12984        // Delete application code and resources
12985        if (deleteCodeAndResources && (outInfo != null)) {
12986            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12987                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12988            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12989        }
12990        return true;
12991    }
12992
12993    @Override
12994    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12995            int userId) {
12996        mContext.enforceCallingOrSelfPermission(
12997                android.Manifest.permission.DELETE_PACKAGES, null);
12998        synchronized (mPackages) {
12999            PackageSetting ps = mSettings.mPackages.get(packageName);
13000            if (ps == null) {
13001                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13002                return false;
13003            }
13004            if (!ps.getInstalled(userId)) {
13005                // Can't block uninstall for an app that is not installed or enabled.
13006                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13007                return false;
13008            }
13009            ps.setBlockUninstall(blockUninstall, userId);
13010            mSettings.writePackageRestrictionsLPr(userId);
13011        }
13012        return true;
13013    }
13014
13015    @Override
13016    public boolean getBlockUninstallForUser(String packageName, int userId) {
13017        synchronized (mPackages) {
13018            PackageSetting ps = mSettings.mPackages.get(packageName);
13019            if (ps == null) {
13020                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13021                return false;
13022            }
13023            return ps.getBlockUninstall(userId);
13024        }
13025    }
13026
13027    /*
13028     * This method handles package deletion in general
13029     */
13030    private boolean deletePackageLI(String packageName, UserHandle user,
13031            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13032            int flags, PackageRemovedInfo outInfo,
13033            boolean writeSettings) {
13034        if (packageName == null) {
13035            Slog.w(TAG, "Attempt to delete null packageName.");
13036            return false;
13037        }
13038        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13039        PackageSetting ps;
13040        boolean dataOnly = false;
13041        int removeUser = -1;
13042        int appId = -1;
13043        synchronized (mPackages) {
13044            ps = mSettings.mPackages.get(packageName);
13045            if (ps == null) {
13046                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13047                return false;
13048            }
13049            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13050                    && user.getIdentifier() != UserHandle.USER_ALL) {
13051                // The caller is asking that the package only be deleted for a single
13052                // user.  To do this, we just mark its uninstalled state and delete
13053                // its data.  If this is a system app, we only allow this to happen if
13054                // they have set the special DELETE_SYSTEM_APP which requests different
13055                // semantics than normal for uninstalling system apps.
13056                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13057                ps.setUserState(user.getIdentifier(),
13058                        COMPONENT_ENABLED_STATE_DEFAULT,
13059                        false, //installed
13060                        true,  //stopped
13061                        true,  //notLaunched
13062                        false, //hidden
13063                        null, null, null,
13064                        false, // blockUninstall
13065                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13066                if (!isSystemApp(ps)) {
13067                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13068                        // Other user still have this package installed, so all
13069                        // we need to do is clear this user's data and save that
13070                        // it is uninstalled.
13071                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13072                        removeUser = user.getIdentifier();
13073                        appId = ps.appId;
13074                        scheduleWritePackageRestrictionsLocked(removeUser);
13075                    } else {
13076                        // We need to set it back to 'installed' so the uninstall
13077                        // broadcasts will be sent correctly.
13078                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13079                        ps.setInstalled(true, user.getIdentifier());
13080                    }
13081                } else {
13082                    // This is a system app, so we assume that the
13083                    // other users still have this package installed, so all
13084                    // we need to do is clear this user's data and save that
13085                    // it is uninstalled.
13086                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13087                    removeUser = user.getIdentifier();
13088                    appId = ps.appId;
13089                    scheduleWritePackageRestrictionsLocked(removeUser);
13090                }
13091            }
13092        }
13093
13094        if (removeUser >= 0) {
13095            // From above, we determined that we are deleting this only
13096            // for a single user.  Continue the work here.
13097            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13098            if (outInfo != null) {
13099                outInfo.removedPackage = packageName;
13100                outInfo.removedAppId = appId;
13101                outInfo.removedUsers = new int[] {removeUser};
13102            }
13103            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13104            removeKeystoreDataIfNeeded(removeUser, appId);
13105            schedulePackageCleaning(packageName, removeUser, false);
13106            synchronized (mPackages) {
13107                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13108                    scheduleWritePackageRestrictionsLocked(removeUser);
13109                }
13110                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13111            }
13112            return true;
13113        }
13114
13115        if (dataOnly) {
13116            // Delete application data first
13117            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13118            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13119            return true;
13120        }
13121
13122        boolean ret = false;
13123        if (isSystemApp(ps)) {
13124            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13125            // When an updated system application is deleted we delete the existing resources as well and
13126            // fall back to existing code in system partition
13127            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13128                    flags, outInfo, writeSettings);
13129        } else {
13130            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13131            // Kill application pre-emptively especially for apps on sd.
13132            killApplication(packageName, ps.appId, "uninstall pkg");
13133            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13134                    allUserHandles, perUserInstalled,
13135                    outInfo, writeSettings);
13136        }
13137
13138        return ret;
13139    }
13140
13141    private final class ClearStorageConnection implements ServiceConnection {
13142        IMediaContainerService mContainerService;
13143
13144        @Override
13145        public void onServiceConnected(ComponentName name, IBinder service) {
13146            synchronized (this) {
13147                mContainerService = IMediaContainerService.Stub.asInterface(service);
13148                notifyAll();
13149            }
13150        }
13151
13152        @Override
13153        public void onServiceDisconnected(ComponentName name) {
13154        }
13155    }
13156
13157    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13158        final boolean mounted;
13159        if (Environment.isExternalStorageEmulated()) {
13160            mounted = true;
13161        } else {
13162            final String status = Environment.getExternalStorageState();
13163
13164            mounted = status.equals(Environment.MEDIA_MOUNTED)
13165                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13166        }
13167
13168        if (!mounted) {
13169            return;
13170        }
13171
13172        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13173        int[] users;
13174        if (userId == UserHandle.USER_ALL) {
13175            users = sUserManager.getUserIds();
13176        } else {
13177            users = new int[] { userId };
13178        }
13179        final ClearStorageConnection conn = new ClearStorageConnection();
13180        if (mContext.bindServiceAsUser(
13181                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13182            try {
13183                for (int curUser : users) {
13184                    long timeout = SystemClock.uptimeMillis() + 5000;
13185                    synchronized (conn) {
13186                        long now = SystemClock.uptimeMillis();
13187                        while (conn.mContainerService == null && now < timeout) {
13188                            try {
13189                                conn.wait(timeout - now);
13190                            } catch (InterruptedException e) {
13191                            }
13192                        }
13193                    }
13194                    if (conn.mContainerService == null) {
13195                        return;
13196                    }
13197
13198                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13199                    clearDirectory(conn.mContainerService,
13200                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13201                    if (allData) {
13202                        clearDirectory(conn.mContainerService,
13203                                userEnv.buildExternalStorageAppDataDirs(packageName));
13204                        clearDirectory(conn.mContainerService,
13205                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13206                    }
13207                }
13208            } finally {
13209                mContext.unbindService(conn);
13210            }
13211        }
13212    }
13213
13214    @Override
13215    public void clearApplicationUserData(final String packageName,
13216            final IPackageDataObserver observer, final int userId) {
13217        mContext.enforceCallingOrSelfPermission(
13218                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13219        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13220        // Queue up an async operation since the package deletion may take a little while.
13221        mHandler.post(new Runnable() {
13222            public void run() {
13223                mHandler.removeCallbacks(this);
13224                final boolean succeeded;
13225                synchronized (mInstallLock) {
13226                    succeeded = clearApplicationUserDataLI(packageName, userId);
13227                }
13228                clearExternalStorageDataSync(packageName, userId, true);
13229                if (succeeded) {
13230                    // invoke DeviceStorageMonitor's update method to clear any notifications
13231                    DeviceStorageMonitorInternal
13232                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13233                    if (dsm != null) {
13234                        dsm.checkMemory();
13235                    }
13236                }
13237                if(observer != null) {
13238                    try {
13239                        observer.onRemoveCompleted(packageName, succeeded);
13240                    } catch (RemoteException e) {
13241                        Log.i(TAG, "Observer no longer exists.");
13242                    }
13243                } //end if observer
13244            } //end run
13245        });
13246    }
13247
13248    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13249        if (packageName == null) {
13250            Slog.w(TAG, "Attempt to delete null packageName.");
13251            return false;
13252        }
13253
13254        // Try finding details about the requested package
13255        PackageParser.Package pkg;
13256        synchronized (mPackages) {
13257            pkg = mPackages.get(packageName);
13258            if (pkg == null) {
13259                final PackageSetting ps = mSettings.mPackages.get(packageName);
13260                if (ps != null) {
13261                    pkg = ps.pkg;
13262                }
13263            }
13264
13265            if (pkg == null) {
13266                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13267                return false;
13268            }
13269
13270            PackageSetting ps = (PackageSetting) pkg.mExtras;
13271            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13272        }
13273
13274        // Always delete data directories for package, even if we found no other
13275        // record of app. This helps users recover from UID mismatches without
13276        // resorting to a full data wipe.
13277        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13278        if (retCode < 0) {
13279            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13280            return false;
13281        }
13282
13283        final int appId = pkg.applicationInfo.uid;
13284        removeKeystoreDataIfNeeded(userId, appId);
13285
13286        // Create a native library symlink only if we have native libraries
13287        // and if the native libraries are 32 bit libraries. We do not provide
13288        // this symlink for 64 bit libraries.
13289        if (pkg.applicationInfo.primaryCpuAbi != null &&
13290                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13291            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13292            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13293                    nativeLibPath, userId) < 0) {
13294                Slog.w(TAG, "Failed linking native library dir");
13295                return false;
13296            }
13297        }
13298
13299        return true;
13300    }
13301
13302    /**
13303     * Reverts user permission state changes (permissions and flags) in
13304     * all packages for a given user.
13305     *
13306     * @param userId The device user for which to do a reset.
13307     */
13308    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13309        final int packageCount = mPackages.size();
13310        for (int i = 0; i < packageCount; i++) {
13311            PackageParser.Package pkg = mPackages.valueAt(i);
13312            PackageSetting ps = (PackageSetting) pkg.mExtras;
13313            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13314        }
13315    }
13316
13317    /**
13318     * Reverts user permission state changes (permissions and flags).
13319     *
13320     * @param ps The package for which to reset.
13321     * @param userId The device user for which to do a reset.
13322     */
13323    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13324            final PackageSetting ps, final int userId) {
13325        if (ps.pkg == null) {
13326            return;
13327        }
13328
13329        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13330                | FLAG_PERMISSION_USER_FIXED
13331                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13332
13333        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13334                | FLAG_PERMISSION_POLICY_FIXED;
13335
13336        boolean writeInstallPermissions = false;
13337        boolean writeRuntimePermissions = false;
13338
13339        final int permissionCount = ps.pkg.requestedPermissions.size();
13340        for (int i = 0; i < permissionCount; i++) {
13341            String permission = ps.pkg.requestedPermissions.get(i);
13342
13343            BasePermission bp = mSettings.mPermissions.get(permission);
13344            if (bp == null) {
13345                continue;
13346            }
13347
13348            // If shared user we just reset the state to which only this app contributed.
13349            if (ps.sharedUser != null) {
13350                boolean used = false;
13351                final int packageCount = ps.sharedUser.packages.size();
13352                for (int j = 0; j < packageCount; j++) {
13353                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13354                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13355                            && pkg.pkg.requestedPermissions.contains(permission)) {
13356                        used = true;
13357                        break;
13358                    }
13359                }
13360                if (used) {
13361                    continue;
13362                }
13363            }
13364
13365            PermissionsState permissionsState = ps.getPermissionsState();
13366
13367            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13368
13369            // Always clear the user settable flags.
13370            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13371                    bp.name) != null;
13372            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13373                if (hasInstallState) {
13374                    writeInstallPermissions = true;
13375                } else {
13376                    writeRuntimePermissions = true;
13377                }
13378            }
13379
13380            // Below is only runtime permission handling.
13381            if (!bp.isRuntime()) {
13382                continue;
13383            }
13384
13385            // Never clobber system or policy.
13386            if ((oldFlags & policyOrSystemFlags) != 0) {
13387                continue;
13388            }
13389
13390            // If this permission was granted by default, make sure it is.
13391            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13392                if (permissionsState.grantRuntimePermission(bp, userId)
13393                        != PERMISSION_OPERATION_FAILURE) {
13394                    writeRuntimePermissions = true;
13395                }
13396            } else {
13397                // Otherwise, reset the permission.
13398                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13399                switch (revokeResult) {
13400                    case PERMISSION_OPERATION_SUCCESS: {
13401                        writeRuntimePermissions = true;
13402                    } break;
13403
13404                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13405                        writeRuntimePermissions = true;
13406                        // If gids changed for this user, kill all affected packages.
13407                        mHandler.post(new Runnable() {
13408                            @Override
13409                            public void run() {
13410                                // This has to happen with no lock held.
13411                                killSettingPackagesForUser(ps, userId,
13412                                        KILL_APP_REASON_GIDS_CHANGED);
13413                            }
13414                        });
13415                    } break;
13416                }
13417            }
13418        }
13419
13420        // Synchronously write as we are taking permissions away.
13421        if (writeRuntimePermissions) {
13422            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13423        }
13424
13425        // Synchronously write as we are taking permissions away.
13426        if (writeInstallPermissions) {
13427            mSettings.writeLPr();
13428        }
13429    }
13430
13431    /**
13432     * Remove entries from the keystore daemon. Will only remove it if the
13433     * {@code appId} is valid.
13434     */
13435    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13436        if (appId < 0) {
13437            return;
13438        }
13439
13440        final KeyStore keyStore = KeyStore.getInstance();
13441        if (keyStore != null) {
13442            if (userId == UserHandle.USER_ALL) {
13443                for (final int individual : sUserManager.getUserIds()) {
13444                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13445                }
13446            } else {
13447                keyStore.clearUid(UserHandle.getUid(userId, appId));
13448            }
13449        } else {
13450            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13451        }
13452    }
13453
13454    @Override
13455    public void deleteApplicationCacheFiles(final String packageName,
13456            final IPackageDataObserver observer) {
13457        mContext.enforceCallingOrSelfPermission(
13458                android.Manifest.permission.DELETE_CACHE_FILES, null);
13459        // Queue up an async operation since the package deletion may take a little while.
13460        final int userId = UserHandle.getCallingUserId();
13461        mHandler.post(new Runnable() {
13462            public void run() {
13463                mHandler.removeCallbacks(this);
13464                final boolean succeded;
13465                synchronized (mInstallLock) {
13466                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13467                }
13468                clearExternalStorageDataSync(packageName, userId, false);
13469                if (observer != null) {
13470                    try {
13471                        observer.onRemoveCompleted(packageName, succeded);
13472                    } catch (RemoteException e) {
13473                        Log.i(TAG, "Observer no longer exists.");
13474                    }
13475                } //end if observer
13476            } //end run
13477        });
13478    }
13479
13480    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13481        if (packageName == null) {
13482            Slog.w(TAG, "Attempt to delete null packageName.");
13483            return false;
13484        }
13485        PackageParser.Package p;
13486        synchronized (mPackages) {
13487            p = mPackages.get(packageName);
13488        }
13489        if (p == null) {
13490            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13491            return false;
13492        }
13493        final ApplicationInfo applicationInfo = p.applicationInfo;
13494        if (applicationInfo == null) {
13495            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13496            return false;
13497        }
13498        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13499        if (retCode < 0) {
13500            Slog.w(TAG, "Couldn't remove cache files for package: "
13501                       + packageName + " u" + userId);
13502            return false;
13503        }
13504        return true;
13505    }
13506
13507    @Override
13508    public void getPackageSizeInfo(final String packageName, int userHandle,
13509            final IPackageStatsObserver observer) {
13510        mContext.enforceCallingOrSelfPermission(
13511                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13512        if (packageName == null) {
13513            throw new IllegalArgumentException("Attempt to get size of null packageName");
13514        }
13515
13516        PackageStats stats = new PackageStats(packageName, userHandle);
13517
13518        /*
13519         * Queue up an async operation since the package measurement may take a
13520         * little while.
13521         */
13522        Message msg = mHandler.obtainMessage(INIT_COPY);
13523        msg.obj = new MeasureParams(stats, observer);
13524        mHandler.sendMessage(msg);
13525    }
13526
13527    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13528            PackageStats pStats) {
13529        if (packageName == null) {
13530            Slog.w(TAG, "Attempt to get size of null packageName.");
13531            return false;
13532        }
13533        PackageParser.Package p;
13534        boolean dataOnly = false;
13535        String libDirRoot = null;
13536        String asecPath = null;
13537        PackageSetting ps = null;
13538        synchronized (mPackages) {
13539            p = mPackages.get(packageName);
13540            ps = mSettings.mPackages.get(packageName);
13541            if(p == null) {
13542                dataOnly = true;
13543                if((ps == null) || (ps.pkg == null)) {
13544                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13545                    return false;
13546                }
13547                p = ps.pkg;
13548            }
13549            if (ps != null) {
13550                libDirRoot = ps.legacyNativeLibraryPathString;
13551            }
13552            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13553                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13554                if (secureContainerId != null) {
13555                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13556                }
13557            }
13558        }
13559        String publicSrcDir = null;
13560        if(!dataOnly) {
13561            final ApplicationInfo applicationInfo = p.applicationInfo;
13562            if (applicationInfo == null) {
13563                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13564                return false;
13565            }
13566            if (p.isForwardLocked()) {
13567                publicSrcDir = applicationInfo.getBaseResourcePath();
13568            }
13569        }
13570        // TODO: extend to measure size of split APKs
13571        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13572        // not just the first level.
13573        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13574        // just the primary.
13575        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13576        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13577                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13578        if (res < 0) {
13579            return false;
13580        }
13581
13582        // Fix-up for forward-locked applications in ASEC containers.
13583        if (!isExternal(p)) {
13584            pStats.codeSize += pStats.externalCodeSize;
13585            pStats.externalCodeSize = 0L;
13586        }
13587
13588        return true;
13589    }
13590
13591
13592    @Override
13593    public void addPackageToPreferred(String packageName) {
13594        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13595    }
13596
13597    @Override
13598    public void removePackageFromPreferred(String packageName) {
13599        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13600    }
13601
13602    @Override
13603    public List<PackageInfo> getPreferredPackages(int flags) {
13604        return new ArrayList<PackageInfo>();
13605    }
13606
13607    private int getUidTargetSdkVersionLockedLPr(int uid) {
13608        Object obj = mSettings.getUserIdLPr(uid);
13609        if (obj instanceof SharedUserSetting) {
13610            final SharedUserSetting sus = (SharedUserSetting) obj;
13611            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13612            final Iterator<PackageSetting> it = sus.packages.iterator();
13613            while (it.hasNext()) {
13614                final PackageSetting ps = it.next();
13615                if (ps.pkg != null) {
13616                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13617                    if (v < vers) vers = v;
13618                }
13619            }
13620            return vers;
13621        } else if (obj instanceof PackageSetting) {
13622            final PackageSetting ps = (PackageSetting) obj;
13623            if (ps.pkg != null) {
13624                return ps.pkg.applicationInfo.targetSdkVersion;
13625            }
13626        }
13627        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13628    }
13629
13630    @Override
13631    public void addPreferredActivity(IntentFilter filter, int match,
13632            ComponentName[] set, ComponentName activity, int userId) {
13633        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13634                "Adding preferred");
13635    }
13636
13637    private void addPreferredActivityInternal(IntentFilter filter, int match,
13638            ComponentName[] set, ComponentName activity, boolean always, int userId,
13639            String opname) {
13640        // writer
13641        int callingUid = Binder.getCallingUid();
13642        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13643        if (filter.countActions() == 0) {
13644            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13645            return;
13646        }
13647        synchronized (mPackages) {
13648            if (mContext.checkCallingOrSelfPermission(
13649                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13650                    != PackageManager.PERMISSION_GRANTED) {
13651                if (getUidTargetSdkVersionLockedLPr(callingUid)
13652                        < Build.VERSION_CODES.FROYO) {
13653                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13654                            + callingUid);
13655                    return;
13656                }
13657                mContext.enforceCallingOrSelfPermission(
13658                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13659            }
13660
13661            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13662            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13663                    + userId + ":");
13664            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13665            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13666            scheduleWritePackageRestrictionsLocked(userId);
13667        }
13668    }
13669
13670    @Override
13671    public void replacePreferredActivity(IntentFilter filter, int match,
13672            ComponentName[] set, ComponentName activity, int userId) {
13673        if (filter.countActions() != 1) {
13674            throw new IllegalArgumentException(
13675                    "replacePreferredActivity expects filter to have only 1 action.");
13676        }
13677        if (filter.countDataAuthorities() != 0
13678                || filter.countDataPaths() != 0
13679                || filter.countDataSchemes() > 1
13680                || filter.countDataTypes() != 0) {
13681            throw new IllegalArgumentException(
13682                    "replacePreferredActivity expects filter to have no data authorities, " +
13683                    "paths, or types; and at most one scheme.");
13684        }
13685
13686        final int callingUid = Binder.getCallingUid();
13687        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13688        synchronized (mPackages) {
13689            if (mContext.checkCallingOrSelfPermission(
13690                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13691                    != PackageManager.PERMISSION_GRANTED) {
13692                if (getUidTargetSdkVersionLockedLPr(callingUid)
13693                        < Build.VERSION_CODES.FROYO) {
13694                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13695                            + Binder.getCallingUid());
13696                    return;
13697                }
13698                mContext.enforceCallingOrSelfPermission(
13699                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13700            }
13701
13702            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13703            if (pir != null) {
13704                // Get all of the existing entries that exactly match this filter.
13705                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13706                if (existing != null && existing.size() == 1) {
13707                    PreferredActivity cur = existing.get(0);
13708                    if (DEBUG_PREFERRED) {
13709                        Slog.i(TAG, "Checking replace of preferred:");
13710                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13711                        if (!cur.mPref.mAlways) {
13712                            Slog.i(TAG, "  -- CUR; not mAlways!");
13713                        } else {
13714                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13715                            Slog.i(TAG, "  -- CUR: mSet="
13716                                    + Arrays.toString(cur.mPref.mSetComponents));
13717                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13718                            Slog.i(TAG, "  -- NEW: mMatch="
13719                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13720                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13721                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13722                        }
13723                    }
13724                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13725                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13726                            && cur.mPref.sameSet(set)) {
13727                        // Setting the preferred activity to what it happens to be already
13728                        if (DEBUG_PREFERRED) {
13729                            Slog.i(TAG, "Replacing with same preferred activity "
13730                                    + cur.mPref.mShortComponent + " for user "
13731                                    + userId + ":");
13732                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13733                        }
13734                        return;
13735                    }
13736                }
13737
13738                if (existing != null) {
13739                    if (DEBUG_PREFERRED) {
13740                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13741                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13742                    }
13743                    for (int i = 0; i < existing.size(); i++) {
13744                        PreferredActivity pa = existing.get(i);
13745                        if (DEBUG_PREFERRED) {
13746                            Slog.i(TAG, "Removing existing preferred activity "
13747                                    + pa.mPref.mComponent + ":");
13748                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13749                        }
13750                        pir.removeFilter(pa);
13751                    }
13752                }
13753            }
13754            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13755                    "Replacing preferred");
13756        }
13757    }
13758
13759    @Override
13760    public void clearPackagePreferredActivities(String packageName) {
13761        final int uid = Binder.getCallingUid();
13762        // writer
13763        synchronized (mPackages) {
13764            PackageParser.Package pkg = mPackages.get(packageName);
13765            if (pkg == null || pkg.applicationInfo.uid != uid) {
13766                if (mContext.checkCallingOrSelfPermission(
13767                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13768                        != PackageManager.PERMISSION_GRANTED) {
13769                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13770                            < Build.VERSION_CODES.FROYO) {
13771                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13772                                + Binder.getCallingUid());
13773                        return;
13774                    }
13775                    mContext.enforceCallingOrSelfPermission(
13776                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13777                }
13778            }
13779
13780            int user = UserHandle.getCallingUserId();
13781            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13782                scheduleWritePackageRestrictionsLocked(user);
13783            }
13784        }
13785    }
13786
13787    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13788    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13789        ArrayList<PreferredActivity> removed = null;
13790        boolean changed = false;
13791        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13792            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13793            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13794            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13795                continue;
13796            }
13797            Iterator<PreferredActivity> it = pir.filterIterator();
13798            while (it.hasNext()) {
13799                PreferredActivity pa = it.next();
13800                // Mark entry for removal only if it matches the package name
13801                // and the entry is of type "always".
13802                if (packageName == null ||
13803                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13804                                && pa.mPref.mAlways)) {
13805                    if (removed == null) {
13806                        removed = new ArrayList<PreferredActivity>();
13807                    }
13808                    removed.add(pa);
13809                }
13810            }
13811            if (removed != null) {
13812                for (int j=0; j<removed.size(); j++) {
13813                    PreferredActivity pa = removed.get(j);
13814                    pir.removeFilter(pa);
13815                }
13816                changed = true;
13817            }
13818        }
13819        return changed;
13820    }
13821
13822    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13823    private void clearIntentFilterVerificationsLPw(int userId) {
13824        final int packageCount = mPackages.size();
13825        for (int i = 0; i < packageCount; i++) {
13826            PackageParser.Package pkg = mPackages.valueAt(i);
13827            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13828        }
13829    }
13830
13831    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13832    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13833        if (userId == UserHandle.USER_ALL) {
13834            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13835                    sUserManager.getUserIds())) {
13836                for (int oneUserId : sUserManager.getUserIds()) {
13837                    scheduleWritePackageRestrictionsLocked(oneUserId);
13838                }
13839            }
13840        } else {
13841            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13842                scheduleWritePackageRestrictionsLocked(userId);
13843            }
13844        }
13845    }
13846
13847    void clearDefaultBrowserIfNeeded(String packageName) {
13848        for (int oneUserId : sUserManager.getUserIds()) {
13849            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13850            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13851            if (packageName.equals(defaultBrowserPackageName)) {
13852                setDefaultBrowserPackageName(null, oneUserId);
13853            }
13854        }
13855    }
13856
13857    @Override
13858    public void resetApplicationPreferences(int userId) {
13859        mContext.enforceCallingOrSelfPermission(
13860                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13861        // writer
13862        synchronized (mPackages) {
13863            final long identity = Binder.clearCallingIdentity();
13864            try {
13865                clearPackagePreferredActivitiesLPw(null, userId);
13866                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13867                // TODO: We have to reset the default SMS and Phone. This requires
13868                // significant refactoring to keep all default apps in the package
13869                // manager (cleaner but more work) or have the services provide
13870                // callbacks to the package manager to request a default app reset.
13871                applyFactoryDefaultBrowserLPw(userId);
13872                clearIntentFilterVerificationsLPw(userId);
13873                primeDomainVerificationsLPw(userId);
13874                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13875                scheduleWritePackageRestrictionsLocked(userId);
13876            } finally {
13877                Binder.restoreCallingIdentity(identity);
13878            }
13879        }
13880    }
13881
13882    @Override
13883    public int getPreferredActivities(List<IntentFilter> outFilters,
13884            List<ComponentName> outActivities, String packageName) {
13885
13886        int num = 0;
13887        final int userId = UserHandle.getCallingUserId();
13888        // reader
13889        synchronized (mPackages) {
13890            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13891            if (pir != null) {
13892                final Iterator<PreferredActivity> it = pir.filterIterator();
13893                while (it.hasNext()) {
13894                    final PreferredActivity pa = it.next();
13895                    if (packageName == null
13896                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13897                                    && pa.mPref.mAlways)) {
13898                        if (outFilters != null) {
13899                            outFilters.add(new IntentFilter(pa));
13900                        }
13901                        if (outActivities != null) {
13902                            outActivities.add(pa.mPref.mComponent);
13903                        }
13904                    }
13905                }
13906            }
13907        }
13908
13909        return num;
13910    }
13911
13912    @Override
13913    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13914            int userId) {
13915        int callingUid = Binder.getCallingUid();
13916        if (callingUid != Process.SYSTEM_UID) {
13917            throw new SecurityException(
13918                    "addPersistentPreferredActivity can only be run by the system");
13919        }
13920        if (filter.countActions() == 0) {
13921            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13922            return;
13923        }
13924        synchronized (mPackages) {
13925            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13926                    " :");
13927            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13928            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13929                    new PersistentPreferredActivity(filter, activity));
13930            scheduleWritePackageRestrictionsLocked(userId);
13931        }
13932    }
13933
13934    @Override
13935    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13936        int callingUid = Binder.getCallingUid();
13937        if (callingUid != Process.SYSTEM_UID) {
13938            throw new SecurityException(
13939                    "clearPackagePersistentPreferredActivities can only be run by the system");
13940        }
13941        ArrayList<PersistentPreferredActivity> removed = null;
13942        boolean changed = false;
13943        synchronized (mPackages) {
13944            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13945                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13946                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13947                        .valueAt(i);
13948                if (userId != thisUserId) {
13949                    continue;
13950                }
13951                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13952                while (it.hasNext()) {
13953                    PersistentPreferredActivity ppa = it.next();
13954                    // Mark entry for removal only if it matches the package name.
13955                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13956                        if (removed == null) {
13957                            removed = new ArrayList<PersistentPreferredActivity>();
13958                        }
13959                        removed.add(ppa);
13960                    }
13961                }
13962                if (removed != null) {
13963                    for (int j=0; j<removed.size(); j++) {
13964                        PersistentPreferredActivity ppa = removed.get(j);
13965                        ppir.removeFilter(ppa);
13966                    }
13967                    changed = true;
13968                }
13969            }
13970
13971            if (changed) {
13972                scheduleWritePackageRestrictionsLocked(userId);
13973            }
13974        }
13975    }
13976
13977    /**
13978     * Common machinery for picking apart a restored XML blob and passing
13979     * it to a caller-supplied functor to be applied to the running system.
13980     */
13981    private void restoreFromXml(XmlPullParser parser, int userId,
13982            String expectedStartTag, BlobXmlRestorer functor)
13983            throws IOException, XmlPullParserException {
13984        int type;
13985        while ((type = parser.next()) != XmlPullParser.START_TAG
13986                && type != XmlPullParser.END_DOCUMENT) {
13987        }
13988        if (type != XmlPullParser.START_TAG) {
13989            // oops didn't find a start tag?!
13990            if (DEBUG_BACKUP) {
13991                Slog.e(TAG, "Didn't find start tag during restore");
13992            }
13993            return;
13994        }
13995
13996        // this is supposed to be TAG_PREFERRED_BACKUP
13997        if (!expectedStartTag.equals(parser.getName())) {
13998            if (DEBUG_BACKUP) {
13999                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14000            }
14001            return;
14002        }
14003
14004        // skip interfering stuff, then we're aligned with the backing implementation
14005        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14006        functor.apply(parser, userId);
14007    }
14008
14009    private interface BlobXmlRestorer {
14010        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14011    }
14012
14013    /**
14014     * Non-Binder method, support for the backup/restore mechanism: write the
14015     * full set of preferred activities in its canonical XML format.  Returns the
14016     * XML output as a byte array, or null if there is none.
14017     */
14018    @Override
14019    public byte[] getPreferredActivityBackup(int userId) {
14020        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14021            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14022        }
14023
14024        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14025        try {
14026            final XmlSerializer serializer = new FastXmlSerializer();
14027            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14028            serializer.startDocument(null, true);
14029            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14030
14031            synchronized (mPackages) {
14032                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14033            }
14034
14035            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14036            serializer.endDocument();
14037            serializer.flush();
14038        } catch (Exception e) {
14039            if (DEBUG_BACKUP) {
14040                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14041            }
14042            return null;
14043        }
14044
14045        return dataStream.toByteArray();
14046    }
14047
14048    @Override
14049    public void restorePreferredActivities(byte[] backup, int userId) {
14050        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14051            throw new SecurityException("Only the system may call restorePreferredActivities()");
14052        }
14053
14054        try {
14055            final XmlPullParser parser = Xml.newPullParser();
14056            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14057            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14058                    new BlobXmlRestorer() {
14059                        @Override
14060                        public void apply(XmlPullParser parser, int userId)
14061                                throws XmlPullParserException, IOException {
14062                            synchronized (mPackages) {
14063                                mSettings.readPreferredActivitiesLPw(parser, userId);
14064                            }
14065                        }
14066                    } );
14067        } catch (Exception e) {
14068            if (DEBUG_BACKUP) {
14069                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14070            }
14071        }
14072    }
14073
14074    /**
14075     * Non-Binder method, support for the backup/restore mechanism: write the
14076     * default browser (etc) settings in its canonical XML format.  Returns the default
14077     * browser XML representation as a byte array, or null if there is none.
14078     */
14079    @Override
14080    public byte[] getDefaultAppsBackup(int userId) {
14081        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14082            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14083        }
14084
14085        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14086        try {
14087            final XmlSerializer serializer = new FastXmlSerializer();
14088            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14089            serializer.startDocument(null, true);
14090            serializer.startTag(null, TAG_DEFAULT_APPS);
14091
14092            synchronized (mPackages) {
14093                mSettings.writeDefaultAppsLPr(serializer, userId);
14094            }
14095
14096            serializer.endTag(null, TAG_DEFAULT_APPS);
14097            serializer.endDocument();
14098            serializer.flush();
14099        } catch (Exception e) {
14100            if (DEBUG_BACKUP) {
14101                Slog.e(TAG, "Unable to write default apps for backup", e);
14102            }
14103            return null;
14104        }
14105
14106        return dataStream.toByteArray();
14107    }
14108
14109    @Override
14110    public void restoreDefaultApps(byte[] backup, int userId) {
14111        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14112            throw new SecurityException("Only the system may call restoreDefaultApps()");
14113        }
14114
14115        try {
14116            final XmlPullParser parser = Xml.newPullParser();
14117            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14118            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14119                    new BlobXmlRestorer() {
14120                        @Override
14121                        public void apply(XmlPullParser parser, int userId)
14122                                throws XmlPullParserException, IOException {
14123                            synchronized (mPackages) {
14124                                mSettings.readDefaultAppsLPw(parser, userId);
14125                            }
14126                        }
14127                    } );
14128        } catch (Exception e) {
14129            if (DEBUG_BACKUP) {
14130                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14131            }
14132        }
14133    }
14134
14135    @Override
14136    public byte[] getIntentFilterVerificationBackup(int userId) {
14137        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14138            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14139        }
14140
14141        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14142        try {
14143            final XmlSerializer serializer = new FastXmlSerializer();
14144            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14145            serializer.startDocument(null, true);
14146            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14147
14148            synchronized (mPackages) {
14149                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14150            }
14151
14152            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14153            serializer.endDocument();
14154            serializer.flush();
14155        } catch (Exception e) {
14156            if (DEBUG_BACKUP) {
14157                Slog.e(TAG, "Unable to write default apps for backup", e);
14158            }
14159            return null;
14160        }
14161
14162        return dataStream.toByteArray();
14163    }
14164
14165    @Override
14166    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14167        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14168            throw new SecurityException("Only the system may call restorePreferredActivities()");
14169        }
14170
14171        try {
14172            final XmlPullParser parser = Xml.newPullParser();
14173            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14174            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14175                    new BlobXmlRestorer() {
14176                        @Override
14177                        public void apply(XmlPullParser parser, int userId)
14178                                throws XmlPullParserException, IOException {
14179                            synchronized (mPackages) {
14180                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14181                                mSettings.writeLPr();
14182                            }
14183                        }
14184                    } );
14185        } catch (Exception e) {
14186            if (DEBUG_BACKUP) {
14187                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14188            }
14189        }
14190    }
14191
14192    @Override
14193    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14194            int sourceUserId, int targetUserId, int flags) {
14195        mContext.enforceCallingOrSelfPermission(
14196                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14197        int callingUid = Binder.getCallingUid();
14198        enforceOwnerRights(ownerPackage, callingUid);
14199        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14200        if (intentFilter.countActions() == 0) {
14201            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14202            return;
14203        }
14204        synchronized (mPackages) {
14205            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14206                    ownerPackage, targetUserId, flags);
14207            CrossProfileIntentResolver resolver =
14208                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14209            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14210            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14211            if (existing != null) {
14212                int size = existing.size();
14213                for (int i = 0; i < size; i++) {
14214                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14215                        return;
14216                    }
14217                }
14218            }
14219            resolver.addFilter(newFilter);
14220            scheduleWritePackageRestrictionsLocked(sourceUserId);
14221        }
14222    }
14223
14224    @Override
14225    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14226        mContext.enforceCallingOrSelfPermission(
14227                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14228        int callingUid = Binder.getCallingUid();
14229        enforceOwnerRights(ownerPackage, callingUid);
14230        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14231        synchronized (mPackages) {
14232            CrossProfileIntentResolver resolver =
14233                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14234            ArraySet<CrossProfileIntentFilter> set =
14235                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14236            for (CrossProfileIntentFilter filter : set) {
14237                if (filter.getOwnerPackage().equals(ownerPackage)) {
14238                    resolver.removeFilter(filter);
14239                }
14240            }
14241            scheduleWritePackageRestrictionsLocked(sourceUserId);
14242        }
14243    }
14244
14245    // Enforcing that callingUid is owning pkg on userId
14246    private void enforceOwnerRights(String pkg, int callingUid) {
14247        // The system owns everything.
14248        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14249            return;
14250        }
14251        int callingUserId = UserHandle.getUserId(callingUid);
14252        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14253        if (pi == null) {
14254            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14255                    + callingUserId);
14256        }
14257        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14258            throw new SecurityException("Calling uid " + callingUid
14259                    + " does not own package " + pkg);
14260        }
14261    }
14262
14263    @Override
14264    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14265        Intent intent = new Intent(Intent.ACTION_MAIN);
14266        intent.addCategory(Intent.CATEGORY_HOME);
14267
14268        final int callingUserId = UserHandle.getCallingUserId();
14269        List<ResolveInfo> list = queryIntentActivities(intent, null,
14270                PackageManager.GET_META_DATA, callingUserId);
14271        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14272                true, false, false, callingUserId);
14273
14274        allHomeCandidates.clear();
14275        if (list != null) {
14276            for (ResolveInfo ri : list) {
14277                allHomeCandidates.add(ri);
14278            }
14279        }
14280        return (preferred == null || preferred.activityInfo == null)
14281                ? null
14282                : new ComponentName(preferred.activityInfo.packageName,
14283                        preferred.activityInfo.name);
14284    }
14285
14286    @Override
14287    public void setApplicationEnabledSetting(String appPackageName,
14288            int newState, int flags, int userId, String callingPackage) {
14289        if (!sUserManager.exists(userId)) return;
14290        if (callingPackage == null) {
14291            callingPackage = Integer.toString(Binder.getCallingUid());
14292        }
14293        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14294    }
14295
14296    @Override
14297    public void setComponentEnabledSetting(ComponentName componentName,
14298            int newState, int flags, int userId) {
14299        if (!sUserManager.exists(userId)) return;
14300        setEnabledSetting(componentName.getPackageName(),
14301                componentName.getClassName(), newState, flags, userId, null);
14302    }
14303
14304    private void setEnabledSetting(final String packageName, String className, int newState,
14305            final int flags, int userId, String callingPackage) {
14306        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14307              || newState == COMPONENT_ENABLED_STATE_ENABLED
14308              || newState == COMPONENT_ENABLED_STATE_DISABLED
14309              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14310              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14311            throw new IllegalArgumentException("Invalid new component state: "
14312                    + newState);
14313        }
14314        PackageSetting pkgSetting;
14315        final int uid = Binder.getCallingUid();
14316        final int permission = mContext.checkCallingOrSelfPermission(
14317                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14318        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14319        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14320        boolean sendNow = false;
14321        boolean isApp = (className == null);
14322        String componentName = isApp ? packageName : className;
14323        int packageUid = -1;
14324        ArrayList<String> components;
14325
14326        // writer
14327        synchronized (mPackages) {
14328            pkgSetting = mSettings.mPackages.get(packageName);
14329            if (pkgSetting == null) {
14330                if (className == null) {
14331                    throw new IllegalArgumentException(
14332                            "Unknown package: " + packageName);
14333                }
14334                throw new IllegalArgumentException(
14335                        "Unknown component: " + packageName
14336                        + "/" + className);
14337            }
14338            // Allow root and verify that userId is not being specified by a different user
14339            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14340                throw new SecurityException(
14341                        "Permission Denial: attempt to change component state from pid="
14342                        + Binder.getCallingPid()
14343                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14344            }
14345            if (className == null) {
14346                // We're dealing with an application/package level state change
14347                if (pkgSetting.getEnabled(userId) == newState) {
14348                    // Nothing to do
14349                    return;
14350                }
14351                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14352                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14353                    // Don't care about who enables an app.
14354                    callingPackage = null;
14355                }
14356                pkgSetting.setEnabled(newState, userId, callingPackage);
14357                // pkgSetting.pkg.mSetEnabled = newState;
14358            } else {
14359                // We're dealing with a component level state change
14360                // First, verify that this is a valid class name.
14361                PackageParser.Package pkg = pkgSetting.pkg;
14362                if (pkg == null || !pkg.hasComponentClassName(className)) {
14363                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14364                        throw new IllegalArgumentException("Component class " + className
14365                                + " does not exist in " + packageName);
14366                    } else {
14367                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14368                                + className + " does not exist in " + packageName);
14369                    }
14370                }
14371                switch (newState) {
14372                case COMPONENT_ENABLED_STATE_ENABLED:
14373                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14374                        return;
14375                    }
14376                    break;
14377                case COMPONENT_ENABLED_STATE_DISABLED:
14378                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14379                        return;
14380                    }
14381                    break;
14382                case COMPONENT_ENABLED_STATE_DEFAULT:
14383                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14384                        return;
14385                    }
14386                    break;
14387                default:
14388                    Slog.e(TAG, "Invalid new component state: " + newState);
14389                    return;
14390                }
14391            }
14392            scheduleWritePackageRestrictionsLocked(userId);
14393            components = mPendingBroadcasts.get(userId, packageName);
14394            final boolean newPackage = components == null;
14395            if (newPackage) {
14396                components = new ArrayList<String>();
14397            }
14398            if (!components.contains(componentName)) {
14399                components.add(componentName);
14400            }
14401            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14402                sendNow = true;
14403                // Purge entry from pending broadcast list if another one exists already
14404                // since we are sending one right away.
14405                mPendingBroadcasts.remove(userId, packageName);
14406            } else {
14407                if (newPackage) {
14408                    mPendingBroadcasts.put(userId, packageName, components);
14409                }
14410                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14411                    // Schedule a message
14412                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14413                }
14414            }
14415        }
14416
14417        long callingId = Binder.clearCallingIdentity();
14418        try {
14419            if (sendNow) {
14420                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14421                sendPackageChangedBroadcast(packageName,
14422                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14423            }
14424        } finally {
14425            Binder.restoreCallingIdentity(callingId);
14426        }
14427    }
14428
14429    private void sendPackageChangedBroadcast(String packageName,
14430            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14431        if (DEBUG_INSTALL)
14432            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14433                    + componentNames);
14434        Bundle extras = new Bundle(4);
14435        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14436        String nameList[] = new String[componentNames.size()];
14437        componentNames.toArray(nameList);
14438        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14439        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14440        extras.putInt(Intent.EXTRA_UID, packageUid);
14441        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14442                new int[] {UserHandle.getUserId(packageUid)});
14443    }
14444
14445    @Override
14446    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14447        if (!sUserManager.exists(userId)) return;
14448        final int uid = Binder.getCallingUid();
14449        final int permission = mContext.checkCallingOrSelfPermission(
14450                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14451        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14452        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14453        // writer
14454        synchronized (mPackages) {
14455            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14456                    allowedByPermission, uid, userId)) {
14457                scheduleWritePackageRestrictionsLocked(userId);
14458            }
14459        }
14460    }
14461
14462    @Override
14463    public String getInstallerPackageName(String packageName) {
14464        // reader
14465        synchronized (mPackages) {
14466            return mSettings.getInstallerPackageNameLPr(packageName);
14467        }
14468    }
14469
14470    @Override
14471    public int getApplicationEnabledSetting(String packageName, int userId) {
14472        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14473        int uid = Binder.getCallingUid();
14474        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14475        // reader
14476        synchronized (mPackages) {
14477            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14478        }
14479    }
14480
14481    @Override
14482    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14483        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14484        int uid = Binder.getCallingUid();
14485        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14486        // reader
14487        synchronized (mPackages) {
14488            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14489        }
14490    }
14491
14492    @Override
14493    public void enterSafeMode() {
14494        enforceSystemOrRoot("Only the system can request entering safe mode");
14495
14496        if (!mSystemReady) {
14497            mSafeMode = true;
14498        }
14499    }
14500
14501    @Override
14502    public void systemReady() {
14503        mSystemReady = true;
14504
14505        // Read the compatibilty setting when the system is ready.
14506        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14507                mContext.getContentResolver(),
14508                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14509        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14510        if (DEBUG_SETTINGS) {
14511            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14512        }
14513
14514        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14515
14516        synchronized (mPackages) {
14517            // Verify that all of the preferred activity components actually
14518            // exist.  It is possible for applications to be updated and at
14519            // that point remove a previously declared activity component that
14520            // had been set as a preferred activity.  We try to clean this up
14521            // the next time we encounter that preferred activity, but it is
14522            // possible for the user flow to never be able to return to that
14523            // situation so here we do a sanity check to make sure we haven't
14524            // left any junk around.
14525            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14526            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14527                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14528                removed.clear();
14529                for (PreferredActivity pa : pir.filterSet()) {
14530                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14531                        removed.add(pa);
14532                    }
14533                }
14534                if (removed.size() > 0) {
14535                    for (int r=0; r<removed.size(); r++) {
14536                        PreferredActivity pa = removed.get(r);
14537                        Slog.w(TAG, "Removing dangling preferred activity: "
14538                                + pa.mPref.mComponent);
14539                        pir.removeFilter(pa);
14540                    }
14541                    mSettings.writePackageRestrictionsLPr(
14542                            mSettings.mPreferredActivities.keyAt(i));
14543                }
14544            }
14545
14546            for (int userId : UserManagerService.getInstance().getUserIds()) {
14547                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14548                    grantPermissionsUserIds = ArrayUtils.appendInt(
14549                            grantPermissionsUserIds, userId);
14550                }
14551            }
14552        }
14553        sUserManager.systemReady();
14554
14555        // If we upgraded grant all default permissions before kicking off.
14556        for (int userId : grantPermissionsUserIds) {
14557            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14558        }
14559
14560        // Kick off any messages waiting for system ready
14561        if (mPostSystemReadyMessages != null) {
14562            for (Message msg : mPostSystemReadyMessages) {
14563                msg.sendToTarget();
14564            }
14565            mPostSystemReadyMessages = null;
14566        }
14567
14568        // Watch for external volumes that come and go over time
14569        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14570        storage.registerListener(mStorageListener);
14571
14572        mInstallerService.systemReady();
14573        mPackageDexOptimizer.systemReady();
14574
14575        MountServiceInternal mountServiceInternal = LocalServices.getService(
14576                MountServiceInternal.class);
14577        mountServiceInternal.addExternalStoragePolicy(
14578                new MountServiceInternal.ExternalStorageMountPolicy() {
14579            @Override
14580            public int getMountMode(int uid, String packageName) {
14581                if (Process.isIsolated(uid)) {
14582                    return Zygote.MOUNT_EXTERNAL_NONE;
14583                }
14584                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14585                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14586                }
14587                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14588                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14589                }
14590                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14591                    return Zygote.MOUNT_EXTERNAL_READ;
14592                }
14593                return Zygote.MOUNT_EXTERNAL_WRITE;
14594            }
14595
14596            @Override
14597            public boolean hasExternalStorage(int uid, String packageName) {
14598                return true;
14599            }
14600        });
14601    }
14602
14603    @Override
14604    public boolean isSafeMode() {
14605        return mSafeMode;
14606    }
14607
14608    @Override
14609    public boolean hasSystemUidErrors() {
14610        return mHasSystemUidErrors;
14611    }
14612
14613    static String arrayToString(int[] array) {
14614        StringBuffer buf = new StringBuffer(128);
14615        buf.append('[');
14616        if (array != null) {
14617            for (int i=0; i<array.length; i++) {
14618                if (i > 0) buf.append(", ");
14619                buf.append(array[i]);
14620            }
14621        }
14622        buf.append(']');
14623        return buf.toString();
14624    }
14625
14626    static class DumpState {
14627        public static final int DUMP_LIBS = 1 << 0;
14628        public static final int DUMP_FEATURES = 1 << 1;
14629        public static final int DUMP_RESOLVERS = 1 << 2;
14630        public static final int DUMP_PERMISSIONS = 1 << 3;
14631        public static final int DUMP_PACKAGES = 1 << 4;
14632        public static final int DUMP_SHARED_USERS = 1 << 5;
14633        public static final int DUMP_MESSAGES = 1 << 6;
14634        public static final int DUMP_PROVIDERS = 1 << 7;
14635        public static final int DUMP_VERIFIERS = 1 << 8;
14636        public static final int DUMP_PREFERRED = 1 << 9;
14637        public static final int DUMP_PREFERRED_XML = 1 << 10;
14638        public static final int DUMP_KEYSETS = 1 << 11;
14639        public static final int DUMP_VERSION = 1 << 12;
14640        public static final int DUMP_INSTALLS = 1 << 13;
14641        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14642        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14643
14644        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14645
14646        private int mTypes;
14647
14648        private int mOptions;
14649
14650        private boolean mTitlePrinted;
14651
14652        private SharedUserSetting mSharedUser;
14653
14654        public boolean isDumping(int type) {
14655            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14656                return true;
14657            }
14658
14659            return (mTypes & type) != 0;
14660        }
14661
14662        public void setDump(int type) {
14663            mTypes |= type;
14664        }
14665
14666        public boolean isOptionEnabled(int option) {
14667            return (mOptions & option) != 0;
14668        }
14669
14670        public void setOptionEnabled(int option) {
14671            mOptions |= option;
14672        }
14673
14674        public boolean onTitlePrinted() {
14675            final boolean printed = mTitlePrinted;
14676            mTitlePrinted = true;
14677            return printed;
14678        }
14679
14680        public boolean getTitlePrinted() {
14681            return mTitlePrinted;
14682        }
14683
14684        public void setTitlePrinted(boolean enabled) {
14685            mTitlePrinted = enabled;
14686        }
14687
14688        public SharedUserSetting getSharedUser() {
14689            return mSharedUser;
14690        }
14691
14692        public void setSharedUser(SharedUserSetting user) {
14693            mSharedUser = user;
14694        }
14695    }
14696
14697    @Override
14698    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14699        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14700                != PackageManager.PERMISSION_GRANTED) {
14701            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14702                    + Binder.getCallingPid()
14703                    + ", uid=" + Binder.getCallingUid()
14704                    + " without permission "
14705                    + android.Manifest.permission.DUMP);
14706            return;
14707        }
14708
14709        DumpState dumpState = new DumpState();
14710        boolean fullPreferred = false;
14711        boolean checkin = false;
14712
14713        String packageName = null;
14714        ArraySet<String> permissionNames = null;
14715
14716        int opti = 0;
14717        while (opti < args.length) {
14718            String opt = args[opti];
14719            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14720                break;
14721            }
14722            opti++;
14723
14724            if ("-a".equals(opt)) {
14725                // Right now we only know how to print all.
14726            } else if ("-h".equals(opt)) {
14727                pw.println("Package manager dump options:");
14728                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14729                pw.println("    --checkin: dump for a checkin");
14730                pw.println("    -f: print details of intent filters");
14731                pw.println("    -h: print this help");
14732                pw.println("  cmd may be one of:");
14733                pw.println("    l[ibraries]: list known shared libraries");
14734                pw.println("    f[ibraries]: list device features");
14735                pw.println("    k[eysets]: print known keysets");
14736                pw.println("    r[esolvers]: dump intent resolvers");
14737                pw.println("    perm[issions]: dump permissions");
14738                pw.println("    permission [name ...]: dump declaration and use of given permission");
14739                pw.println("    pref[erred]: print preferred package settings");
14740                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14741                pw.println("    prov[iders]: dump content providers");
14742                pw.println("    p[ackages]: dump installed packages");
14743                pw.println("    s[hared-users]: dump shared user IDs");
14744                pw.println("    m[essages]: print collected runtime messages");
14745                pw.println("    v[erifiers]: print package verifier info");
14746                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14747                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14748                pw.println("    version: print database version info");
14749                pw.println("    write: write current settings now");
14750                pw.println("    installs: details about install sessions");
14751                pw.println("    <package.name>: info about given package");
14752                return;
14753            } else if ("--checkin".equals(opt)) {
14754                checkin = true;
14755            } else if ("-f".equals(opt)) {
14756                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14757            } else {
14758                pw.println("Unknown argument: " + opt + "; use -h for help");
14759            }
14760        }
14761
14762        // Is the caller requesting to dump a particular piece of data?
14763        if (opti < args.length) {
14764            String cmd = args[opti];
14765            opti++;
14766            // Is this a package name?
14767            if ("android".equals(cmd) || cmd.contains(".")) {
14768                packageName = cmd;
14769                // When dumping a single package, we always dump all of its
14770                // filter information since the amount of data will be reasonable.
14771                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14772            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14773                dumpState.setDump(DumpState.DUMP_LIBS);
14774            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14775                dumpState.setDump(DumpState.DUMP_FEATURES);
14776            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14777                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14778            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14779                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14780            } else if ("permission".equals(cmd)) {
14781                if (opti >= args.length) {
14782                    pw.println("Error: permission requires permission name");
14783                    return;
14784                }
14785                permissionNames = new ArraySet<>();
14786                while (opti < args.length) {
14787                    permissionNames.add(args[opti]);
14788                    opti++;
14789                }
14790                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14791                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14792            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14793                dumpState.setDump(DumpState.DUMP_PREFERRED);
14794            } else if ("preferred-xml".equals(cmd)) {
14795                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14796                if (opti < args.length && "--full".equals(args[opti])) {
14797                    fullPreferred = true;
14798                    opti++;
14799                }
14800            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14801                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14802            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14803                dumpState.setDump(DumpState.DUMP_PACKAGES);
14804            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14805                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14806            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14807                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14808            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14809                dumpState.setDump(DumpState.DUMP_MESSAGES);
14810            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14811                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14812            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14813                    || "intent-filter-verifiers".equals(cmd)) {
14814                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14815            } else if ("version".equals(cmd)) {
14816                dumpState.setDump(DumpState.DUMP_VERSION);
14817            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14818                dumpState.setDump(DumpState.DUMP_KEYSETS);
14819            } else if ("installs".equals(cmd)) {
14820                dumpState.setDump(DumpState.DUMP_INSTALLS);
14821            } else if ("write".equals(cmd)) {
14822                synchronized (mPackages) {
14823                    mSettings.writeLPr();
14824                    pw.println("Settings written.");
14825                    return;
14826                }
14827            }
14828        }
14829
14830        if (checkin) {
14831            pw.println("vers,1");
14832        }
14833
14834        // reader
14835        synchronized (mPackages) {
14836            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14837                if (!checkin) {
14838                    if (dumpState.onTitlePrinted())
14839                        pw.println();
14840                    pw.println("Database versions:");
14841                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14842                }
14843            }
14844
14845            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14846                if (!checkin) {
14847                    if (dumpState.onTitlePrinted())
14848                        pw.println();
14849                    pw.println("Verifiers:");
14850                    pw.print("  Required: ");
14851                    pw.print(mRequiredVerifierPackage);
14852                    pw.print(" (uid=");
14853                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14854                    pw.println(")");
14855                } else if (mRequiredVerifierPackage != null) {
14856                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14857                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14858                }
14859            }
14860
14861            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14862                    packageName == null) {
14863                if (mIntentFilterVerifierComponent != null) {
14864                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14865                    if (!checkin) {
14866                        if (dumpState.onTitlePrinted())
14867                            pw.println();
14868                        pw.println("Intent Filter Verifier:");
14869                        pw.print("  Using: ");
14870                        pw.print(verifierPackageName);
14871                        pw.print(" (uid=");
14872                        pw.print(getPackageUid(verifierPackageName, 0));
14873                        pw.println(")");
14874                    } else if (verifierPackageName != null) {
14875                        pw.print("ifv,"); pw.print(verifierPackageName);
14876                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14877                    }
14878                } else {
14879                    pw.println();
14880                    pw.println("No Intent Filter Verifier available!");
14881                }
14882            }
14883
14884            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14885                boolean printedHeader = false;
14886                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14887                while (it.hasNext()) {
14888                    String name = it.next();
14889                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14890                    if (!checkin) {
14891                        if (!printedHeader) {
14892                            if (dumpState.onTitlePrinted())
14893                                pw.println();
14894                            pw.println("Libraries:");
14895                            printedHeader = true;
14896                        }
14897                        pw.print("  ");
14898                    } else {
14899                        pw.print("lib,");
14900                    }
14901                    pw.print(name);
14902                    if (!checkin) {
14903                        pw.print(" -> ");
14904                    }
14905                    if (ent.path != null) {
14906                        if (!checkin) {
14907                            pw.print("(jar) ");
14908                            pw.print(ent.path);
14909                        } else {
14910                            pw.print(",jar,");
14911                            pw.print(ent.path);
14912                        }
14913                    } else {
14914                        if (!checkin) {
14915                            pw.print("(apk) ");
14916                            pw.print(ent.apk);
14917                        } else {
14918                            pw.print(",apk,");
14919                            pw.print(ent.apk);
14920                        }
14921                    }
14922                    pw.println();
14923                }
14924            }
14925
14926            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14927                if (dumpState.onTitlePrinted())
14928                    pw.println();
14929                if (!checkin) {
14930                    pw.println("Features:");
14931                }
14932                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14933                while (it.hasNext()) {
14934                    String name = it.next();
14935                    if (!checkin) {
14936                        pw.print("  ");
14937                    } else {
14938                        pw.print("feat,");
14939                    }
14940                    pw.println(name);
14941                }
14942            }
14943
14944            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14945                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14946                        : "Activity Resolver Table:", "  ", packageName,
14947                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14948                    dumpState.setTitlePrinted(true);
14949                }
14950                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14951                        : "Receiver Resolver Table:", "  ", packageName,
14952                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14953                    dumpState.setTitlePrinted(true);
14954                }
14955                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14956                        : "Service Resolver Table:", "  ", packageName,
14957                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14958                    dumpState.setTitlePrinted(true);
14959                }
14960                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14961                        : "Provider Resolver Table:", "  ", packageName,
14962                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14963                    dumpState.setTitlePrinted(true);
14964                }
14965            }
14966
14967            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14968                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14969                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14970                    int user = mSettings.mPreferredActivities.keyAt(i);
14971                    if (pir.dump(pw,
14972                            dumpState.getTitlePrinted()
14973                                ? "\nPreferred Activities User " + user + ":"
14974                                : "Preferred Activities User " + user + ":", "  ",
14975                            packageName, true, false)) {
14976                        dumpState.setTitlePrinted(true);
14977                    }
14978                }
14979            }
14980
14981            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14982                pw.flush();
14983                FileOutputStream fout = new FileOutputStream(fd);
14984                BufferedOutputStream str = new BufferedOutputStream(fout);
14985                XmlSerializer serializer = new FastXmlSerializer();
14986                try {
14987                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14988                    serializer.startDocument(null, true);
14989                    serializer.setFeature(
14990                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14991                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14992                    serializer.endDocument();
14993                    serializer.flush();
14994                } catch (IllegalArgumentException e) {
14995                    pw.println("Failed writing: " + e);
14996                } catch (IllegalStateException e) {
14997                    pw.println("Failed writing: " + e);
14998                } catch (IOException e) {
14999                    pw.println("Failed writing: " + e);
15000                }
15001            }
15002
15003            if (!checkin
15004                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15005                    && packageName == null) {
15006                pw.println();
15007                int count = mSettings.mPackages.size();
15008                if (count == 0) {
15009                    pw.println("No applications!");
15010                    pw.println();
15011                } else {
15012                    final String prefix = "  ";
15013                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15014                    if (allPackageSettings.size() == 0) {
15015                        pw.println("No domain preferred apps!");
15016                        pw.println();
15017                    } else {
15018                        pw.println("App verification status:");
15019                        pw.println();
15020                        count = 0;
15021                        for (PackageSetting ps : allPackageSettings) {
15022                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15023                            if (ivi == null || ivi.getPackageName() == null) continue;
15024                            pw.println(prefix + "Package: " + ivi.getPackageName());
15025                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15026                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15027                            pw.println();
15028                            count++;
15029                        }
15030                        if (count == 0) {
15031                            pw.println(prefix + "No app verification established.");
15032                            pw.println();
15033                        }
15034                        for (int userId : sUserManager.getUserIds()) {
15035                            pw.println("App linkages for user " + userId + ":");
15036                            pw.println();
15037                            count = 0;
15038                            for (PackageSetting ps : allPackageSettings) {
15039                                final long status = ps.getDomainVerificationStatusForUser(userId);
15040                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15041                                    continue;
15042                                }
15043                                pw.println(prefix + "Package: " + ps.name);
15044                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15045                                String statusStr = IntentFilterVerificationInfo.
15046                                        getStatusStringFromValue(status);
15047                                pw.println(prefix + "Status:  " + statusStr);
15048                                pw.println();
15049                                count++;
15050                            }
15051                            if (count == 0) {
15052                                pw.println(prefix + "No configured app linkages.");
15053                                pw.println();
15054                            }
15055                        }
15056                    }
15057                }
15058            }
15059
15060            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15061                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15062                if (packageName == null && permissionNames == null) {
15063                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15064                        if (iperm == 0) {
15065                            if (dumpState.onTitlePrinted())
15066                                pw.println();
15067                            pw.println("AppOp Permissions:");
15068                        }
15069                        pw.print("  AppOp Permission ");
15070                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15071                        pw.println(":");
15072                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15073                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15074                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15075                        }
15076                    }
15077                }
15078            }
15079
15080            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15081                boolean printedSomething = false;
15082                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15083                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15084                        continue;
15085                    }
15086                    if (!printedSomething) {
15087                        if (dumpState.onTitlePrinted())
15088                            pw.println();
15089                        pw.println("Registered ContentProviders:");
15090                        printedSomething = true;
15091                    }
15092                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15093                    pw.print("    "); pw.println(p.toString());
15094                }
15095                printedSomething = false;
15096                for (Map.Entry<String, PackageParser.Provider> entry :
15097                        mProvidersByAuthority.entrySet()) {
15098                    PackageParser.Provider p = entry.getValue();
15099                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15100                        continue;
15101                    }
15102                    if (!printedSomething) {
15103                        if (dumpState.onTitlePrinted())
15104                            pw.println();
15105                        pw.println("ContentProvider Authorities:");
15106                        printedSomething = true;
15107                    }
15108                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15109                    pw.print("    "); pw.println(p.toString());
15110                    if (p.info != null && p.info.applicationInfo != null) {
15111                        final String appInfo = p.info.applicationInfo.toString();
15112                        pw.print("      applicationInfo="); pw.println(appInfo);
15113                    }
15114                }
15115            }
15116
15117            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15118                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15119            }
15120
15121            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15122                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15123            }
15124
15125            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15126                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15127            }
15128
15129            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15130                // XXX should handle packageName != null by dumping only install data that
15131                // the given package is involved with.
15132                if (dumpState.onTitlePrinted()) pw.println();
15133                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15134            }
15135
15136            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15137                if (dumpState.onTitlePrinted()) pw.println();
15138                mSettings.dumpReadMessagesLPr(pw, dumpState);
15139
15140                pw.println();
15141                pw.println("Package warning messages:");
15142                BufferedReader in = null;
15143                String line = null;
15144                try {
15145                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15146                    while ((line = in.readLine()) != null) {
15147                        if (line.contains("ignored: updated version")) continue;
15148                        pw.println(line);
15149                    }
15150                } catch (IOException ignored) {
15151                } finally {
15152                    IoUtils.closeQuietly(in);
15153                }
15154            }
15155
15156            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15157                BufferedReader in = null;
15158                String line = null;
15159                try {
15160                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15161                    while ((line = in.readLine()) != null) {
15162                        if (line.contains("ignored: updated version")) continue;
15163                        pw.print("msg,");
15164                        pw.println(line);
15165                    }
15166                } catch (IOException ignored) {
15167                } finally {
15168                    IoUtils.closeQuietly(in);
15169                }
15170            }
15171        }
15172    }
15173
15174    private String dumpDomainString(String packageName) {
15175        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15176        List<IntentFilter> filters = getAllIntentFilters(packageName);
15177
15178        ArraySet<String> result = new ArraySet<>();
15179        if (iviList.size() > 0) {
15180            for (IntentFilterVerificationInfo ivi : iviList) {
15181                for (String host : ivi.getDomains()) {
15182                    result.add(host);
15183                }
15184            }
15185        }
15186        if (filters != null && filters.size() > 0) {
15187            for (IntentFilter filter : filters) {
15188                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15189                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15190                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15191                    result.addAll(filter.getHostsList());
15192                }
15193            }
15194        }
15195
15196        StringBuilder sb = new StringBuilder(result.size() * 16);
15197        for (String domain : result) {
15198            if (sb.length() > 0) sb.append(" ");
15199            sb.append(domain);
15200        }
15201        return sb.toString();
15202    }
15203
15204    // ------- apps on sdcard specific code -------
15205    static final boolean DEBUG_SD_INSTALL = false;
15206
15207    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15208
15209    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15210
15211    private boolean mMediaMounted = false;
15212
15213    static String getEncryptKey() {
15214        try {
15215            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15216                    SD_ENCRYPTION_KEYSTORE_NAME);
15217            if (sdEncKey == null) {
15218                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15219                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15220                if (sdEncKey == null) {
15221                    Slog.e(TAG, "Failed to create encryption keys");
15222                    return null;
15223                }
15224            }
15225            return sdEncKey;
15226        } catch (NoSuchAlgorithmException nsae) {
15227            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15228            return null;
15229        } catch (IOException ioe) {
15230            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15231            return null;
15232        }
15233    }
15234
15235    /*
15236     * Update media status on PackageManager.
15237     */
15238    @Override
15239    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15240        int callingUid = Binder.getCallingUid();
15241        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15242            throw new SecurityException("Media status can only be updated by the system");
15243        }
15244        // reader; this apparently protects mMediaMounted, but should probably
15245        // be a different lock in that case.
15246        synchronized (mPackages) {
15247            Log.i(TAG, "Updating external media status from "
15248                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15249                    + (mediaStatus ? "mounted" : "unmounted"));
15250            if (DEBUG_SD_INSTALL)
15251                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15252                        + ", mMediaMounted=" + mMediaMounted);
15253            if (mediaStatus == mMediaMounted) {
15254                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15255                        : 0, -1);
15256                mHandler.sendMessage(msg);
15257                return;
15258            }
15259            mMediaMounted = mediaStatus;
15260        }
15261        // Queue up an async operation since the package installation may take a
15262        // little while.
15263        mHandler.post(new Runnable() {
15264            public void run() {
15265                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15266            }
15267        });
15268    }
15269
15270    /**
15271     * Called by MountService when the initial ASECs to scan are available.
15272     * Should block until all the ASEC containers are finished being scanned.
15273     */
15274    public void scanAvailableAsecs() {
15275        updateExternalMediaStatusInner(true, false, false);
15276        if (mShouldRestoreconData) {
15277            SELinuxMMAC.setRestoreconDone();
15278            mShouldRestoreconData = false;
15279        }
15280    }
15281
15282    /*
15283     * Collect information of applications on external media, map them against
15284     * existing containers and update information based on current mount status.
15285     * Please note that we always have to report status if reportStatus has been
15286     * set to true especially when unloading packages.
15287     */
15288    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15289            boolean externalStorage) {
15290        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15291        int[] uidArr = EmptyArray.INT;
15292
15293        final String[] list = PackageHelper.getSecureContainerList();
15294        if (ArrayUtils.isEmpty(list)) {
15295            Log.i(TAG, "No secure containers found");
15296        } else {
15297            // Process list of secure containers and categorize them
15298            // as active or stale based on their package internal state.
15299
15300            // reader
15301            synchronized (mPackages) {
15302                for (String cid : list) {
15303                    // Leave stages untouched for now; installer service owns them
15304                    if (PackageInstallerService.isStageName(cid)) continue;
15305
15306                    if (DEBUG_SD_INSTALL)
15307                        Log.i(TAG, "Processing container " + cid);
15308                    String pkgName = getAsecPackageName(cid);
15309                    if (pkgName == null) {
15310                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15311                        continue;
15312                    }
15313                    if (DEBUG_SD_INSTALL)
15314                        Log.i(TAG, "Looking for pkg : " + pkgName);
15315
15316                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15317                    if (ps == null) {
15318                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15319                        continue;
15320                    }
15321
15322                    /*
15323                     * Skip packages that are not external if we're unmounting
15324                     * external storage.
15325                     */
15326                    if (externalStorage && !isMounted && !isExternal(ps)) {
15327                        continue;
15328                    }
15329
15330                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15331                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15332                    // The package status is changed only if the code path
15333                    // matches between settings and the container id.
15334                    if (ps.codePathString != null
15335                            && ps.codePathString.startsWith(args.getCodePath())) {
15336                        if (DEBUG_SD_INSTALL) {
15337                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15338                                    + " at code path: " + ps.codePathString);
15339                        }
15340
15341                        // We do have a valid package installed on sdcard
15342                        processCids.put(args, ps.codePathString);
15343                        final int uid = ps.appId;
15344                        if (uid != -1) {
15345                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15346                        }
15347                    } else {
15348                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15349                                + ps.codePathString);
15350                    }
15351                }
15352            }
15353
15354            Arrays.sort(uidArr);
15355        }
15356
15357        // Process packages with valid entries.
15358        if (isMounted) {
15359            if (DEBUG_SD_INSTALL)
15360                Log.i(TAG, "Loading packages");
15361            loadMediaPackages(processCids, uidArr);
15362            startCleaningPackages();
15363            mInstallerService.onSecureContainersAvailable();
15364        } else {
15365            if (DEBUG_SD_INSTALL)
15366                Log.i(TAG, "Unloading packages");
15367            unloadMediaPackages(processCids, uidArr, reportStatus);
15368        }
15369    }
15370
15371    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15372            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15373        final int size = infos.size();
15374        final String[] packageNames = new String[size];
15375        final int[] packageUids = new int[size];
15376        for (int i = 0; i < size; i++) {
15377            final ApplicationInfo info = infos.get(i);
15378            packageNames[i] = info.packageName;
15379            packageUids[i] = info.uid;
15380        }
15381        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15382                finishedReceiver);
15383    }
15384
15385    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15386            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15387        sendResourcesChangedBroadcast(mediaStatus, replacing,
15388                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15389    }
15390
15391    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15392            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15393        int size = pkgList.length;
15394        if (size > 0) {
15395            // Send broadcasts here
15396            Bundle extras = new Bundle();
15397            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15398            if (uidArr != null) {
15399                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15400            }
15401            if (replacing) {
15402                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15403            }
15404            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15405                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15406            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15407        }
15408    }
15409
15410   /*
15411     * Look at potentially valid container ids from processCids If package
15412     * information doesn't match the one on record or package scanning fails,
15413     * the cid is added to list of removeCids. We currently don't delete stale
15414     * containers.
15415     */
15416    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15417        ArrayList<String> pkgList = new ArrayList<String>();
15418        Set<AsecInstallArgs> keys = processCids.keySet();
15419
15420        for (AsecInstallArgs args : keys) {
15421            String codePath = processCids.get(args);
15422            if (DEBUG_SD_INSTALL)
15423                Log.i(TAG, "Loading container : " + args.cid);
15424            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15425            try {
15426                // Make sure there are no container errors first.
15427                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15428                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15429                            + " when installing from sdcard");
15430                    continue;
15431                }
15432                // Check code path here.
15433                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15434                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15435                            + " does not match one in settings " + codePath);
15436                    continue;
15437                }
15438                // Parse package
15439                int parseFlags = mDefParseFlags;
15440                if (args.isExternalAsec()) {
15441                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15442                }
15443                if (args.isFwdLocked()) {
15444                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15445                }
15446
15447                synchronized (mInstallLock) {
15448                    PackageParser.Package pkg = null;
15449                    try {
15450                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15451                    } catch (PackageManagerException e) {
15452                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15453                    }
15454                    // Scan the package
15455                    if (pkg != null) {
15456                        /*
15457                         * TODO why is the lock being held? doPostInstall is
15458                         * called in other places without the lock. This needs
15459                         * to be straightened out.
15460                         */
15461                        // writer
15462                        synchronized (mPackages) {
15463                            retCode = PackageManager.INSTALL_SUCCEEDED;
15464                            pkgList.add(pkg.packageName);
15465                            // Post process args
15466                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15467                                    pkg.applicationInfo.uid);
15468                        }
15469                    } else {
15470                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15471                    }
15472                }
15473
15474            } finally {
15475                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15476                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15477                }
15478            }
15479        }
15480        // writer
15481        synchronized (mPackages) {
15482            // If the platform SDK has changed since the last time we booted,
15483            // we need to re-grant app permission to catch any new ones that
15484            // appear. This is really a hack, and means that apps can in some
15485            // cases get permissions that the user didn't initially explicitly
15486            // allow... it would be nice to have some better way to handle
15487            // this situation.
15488            final VersionInfo ver = mSettings.getExternalVersion();
15489
15490            int updateFlags = UPDATE_PERMISSIONS_ALL;
15491            if (ver.sdkVersion != mSdkVersion) {
15492                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15493                        + mSdkVersion + "; regranting permissions for external");
15494                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15495            }
15496            updatePermissionsLPw(null, null, updateFlags);
15497
15498            // Yay, everything is now upgraded
15499            ver.forceCurrent();
15500
15501            // can downgrade to reader
15502            // Persist settings
15503            mSettings.writeLPr();
15504        }
15505        // Send a broadcast to let everyone know we are done processing
15506        if (pkgList.size() > 0) {
15507            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15508        }
15509    }
15510
15511   /*
15512     * Utility method to unload a list of specified containers
15513     */
15514    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15515        // Just unmount all valid containers.
15516        for (AsecInstallArgs arg : cidArgs) {
15517            synchronized (mInstallLock) {
15518                arg.doPostDeleteLI(false);
15519           }
15520       }
15521   }
15522
15523    /*
15524     * Unload packages mounted on external media. This involves deleting package
15525     * data from internal structures, sending broadcasts about diabled packages,
15526     * gc'ing to free up references, unmounting all secure containers
15527     * corresponding to packages on external media, and posting a
15528     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15529     * that we always have to post this message if status has been requested no
15530     * matter what.
15531     */
15532    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15533            final boolean reportStatus) {
15534        if (DEBUG_SD_INSTALL)
15535            Log.i(TAG, "unloading media packages");
15536        ArrayList<String> pkgList = new ArrayList<String>();
15537        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15538        final Set<AsecInstallArgs> keys = processCids.keySet();
15539        for (AsecInstallArgs args : keys) {
15540            String pkgName = args.getPackageName();
15541            if (DEBUG_SD_INSTALL)
15542                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15543            // Delete package internally
15544            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15545            synchronized (mInstallLock) {
15546                boolean res = deletePackageLI(pkgName, null, false, null, null,
15547                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15548                if (res) {
15549                    pkgList.add(pkgName);
15550                } else {
15551                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15552                    failedList.add(args);
15553                }
15554            }
15555        }
15556
15557        // reader
15558        synchronized (mPackages) {
15559            // We didn't update the settings after removing each package;
15560            // write them now for all packages.
15561            mSettings.writeLPr();
15562        }
15563
15564        // We have to absolutely send UPDATED_MEDIA_STATUS only
15565        // after confirming that all the receivers processed the ordered
15566        // broadcast when packages get disabled, force a gc to clean things up.
15567        // and unload all the containers.
15568        if (pkgList.size() > 0) {
15569            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15570                    new IIntentReceiver.Stub() {
15571                public void performReceive(Intent intent, int resultCode, String data,
15572                        Bundle extras, boolean ordered, boolean sticky,
15573                        int sendingUser) throws RemoteException {
15574                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15575                            reportStatus ? 1 : 0, 1, keys);
15576                    mHandler.sendMessage(msg);
15577                }
15578            });
15579        } else {
15580            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15581                    keys);
15582            mHandler.sendMessage(msg);
15583        }
15584    }
15585
15586    private void loadPrivatePackages(VolumeInfo vol) {
15587        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15588        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15589        synchronized (mInstallLock) {
15590        synchronized (mPackages) {
15591            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15592            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15593            for (PackageSetting ps : packages) {
15594                final PackageParser.Package pkg;
15595                try {
15596                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15597                    loaded.add(pkg.applicationInfo);
15598                } catch (PackageManagerException e) {
15599                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15600                }
15601
15602                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15603                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15604                }
15605            }
15606
15607            int updateFlags = UPDATE_PERMISSIONS_ALL;
15608            if (ver.sdkVersion != mSdkVersion) {
15609                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15610                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15611                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15612            }
15613            updatePermissionsLPw(null, null, updateFlags);
15614
15615            // Yay, everything is now upgraded
15616            ver.forceCurrent();
15617
15618            mSettings.writeLPr();
15619        }
15620        }
15621
15622        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15623        sendResourcesChangedBroadcast(true, false, loaded, null);
15624    }
15625
15626    private void unloadPrivatePackages(VolumeInfo vol) {
15627        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15628        synchronized (mInstallLock) {
15629        synchronized (mPackages) {
15630            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15631            for (PackageSetting ps : packages) {
15632                if (ps.pkg == null) continue;
15633
15634                final ApplicationInfo info = ps.pkg.applicationInfo;
15635                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15636                if (deletePackageLI(ps.name, null, false, null, null,
15637                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15638                    unloaded.add(info);
15639                } else {
15640                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15641                }
15642            }
15643
15644            mSettings.writeLPr();
15645        }
15646        }
15647
15648        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15649        sendResourcesChangedBroadcast(false, false, unloaded, null);
15650    }
15651
15652    /**
15653     * Examine all users present on given mounted volume, and destroy data
15654     * belonging to users that are no longer valid, or whose user ID has been
15655     * recycled.
15656     */
15657    private void reconcileUsers(String volumeUuid) {
15658        final File[] files = FileUtils
15659                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15660        for (File file : files) {
15661            if (!file.isDirectory()) continue;
15662
15663            final int userId;
15664            final UserInfo info;
15665            try {
15666                userId = Integer.parseInt(file.getName());
15667                info = sUserManager.getUserInfo(userId);
15668            } catch (NumberFormatException e) {
15669                Slog.w(TAG, "Invalid user directory " + file);
15670                continue;
15671            }
15672
15673            boolean destroyUser = false;
15674            if (info == null) {
15675                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15676                        + " because no matching user was found");
15677                destroyUser = true;
15678            } else {
15679                try {
15680                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15681                } catch (IOException e) {
15682                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15683                            + " because we failed to enforce serial number: " + e);
15684                    destroyUser = true;
15685                }
15686            }
15687
15688            if (destroyUser) {
15689                synchronized (mInstallLock) {
15690                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15691                }
15692            }
15693        }
15694
15695        final UserManager um = mContext.getSystemService(UserManager.class);
15696        for (UserInfo user : um.getUsers()) {
15697            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15698            if (userDir.exists()) continue;
15699
15700            try {
15701                UserManagerService.prepareUserDirectory(userDir);
15702                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15703            } catch (IOException e) {
15704                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15705            }
15706        }
15707    }
15708
15709    /**
15710     * Examine all apps present on given mounted volume, and destroy apps that
15711     * aren't expected, either due to uninstallation or reinstallation on
15712     * another volume.
15713     */
15714    private void reconcileApps(String volumeUuid) {
15715        final File[] files = FileUtils
15716                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15717        for (File file : files) {
15718            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15719                    && !PackageInstallerService.isStageName(file.getName());
15720            if (!isPackage) {
15721                // Ignore entries which are not packages
15722                continue;
15723            }
15724
15725            boolean destroyApp = false;
15726            String packageName = null;
15727            try {
15728                final PackageLite pkg = PackageParser.parsePackageLite(file,
15729                        PackageParser.PARSE_MUST_BE_APK);
15730                packageName = pkg.packageName;
15731
15732                synchronized (mPackages) {
15733                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15734                    if (ps == null) {
15735                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15736                                + volumeUuid + " because we found no install record");
15737                        destroyApp = true;
15738                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15739                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15740                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15741                        destroyApp = true;
15742                    }
15743                }
15744
15745            } catch (PackageParserException e) {
15746                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15747                destroyApp = true;
15748            }
15749
15750            if (destroyApp) {
15751                synchronized (mInstallLock) {
15752                    if (packageName != null) {
15753                        removeDataDirsLI(volumeUuid, packageName);
15754                    }
15755                    if (file.isDirectory()) {
15756                        mInstaller.rmPackageDir(file.getAbsolutePath());
15757                    } else {
15758                        file.delete();
15759                    }
15760                }
15761            }
15762        }
15763    }
15764
15765    private void unfreezePackage(String packageName) {
15766        synchronized (mPackages) {
15767            final PackageSetting ps = mSettings.mPackages.get(packageName);
15768            if (ps != null) {
15769                ps.frozen = false;
15770            }
15771        }
15772    }
15773
15774    @Override
15775    public int movePackage(final String packageName, final String volumeUuid) {
15776        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15777
15778        final int moveId = mNextMoveId.getAndIncrement();
15779        try {
15780            movePackageInternal(packageName, volumeUuid, moveId);
15781        } catch (PackageManagerException e) {
15782            Slog.w(TAG, "Failed to move " + packageName, e);
15783            mMoveCallbacks.notifyStatusChanged(moveId,
15784                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15785        }
15786        return moveId;
15787    }
15788
15789    private void movePackageInternal(final String packageName, final String volumeUuid,
15790            final int moveId) throws PackageManagerException {
15791        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15792        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15793        final PackageManager pm = mContext.getPackageManager();
15794
15795        final boolean currentAsec;
15796        final String currentVolumeUuid;
15797        final File codeFile;
15798        final String installerPackageName;
15799        final String packageAbiOverride;
15800        final int appId;
15801        final String seinfo;
15802        final String label;
15803
15804        // reader
15805        synchronized (mPackages) {
15806            final PackageParser.Package pkg = mPackages.get(packageName);
15807            final PackageSetting ps = mSettings.mPackages.get(packageName);
15808            if (pkg == null || ps == null) {
15809                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15810            }
15811
15812            if (pkg.applicationInfo.isSystemApp()) {
15813                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15814                        "Cannot move system application");
15815            }
15816
15817            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15818                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15819                        "Package already moved to " + volumeUuid);
15820            }
15821
15822            final File probe = new File(pkg.codePath);
15823            final File probeOat = new File(probe, "oat");
15824            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15825                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15826                        "Move only supported for modern cluster style installs");
15827            }
15828
15829            if (ps.frozen) {
15830                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15831                        "Failed to move already frozen package");
15832            }
15833            ps.frozen = true;
15834
15835            currentAsec = pkg.applicationInfo.isForwardLocked()
15836                    || pkg.applicationInfo.isExternalAsec();
15837            currentVolumeUuid = ps.volumeUuid;
15838            codeFile = new File(pkg.codePath);
15839            installerPackageName = ps.installerPackageName;
15840            packageAbiOverride = ps.cpuAbiOverrideString;
15841            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15842            seinfo = pkg.applicationInfo.seinfo;
15843            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15844        }
15845
15846        // Now that we're guarded by frozen state, kill app during move
15847        final long token = Binder.clearCallingIdentity();
15848        try {
15849            killApplication(packageName, appId, "move pkg");
15850        } finally {
15851            Binder.restoreCallingIdentity(token);
15852        }
15853
15854        final Bundle extras = new Bundle();
15855        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15856        extras.putString(Intent.EXTRA_TITLE, label);
15857        mMoveCallbacks.notifyCreated(moveId, extras);
15858
15859        int installFlags;
15860        final boolean moveCompleteApp;
15861        final File measurePath;
15862
15863        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15864            installFlags = INSTALL_INTERNAL;
15865            moveCompleteApp = !currentAsec;
15866            measurePath = Environment.getDataAppDirectory(volumeUuid);
15867        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15868            installFlags = INSTALL_EXTERNAL;
15869            moveCompleteApp = false;
15870            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15871        } else {
15872            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15873            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15874                    || !volume.isMountedWritable()) {
15875                unfreezePackage(packageName);
15876                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15877                        "Move location not mounted private volume");
15878            }
15879
15880            Preconditions.checkState(!currentAsec);
15881
15882            installFlags = INSTALL_INTERNAL;
15883            moveCompleteApp = true;
15884            measurePath = Environment.getDataAppDirectory(volumeUuid);
15885        }
15886
15887        final PackageStats stats = new PackageStats(null, -1);
15888        synchronized (mInstaller) {
15889            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15890                unfreezePackage(packageName);
15891                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15892                        "Failed to measure package size");
15893            }
15894        }
15895
15896        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15897                + stats.dataSize);
15898
15899        final long startFreeBytes = measurePath.getFreeSpace();
15900        final long sizeBytes;
15901        if (moveCompleteApp) {
15902            sizeBytes = stats.codeSize + stats.dataSize;
15903        } else {
15904            sizeBytes = stats.codeSize;
15905        }
15906
15907        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15908            unfreezePackage(packageName);
15909            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15910                    "Not enough free space to move");
15911        }
15912
15913        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15914
15915        final CountDownLatch installedLatch = new CountDownLatch(1);
15916        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15917            @Override
15918            public void onUserActionRequired(Intent intent) throws RemoteException {
15919                throw new IllegalStateException();
15920            }
15921
15922            @Override
15923            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15924                    Bundle extras) throws RemoteException {
15925                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15926                        + PackageManager.installStatusToString(returnCode, msg));
15927
15928                installedLatch.countDown();
15929
15930                // Regardless of success or failure of the move operation,
15931                // always unfreeze the package
15932                unfreezePackage(packageName);
15933
15934                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15935                switch (status) {
15936                    case PackageInstaller.STATUS_SUCCESS:
15937                        mMoveCallbacks.notifyStatusChanged(moveId,
15938                                PackageManager.MOVE_SUCCEEDED);
15939                        break;
15940                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15941                        mMoveCallbacks.notifyStatusChanged(moveId,
15942                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15943                        break;
15944                    default:
15945                        mMoveCallbacks.notifyStatusChanged(moveId,
15946                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15947                        break;
15948                }
15949            }
15950        };
15951
15952        final MoveInfo move;
15953        if (moveCompleteApp) {
15954            // Kick off a thread to report progress estimates
15955            new Thread() {
15956                @Override
15957                public void run() {
15958                    while (true) {
15959                        try {
15960                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15961                                break;
15962                            }
15963                        } catch (InterruptedException ignored) {
15964                        }
15965
15966                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15967                        final int progress = 10 + (int) MathUtils.constrain(
15968                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15969                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15970                    }
15971                }
15972            }.start();
15973
15974            final String dataAppName = codeFile.getName();
15975            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15976                    dataAppName, appId, seinfo);
15977        } else {
15978            move = null;
15979        }
15980
15981        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15982
15983        final Message msg = mHandler.obtainMessage(INIT_COPY);
15984        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15985        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15986                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15987        mHandler.sendMessage(msg);
15988    }
15989
15990    @Override
15991    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15992        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15993
15994        final int realMoveId = mNextMoveId.getAndIncrement();
15995        final Bundle extras = new Bundle();
15996        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15997        mMoveCallbacks.notifyCreated(realMoveId, extras);
15998
15999        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16000            @Override
16001            public void onCreated(int moveId, Bundle extras) {
16002                // Ignored
16003            }
16004
16005            @Override
16006            public void onStatusChanged(int moveId, int status, long estMillis) {
16007                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16008            }
16009        };
16010
16011        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16012        storage.setPrimaryStorageUuid(volumeUuid, callback);
16013        return realMoveId;
16014    }
16015
16016    @Override
16017    public int getMoveStatus(int moveId) {
16018        mContext.enforceCallingOrSelfPermission(
16019                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16020        return mMoveCallbacks.mLastStatus.get(moveId);
16021    }
16022
16023    @Override
16024    public void registerMoveCallback(IPackageMoveObserver callback) {
16025        mContext.enforceCallingOrSelfPermission(
16026                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16027        mMoveCallbacks.register(callback);
16028    }
16029
16030    @Override
16031    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16032        mContext.enforceCallingOrSelfPermission(
16033                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16034        mMoveCallbacks.unregister(callback);
16035    }
16036
16037    @Override
16038    public boolean setInstallLocation(int loc) {
16039        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16040                null);
16041        if (getInstallLocation() == loc) {
16042            return true;
16043        }
16044        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16045                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16046            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16047                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16048            return true;
16049        }
16050        return false;
16051   }
16052
16053    @Override
16054    public int getInstallLocation() {
16055        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16056                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16057                PackageHelper.APP_INSTALL_AUTO);
16058    }
16059
16060    /** Called by UserManagerService */
16061    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16062        mDirtyUsers.remove(userHandle);
16063        mSettings.removeUserLPw(userHandle);
16064        mPendingBroadcasts.remove(userHandle);
16065        if (mInstaller != null) {
16066            // Technically, we shouldn't be doing this with the package lock
16067            // held.  However, this is very rare, and there is already so much
16068            // other disk I/O going on, that we'll let it slide for now.
16069            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16070            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16071                final String volumeUuid = vol.getFsUuid();
16072                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16073                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16074            }
16075        }
16076        mUserNeedsBadging.delete(userHandle);
16077        removeUnusedPackagesLILPw(userManager, userHandle);
16078    }
16079
16080    /**
16081     * We're removing userHandle and would like to remove any downloaded packages
16082     * that are no longer in use by any other user.
16083     * @param userHandle the user being removed
16084     */
16085    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16086        final boolean DEBUG_CLEAN_APKS = false;
16087        int [] users = userManager.getUserIdsLPr();
16088        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16089        while (psit.hasNext()) {
16090            PackageSetting ps = psit.next();
16091            if (ps.pkg == null) {
16092                continue;
16093            }
16094            final String packageName = ps.pkg.packageName;
16095            // Skip over if system app
16096            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16097                continue;
16098            }
16099            if (DEBUG_CLEAN_APKS) {
16100                Slog.i(TAG, "Checking package " + packageName);
16101            }
16102            boolean keep = false;
16103            for (int i = 0; i < users.length; i++) {
16104                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16105                    keep = true;
16106                    if (DEBUG_CLEAN_APKS) {
16107                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16108                                + users[i]);
16109                    }
16110                    break;
16111                }
16112            }
16113            if (!keep) {
16114                if (DEBUG_CLEAN_APKS) {
16115                    Slog.i(TAG, "  Removing package " + packageName);
16116                }
16117                mHandler.post(new Runnable() {
16118                    public void run() {
16119                        deletePackageX(packageName, userHandle, 0);
16120                    } //end run
16121                });
16122            }
16123        }
16124    }
16125
16126    /** Called by UserManagerService */
16127    void createNewUserLILPw(int userHandle) {
16128        if (mInstaller != null) {
16129            mInstaller.createUserConfig(userHandle);
16130            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16131            applyFactoryDefaultBrowserLPw(userHandle);
16132            primeDomainVerificationsLPw(userHandle);
16133        }
16134    }
16135
16136    void newUserCreated(final int userHandle) {
16137        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16138    }
16139
16140    @Override
16141    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16142        mContext.enforceCallingOrSelfPermission(
16143                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16144                "Only package verification agents can read the verifier device identity");
16145
16146        synchronized (mPackages) {
16147            return mSettings.getVerifierDeviceIdentityLPw();
16148        }
16149    }
16150
16151    @Override
16152    public void setPermissionEnforced(String permission, boolean enforced) {
16153        // TODO: Now that we no longer change GID for storage, this should to away.
16154        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16155                "setPermissionEnforced");
16156        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16157            synchronized (mPackages) {
16158                if (mSettings.mReadExternalStorageEnforced == null
16159                        || mSettings.mReadExternalStorageEnforced != enforced) {
16160                    mSettings.mReadExternalStorageEnforced = enforced;
16161                    mSettings.writeLPr();
16162                }
16163            }
16164            // kill any non-foreground processes so we restart them and
16165            // grant/revoke the GID.
16166            final IActivityManager am = ActivityManagerNative.getDefault();
16167            if (am != null) {
16168                final long token = Binder.clearCallingIdentity();
16169                try {
16170                    am.killProcessesBelowForeground("setPermissionEnforcement");
16171                } catch (RemoteException e) {
16172                } finally {
16173                    Binder.restoreCallingIdentity(token);
16174                }
16175            }
16176        } else {
16177            throw new IllegalArgumentException("No selective enforcement for " + permission);
16178        }
16179    }
16180
16181    @Override
16182    @Deprecated
16183    public boolean isPermissionEnforced(String permission) {
16184        return true;
16185    }
16186
16187    @Override
16188    public boolean isStorageLow() {
16189        final long token = Binder.clearCallingIdentity();
16190        try {
16191            final DeviceStorageMonitorInternal
16192                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16193            if (dsm != null) {
16194                return dsm.isMemoryLow();
16195            } else {
16196                return false;
16197            }
16198        } finally {
16199            Binder.restoreCallingIdentity(token);
16200        }
16201    }
16202
16203    @Override
16204    public IPackageInstaller getPackageInstaller() {
16205        return mInstallerService;
16206    }
16207
16208    private boolean userNeedsBadging(int userId) {
16209        int index = mUserNeedsBadging.indexOfKey(userId);
16210        if (index < 0) {
16211            final UserInfo userInfo;
16212            final long token = Binder.clearCallingIdentity();
16213            try {
16214                userInfo = sUserManager.getUserInfo(userId);
16215            } finally {
16216                Binder.restoreCallingIdentity(token);
16217            }
16218            final boolean b;
16219            if (userInfo != null && userInfo.isManagedProfile()) {
16220                b = true;
16221            } else {
16222                b = false;
16223            }
16224            mUserNeedsBadging.put(userId, b);
16225            return b;
16226        }
16227        return mUserNeedsBadging.valueAt(index);
16228    }
16229
16230    @Override
16231    public KeySet getKeySetByAlias(String packageName, String alias) {
16232        if (packageName == null || alias == null) {
16233            return null;
16234        }
16235        synchronized(mPackages) {
16236            final PackageParser.Package pkg = mPackages.get(packageName);
16237            if (pkg == null) {
16238                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16239                throw new IllegalArgumentException("Unknown package: " + packageName);
16240            }
16241            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16242            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16243        }
16244    }
16245
16246    @Override
16247    public KeySet getSigningKeySet(String packageName) {
16248        if (packageName == null) {
16249            return null;
16250        }
16251        synchronized(mPackages) {
16252            final PackageParser.Package pkg = mPackages.get(packageName);
16253            if (pkg == null) {
16254                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16255                throw new IllegalArgumentException("Unknown package: " + packageName);
16256            }
16257            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16258                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16259                throw new SecurityException("May not access signing KeySet of other apps.");
16260            }
16261            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16262            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16263        }
16264    }
16265
16266    @Override
16267    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16268        if (packageName == null || ks == null) {
16269            return false;
16270        }
16271        synchronized(mPackages) {
16272            final PackageParser.Package pkg = mPackages.get(packageName);
16273            if (pkg == null) {
16274                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16275                throw new IllegalArgumentException("Unknown package: " + packageName);
16276            }
16277            IBinder ksh = ks.getToken();
16278            if (ksh instanceof KeySetHandle) {
16279                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16280                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16281            }
16282            return false;
16283        }
16284    }
16285
16286    @Override
16287    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16288        if (packageName == null || ks == null) {
16289            return false;
16290        }
16291        synchronized(mPackages) {
16292            final PackageParser.Package pkg = mPackages.get(packageName);
16293            if (pkg == null) {
16294                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16295                throw new IllegalArgumentException("Unknown package: " + packageName);
16296            }
16297            IBinder ksh = ks.getToken();
16298            if (ksh instanceof KeySetHandle) {
16299                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16300                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16301            }
16302            return false;
16303        }
16304    }
16305
16306    public void getUsageStatsIfNoPackageUsageInfo() {
16307        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16308            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16309            if (usm == null) {
16310                throw new IllegalStateException("UsageStatsManager must be initialized");
16311            }
16312            long now = System.currentTimeMillis();
16313            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16314            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16315                String packageName = entry.getKey();
16316                PackageParser.Package pkg = mPackages.get(packageName);
16317                if (pkg == null) {
16318                    continue;
16319                }
16320                UsageStats usage = entry.getValue();
16321                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16322                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16323            }
16324        }
16325    }
16326
16327    /**
16328     * Check and throw if the given before/after packages would be considered a
16329     * downgrade.
16330     */
16331    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16332            throws PackageManagerException {
16333        if (after.versionCode < before.mVersionCode) {
16334            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16335                    "Update version code " + after.versionCode + " is older than current "
16336                    + before.mVersionCode);
16337        } else if (after.versionCode == before.mVersionCode) {
16338            if (after.baseRevisionCode < before.baseRevisionCode) {
16339                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16340                        "Update base revision code " + after.baseRevisionCode
16341                        + " is older than current " + before.baseRevisionCode);
16342            }
16343
16344            if (!ArrayUtils.isEmpty(after.splitNames)) {
16345                for (int i = 0; i < after.splitNames.length; i++) {
16346                    final String splitName = after.splitNames[i];
16347                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16348                    if (j != -1) {
16349                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16350                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16351                                    "Update split " + splitName + " revision code "
16352                                    + after.splitRevisionCodes[i] + " is older than current "
16353                                    + before.splitRevisionCodes[j]);
16354                        }
16355                    }
16356                }
16357            }
16358        }
16359    }
16360
16361    private static class MoveCallbacks extends Handler {
16362        private static final int MSG_CREATED = 1;
16363        private static final int MSG_STATUS_CHANGED = 2;
16364
16365        private final RemoteCallbackList<IPackageMoveObserver>
16366                mCallbacks = new RemoteCallbackList<>();
16367
16368        private final SparseIntArray mLastStatus = new SparseIntArray();
16369
16370        public MoveCallbacks(Looper looper) {
16371            super(looper);
16372        }
16373
16374        public void register(IPackageMoveObserver callback) {
16375            mCallbacks.register(callback);
16376        }
16377
16378        public void unregister(IPackageMoveObserver callback) {
16379            mCallbacks.unregister(callback);
16380        }
16381
16382        @Override
16383        public void handleMessage(Message msg) {
16384            final SomeArgs args = (SomeArgs) msg.obj;
16385            final int n = mCallbacks.beginBroadcast();
16386            for (int i = 0; i < n; i++) {
16387                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16388                try {
16389                    invokeCallback(callback, msg.what, args);
16390                } catch (RemoteException ignored) {
16391                }
16392            }
16393            mCallbacks.finishBroadcast();
16394            args.recycle();
16395        }
16396
16397        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16398                throws RemoteException {
16399            switch (what) {
16400                case MSG_CREATED: {
16401                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16402                    break;
16403                }
16404                case MSG_STATUS_CHANGED: {
16405                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16406                    break;
16407                }
16408            }
16409        }
16410
16411        private void notifyCreated(int moveId, Bundle extras) {
16412            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16413
16414            final SomeArgs args = SomeArgs.obtain();
16415            args.argi1 = moveId;
16416            args.arg2 = extras;
16417            obtainMessage(MSG_CREATED, args).sendToTarget();
16418        }
16419
16420        private void notifyStatusChanged(int moveId, int status) {
16421            notifyStatusChanged(moveId, status, -1);
16422        }
16423
16424        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16425            Slog.v(TAG, "Move " + moveId + " status " + status);
16426
16427            final SomeArgs args = SomeArgs.obtain();
16428            args.argi1 = moveId;
16429            args.argi2 = status;
16430            args.arg3 = estMillis;
16431            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16432
16433            synchronized (mLastStatus) {
16434                mLastStatus.put(moveId, status);
16435            }
16436        }
16437    }
16438
16439    private final class OnPermissionChangeListeners extends Handler {
16440        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16441
16442        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16443                new RemoteCallbackList<>();
16444
16445        public OnPermissionChangeListeners(Looper looper) {
16446            super(looper);
16447        }
16448
16449        @Override
16450        public void handleMessage(Message msg) {
16451            switch (msg.what) {
16452                case MSG_ON_PERMISSIONS_CHANGED: {
16453                    final int uid = msg.arg1;
16454                    handleOnPermissionsChanged(uid);
16455                } break;
16456            }
16457        }
16458
16459        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16460            mPermissionListeners.register(listener);
16461
16462        }
16463
16464        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16465            mPermissionListeners.unregister(listener);
16466        }
16467
16468        public void onPermissionsChanged(int uid) {
16469            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16470                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16471            }
16472        }
16473
16474        private void handleOnPermissionsChanged(int uid) {
16475            final int count = mPermissionListeners.beginBroadcast();
16476            try {
16477                for (int i = 0; i < count; i++) {
16478                    IOnPermissionsChangeListener callback = mPermissionListeners
16479                            .getBroadcastItem(i);
16480                    try {
16481                        callback.onPermissionsChanged(uid);
16482                    } catch (RemoteException e) {
16483                        Log.e(TAG, "Permission listener is dead", e);
16484                    }
16485                }
16486            } finally {
16487                mPermissionListeners.finishBroadcast();
16488            }
16489        }
16490    }
16491
16492    private class PackageManagerInternalImpl extends PackageManagerInternal {
16493        @Override
16494        public void setLocationPackagesProvider(PackagesProvider provider) {
16495            synchronized (mPackages) {
16496                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16497            }
16498        }
16499
16500        @Override
16501        public void setImePackagesProvider(PackagesProvider provider) {
16502            synchronized (mPackages) {
16503                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16504            }
16505        }
16506
16507        @Override
16508        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16509            synchronized (mPackages) {
16510                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16511            }
16512        }
16513
16514        @Override
16515        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16516            synchronized (mPackages) {
16517                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16518            }
16519        }
16520
16521        @Override
16522        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16523            synchronized (mPackages) {
16524                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16525            }
16526        }
16527
16528        @Override
16529        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16530            synchronized (mPackages) {
16531                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16532            }
16533        }
16534
16535        @Override
16536        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16537            synchronized (mPackages) {
16538                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16539            }
16540        }
16541
16542        @Override
16543        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16544            synchronized (mPackages) {
16545                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16546                        packageName, userId);
16547            }
16548        }
16549
16550        @Override
16551        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16552            synchronized (mPackages) {
16553                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16554                        packageName, userId);
16555            }
16556        }
16557        @Override
16558        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16559            synchronized (mPackages) {
16560                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16561                        packageName, userId);
16562            }
16563        }
16564    }
16565
16566    @Override
16567    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16568        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16569        synchronized (mPackages) {
16570            final long identity = Binder.clearCallingIdentity();
16571            try {
16572                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16573                        packageNames, userId);
16574            } finally {
16575                Binder.restoreCallingIdentity(identity);
16576            }
16577        }
16578    }
16579
16580    private static void enforceSystemOrPhoneCaller(String tag) {
16581        int callingUid = Binder.getCallingUid();
16582        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16583            throw new SecurityException(
16584                    "Cannot call " + tag + " from UID " + callingUid);
16585        }
16586    }
16587}
16588