PackageManagerService.java revision c1836bb0f1bf3e5ef0911719525da0bab3e53507
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 List<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        }
5471
5472        return finalList;
5473    }
5474
5475    @Override
5476    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5477            int flags) {
5478        // reader
5479        synchronized (mPackages) {
5480            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5481            return PackageParser.generateInstrumentationInfo(i, flags);
5482        }
5483    }
5484
5485    @Override
5486    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5487            int flags) {
5488        ArrayList<InstrumentationInfo> finalList =
5489            new ArrayList<InstrumentationInfo>();
5490
5491        // reader
5492        synchronized (mPackages) {
5493            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5494            while (i.hasNext()) {
5495                final PackageParser.Instrumentation p = i.next();
5496                if (targetPackage == null
5497                        || targetPackage.equals(p.info.targetPackage)) {
5498                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5499                            flags);
5500                    if (ii != null) {
5501                        finalList.add(ii);
5502                    }
5503                }
5504            }
5505        }
5506
5507        return finalList;
5508    }
5509
5510    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5511        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5512        if (overlays == null) {
5513            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5514            return;
5515        }
5516        for (PackageParser.Package opkg : overlays.values()) {
5517            // Not much to do if idmap fails: we already logged the error
5518            // and we certainly don't want to abort installation of pkg simply
5519            // because an overlay didn't fit properly. For these reasons,
5520            // ignore the return value of createIdmapForPackagePairLI.
5521            createIdmapForPackagePairLI(pkg, opkg);
5522        }
5523    }
5524
5525    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5526            PackageParser.Package opkg) {
5527        if (!opkg.mTrustedOverlay) {
5528            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5529                    opkg.baseCodePath + ": overlay not trusted");
5530            return false;
5531        }
5532        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5533        if (overlaySet == null) {
5534            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5535                    opkg.baseCodePath + " but target package has no known overlays");
5536            return false;
5537        }
5538        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5539        // TODO: generate idmap for split APKs
5540        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5541            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5542                    + opkg.baseCodePath);
5543            return false;
5544        }
5545        PackageParser.Package[] overlayArray =
5546            overlaySet.values().toArray(new PackageParser.Package[0]);
5547        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5548            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5549                return p1.mOverlayPriority - p2.mOverlayPriority;
5550            }
5551        };
5552        Arrays.sort(overlayArray, cmp);
5553
5554        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5555        int i = 0;
5556        for (PackageParser.Package p : overlayArray) {
5557            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5558        }
5559        return true;
5560    }
5561
5562    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5563        final File[] files = dir.listFiles();
5564        if (ArrayUtils.isEmpty(files)) {
5565            Log.d(TAG, "No files in app dir " + dir);
5566            return;
5567        }
5568
5569        if (DEBUG_PACKAGE_SCANNING) {
5570            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5571                    + " flags=0x" + Integer.toHexString(parseFlags));
5572        }
5573
5574        for (File file : files) {
5575            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5576                    && !PackageInstallerService.isStageName(file.getName());
5577            if (!isPackage) {
5578                // Ignore entries which are not packages
5579                continue;
5580            }
5581            try {
5582                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5583                        scanFlags, currentTime, null);
5584            } catch (PackageManagerException e) {
5585                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5586
5587                // Delete invalid userdata apps
5588                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5589                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5590                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5591                    if (file.isDirectory()) {
5592                        mInstaller.rmPackageDir(file.getAbsolutePath());
5593                    } else {
5594                        file.delete();
5595                    }
5596                }
5597            }
5598        }
5599    }
5600
5601    private static File getSettingsProblemFile() {
5602        File dataDir = Environment.getDataDirectory();
5603        File systemDir = new File(dataDir, "system");
5604        File fname = new File(systemDir, "uiderrors.txt");
5605        return fname;
5606    }
5607
5608    static void reportSettingsProblem(int priority, String msg) {
5609        logCriticalInfo(priority, msg);
5610    }
5611
5612    static void logCriticalInfo(int priority, String msg) {
5613        Slog.println(priority, TAG, msg);
5614        EventLogTags.writePmCriticalInfo(msg);
5615        try {
5616            File fname = getSettingsProblemFile();
5617            FileOutputStream out = new FileOutputStream(fname, true);
5618            PrintWriter pw = new FastPrintWriter(out);
5619            SimpleDateFormat formatter = new SimpleDateFormat();
5620            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5621            pw.println(dateString + ": " + msg);
5622            pw.close();
5623            FileUtils.setPermissions(
5624                    fname.toString(),
5625                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5626                    -1, -1);
5627        } catch (java.io.IOException e) {
5628        }
5629    }
5630
5631    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5632            PackageParser.Package pkg, File srcFile, int parseFlags)
5633            throws PackageManagerException {
5634        if (ps != null
5635                && ps.codePath.equals(srcFile)
5636                && ps.timeStamp == srcFile.lastModified()
5637                && !isCompatSignatureUpdateNeeded(pkg)
5638                && !isRecoverSignatureUpdateNeeded(pkg)) {
5639            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5640            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5641            ArraySet<PublicKey> signingKs;
5642            synchronized (mPackages) {
5643                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5644            }
5645            if (ps.signatures.mSignatures != null
5646                    && ps.signatures.mSignatures.length != 0
5647                    && signingKs != null) {
5648                // Optimization: reuse the existing cached certificates
5649                // if the package appears to be unchanged.
5650                pkg.mSignatures = ps.signatures.mSignatures;
5651                pkg.mSigningKeys = signingKs;
5652                return;
5653            }
5654
5655            Slog.w(TAG, "PackageSetting for " + ps.name
5656                    + " is missing signatures.  Collecting certs again to recover them.");
5657        } else {
5658            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5659        }
5660
5661        try {
5662            pp.collectCertificates(pkg, parseFlags);
5663            pp.collectManifestDigest(pkg);
5664        } catch (PackageParserException e) {
5665            throw PackageManagerException.from(e);
5666        }
5667    }
5668
5669    /*
5670     *  Scan a package and return the newly parsed package.
5671     *  Returns null in case of errors and the error code is stored in mLastScanError
5672     */
5673    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5674            long currentTime, UserHandle user) throws PackageManagerException {
5675        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5676        parseFlags |= mDefParseFlags;
5677        PackageParser pp = new PackageParser();
5678        pp.setSeparateProcesses(mSeparateProcesses);
5679        pp.setOnlyCoreApps(mOnlyCore);
5680        pp.setDisplayMetrics(mMetrics);
5681
5682        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5683            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5684        }
5685
5686        final PackageParser.Package pkg;
5687        try {
5688            pkg = pp.parsePackage(scanFile, parseFlags);
5689        } catch (PackageParserException e) {
5690            throw PackageManagerException.from(e);
5691        }
5692
5693        PackageSetting ps = null;
5694        PackageSetting updatedPkg;
5695        // reader
5696        synchronized (mPackages) {
5697            // Look to see if we already know about this package.
5698            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5699            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5700                // This package has been renamed to its original name.  Let's
5701                // use that.
5702                ps = mSettings.peekPackageLPr(oldName);
5703            }
5704            // If there was no original package, see one for the real package name.
5705            if (ps == null) {
5706                ps = mSettings.peekPackageLPr(pkg.packageName);
5707            }
5708            // Check to see if this package could be hiding/updating a system
5709            // package.  Must look for it either under the original or real
5710            // package name depending on our state.
5711            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5712            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5713        }
5714        boolean updatedPkgBetter = false;
5715        // First check if this is a system package that may involve an update
5716        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5717            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5718            // it needs to drop FLAG_PRIVILEGED.
5719            if (locationIsPrivileged(scanFile)) {
5720                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5721            } else {
5722                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5723            }
5724
5725            if (ps != null && !ps.codePath.equals(scanFile)) {
5726                // The path has changed from what was last scanned...  check the
5727                // version of the new path against what we have stored to determine
5728                // what to do.
5729                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5730                if (pkg.mVersionCode <= ps.versionCode) {
5731                    // The system package has been updated and the code path does not match
5732                    // Ignore entry. Skip it.
5733                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5734                            + " ignored: updated version " + ps.versionCode
5735                            + " better than this " + pkg.mVersionCode);
5736                    if (!updatedPkg.codePath.equals(scanFile)) {
5737                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5738                                + ps.name + " changing from " + updatedPkg.codePathString
5739                                + " to " + scanFile);
5740                        updatedPkg.codePath = scanFile;
5741                        updatedPkg.codePathString = scanFile.toString();
5742                        updatedPkg.resourcePath = scanFile;
5743                        updatedPkg.resourcePathString = scanFile.toString();
5744                    }
5745                    updatedPkg.pkg = pkg;
5746                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5747                            "Package " + ps.name + " at " + scanFile
5748                                    + " ignored: updated version " + ps.versionCode
5749                                    + " better than this " + pkg.mVersionCode);
5750                } else {
5751                    // The current app on the system partition is better than
5752                    // what we have updated to on the data partition; switch
5753                    // back to the system partition version.
5754                    // At this point, its safely assumed that package installation for
5755                    // apps in system partition will go through. If not there won't be a working
5756                    // version of the app
5757                    // writer
5758                    synchronized (mPackages) {
5759                        // Just remove the loaded entries from package lists.
5760                        mPackages.remove(ps.name);
5761                    }
5762
5763                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5764                            + " reverting from " + ps.codePathString
5765                            + ": new version " + pkg.mVersionCode
5766                            + " better than installed " + ps.versionCode);
5767
5768                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5769                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5770                    synchronized (mInstallLock) {
5771                        args.cleanUpResourcesLI();
5772                    }
5773                    synchronized (mPackages) {
5774                        mSettings.enableSystemPackageLPw(ps.name);
5775                    }
5776                    updatedPkgBetter = true;
5777                }
5778            }
5779        }
5780
5781        if (updatedPkg != null) {
5782            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5783            // initially
5784            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5785
5786            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5787            // flag set initially
5788            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5789                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5790            }
5791        }
5792
5793        // Verify certificates against what was last scanned
5794        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5795
5796        /*
5797         * A new system app appeared, but we already had a non-system one of the
5798         * same name installed earlier.
5799         */
5800        boolean shouldHideSystemApp = false;
5801        if (updatedPkg == null && ps != null
5802                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5803            /*
5804             * Check to make sure the signatures match first. If they don't,
5805             * wipe the installed application and its data.
5806             */
5807            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5808                    != PackageManager.SIGNATURE_MATCH) {
5809                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5810                        + " signatures don't match existing userdata copy; removing");
5811                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5812                ps = null;
5813            } else {
5814                /*
5815                 * If the newly-added system app is an older version than the
5816                 * already installed version, hide it. It will be scanned later
5817                 * and re-added like an update.
5818                 */
5819                if (pkg.mVersionCode <= ps.versionCode) {
5820                    shouldHideSystemApp = true;
5821                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5822                            + " but new version " + pkg.mVersionCode + " better than installed "
5823                            + ps.versionCode + "; hiding system");
5824                } else {
5825                    /*
5826                     * The newly found system app is a newer version that the
5827                     * one previously installed. Simply remove the
5828                     * already-installed application and replace it with our own
5829                     * while keeping the application data.
5830                     */
5831                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5832                            + " reverting from " + ps.codePathString + ": new version "
5833                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5834                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5835                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5836                    synchronized (mInstallLock) {
5837                        args.cleanUpResourcesLI();
5838                    }
5839                }
5840            }
5841        }
5842
5843        // The apk is forward locked (not public) if its code and resources
5844        // are kept in different files. (except for app in either system or
5845        // vendor path).
5846        // TODO grab this value from PackageSettings
5847        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5848            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5849                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5850            }
5851        }
5852
5853        // TODO: extend to support forward-locked splits
5854        String resourcePath = null;
5855        String baseResourcePath = null;
5856        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5857            if (ps != null && ps.resourcePathString != null) {
5858                resourcePath = ps.resourcePathString;
5859                baseResourcePath = ps.resourcePathString;
5860            } else {
5861                // Should not happen at all. Just log an error.
5862                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5863            }
5864        } else {
5865            resourcePath = pkg.codePath;
5866            baseResourcePath = pkg.baseCodePath;
5867        }
5868
5869        // Set application objects path explicitly.
5870        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5871        pkg.applicationInfo.setCodePath(pkg.codePath);
5872        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5873        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5874        pkg.applicationInfo.setResourcePath(resourcePath);
5875        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5876        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5877
5878        // Note that we invoke the following method only if we are about to unpack an application
5879        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5880                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5881
5882        /*
5883         * If the system app should be overridden by a previously installed
5884         * data, hide the system app now and let the /data/app scan pick it up
5885         * again.
5886         */
5887        if (shouldHideSystemApp) {
5888            synchronized (mPackages) {
5889                /*
5890                 * We have to grant systems permissions before we hide, because
5891                 * grantPermissions will assume the package update is trying to
5892                 * expand its permissions.
5893                 */
5894                grantPermissionsLPw(pkg, true, pkg.packageName);
5895                mSettings.disableSystemPackageLPw(pkg.packageName);
5896            }
5897        }
5898
5899        return scannedPkg;
5900    }
5901
5902    private static String fixProcessName(String defProcessName,
5903            String processName, int uid) {
5904        if (processName == null) {
5905            return defProcessName;
5906        }
5907        return processName;
5908    }
5909
5910    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5911            throws PackageManagerException {
5912        if (pkgSetting.signatures.mSignatures != null) {
5913            // Already existing package. Make sure signatures match
5914            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5915                    == PackageManager.SIGNATURE_MATCH;
5916            if (!match) {
5917                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5918                        == PackageManager.SIGNATURE_MATCH;
5919            }
5920            if (!match) {
5921                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5922                        == PackageManager.SIGNATURE_MATCH;
5923            }
5924            if (!match) {
5925                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5926                        + pkg.packageName + " signatures do not match the "
5927                        + "previously installed version; ignoring!");
5928            }
5929        }
5930
5931        // Check for shared user signatures
5932        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5933            // Already existing package. Make sure signatures match
5934            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5935                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5936            if (!match) {
5937                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5938                        == PackageManager.SIGNATURE_MATCH;
5939            }
5940            if (!match) {
5941                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5942                        == PackageManager.SIGNATURE_MATCH;
5943            }
5944            if (!match) {
5945                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5946                        "Package " + pkg.packageName
5947                        + " has no signatures that match those in shared user "
5948                        + pkgSetting.sharedUser.name + "; ignoring!");
5949            }
5950        }
5951    }
5952
5953    /**
5954     * Enforces that only the system UID or root's UID can call a method exposed
5955     * via Binder.
5956     *
5957     * @param message used as message if SecurityException is thrown
5958     * @throws SecurityException if the caller is not system or root
5959     */
5960    private static final void enforceSystemOrRoot(String message) {
5961        final int uid = Binder.getCallingUid();
5962        if (uid != Process.SYSTEM_UID && uid != 0) {
5963            throw new SecurityException(message);
5964        }
5965    }
5966
5967    @Override
5968    public void performBootDexOpt() {
5969        enforceSystemOrRoot("Only the system can request dexopt be performed");
5970
5971        // Before everything else, see whether we need to fstrim.
5972        try {
5973            IMountService ms = PackageHelper.getMountService();
5974            if (ms != null) {
5975                final boolean isUpgrade = isUpgrade();
5976                boolean doTrim = isUpgrade;
5977                if (doTrim) {
5978                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5979                } else {
5980                    final long interval = android.provider.Settings.Global.getLong(
5981                            mContext.getContentResolver(),
5982                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5983                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5984                    if (interval > 0) {
5985                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5986                        if (timeSinceLast > interval) {
5987                            doTrim = true;
5988                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5989                                    + "; running immediately");
5990                        }
5991                    }
5992                }
5993                if (doTrim) {
5994                    if (!isFirstBoot()) {
5995                        try {
5996                            ActivityManagerNative.getDefault().showBootMessage(
5997                                    mContext.getResources().getString(
5998                                            R.string.android_upgrading_fstrim), true);
5999                        } catch (RemoteException e) {
6000                        }
6001                    }
6002                    ms.runMaintenance();
6003                }
6004            } else {
6005                Slog.e(TAG, "Mount service unavailable!");
6006            }
6007        } catch (RemoteException e) {
6008            // Can't happen; MountService is local
6009        }
6010
6011        final ArraySet<PackageParser.Package> pkgs;
6012        synchronized (mPackages) {
6013            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6014        }
6015
6016        if (pkgs != null) {
6017            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6018            // in case the device runs out of space.
6019            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6020            // Give priority to core apps.
6021            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6022                PackageParser.Package pkg = it.next();
6023                if (pkg.coreApp) {
6024                    if (DEBUG_DEXOPT) {
6025                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6026                    }
6027                    sortedPkgs.add(pkg);
6028                    it.remove();
6029                }
6030            }
6031            // Give priority to system apps that listen for pre boot complete.
6032            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6033            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6034            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6035                PackageParser.Package pkg = it.next();
6036                if (pkgNames.contains(pkg.packageName)) {
6037                    if (DEBUG_DEXOPT) {
6038                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6039                    }
6040                    sortedPkgs.add(pkg);
6041                    it.remove();
6042                }
6043            }
6044            // Give priority to system apps.
6045            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6046                PackageParser.Package pkg = it.next();
6047                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6048                    if (DEBUG_DEXOPT) {
6049                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6050                    }
6051                    sortedPkgs.add(pkg);
6052                    it.remove();
6053                }
6054            }
6055            // Give priority to updated system apps.
6056            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6057                PackageParser.Package pkg = it.next();
6058                if (pkg.isUpdatedSystemApp()) {
6059                    if (DEBUG_DEXOPT) {
6060                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6061                    }
6062                    sortedPkgs.add(pkg);
6063                    it.remove();
6064                }
6065            }
6066            // Give priority to apps that listen for boot complete.
6067            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6068            pkgNames = getPackageNamesForIntent(intent);
6069            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6070                PackageParser.Package pkg = it.next();
6071                if (pkgNames.contains(pkg.packageName)) {
6072                    if (DEBUG_DEXOPT) {
6073                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6074                    }
6075                    sortedPkgs.add(pkg);
6076                    it.remove();
6077                }
6078            }
6079            // Filter out packages that aren't recently used.
6080            filterRecentlyUsedApps(pkgs);
6081            // Add all remaining apps.
6082            for (PackageParser.Package pkg : pkgs) {
6083                if (DEBUG_DEXOPT) {
6084                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6085                }
6086                sortedPkgs.add(pkg);
6087            }
6088
6089            // If we want to be lazy, filter everything that wasn't recently used.
6090            if (mLazyDexOpt) {
6091                filterRecentlyUsedApps(sortedPkgs);
6092            }
6093
6094            int i = 0;
6095            int total = sortedPkgs.size();
6096            File dataDir = Environment.getDataDirectory();
6097            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6098            if (lowThreshold == 0) {
6099                throw new IllegalStateException("Invalid low memory threshold");
6100            }
6101            for (PackageParser.Package pkg : sortedPkgs) {
6102                long usableSpace = dataDir.getUsableSpace();
6103                if (usableSpace < lowThreshold) {
6104                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6105                    break;
6106                }
6107                performBootDexOpt(pkg, ++i, total);
6108            }
6109        }
6110    }
6111
6112    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6113        // Filter out packages that aren't recently used.
6114        //
6115        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6116        // should do a full dexopt.
6117        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6118            int total = pkgs.size();
6119            int skipped = 0;
6120            long now = System.currentTimeMillis();
6121            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6122                PackageParser.Package pkg = i.next();
6123                long then = pkg.mLastPackageUsageTimeInMills;
6124                if (then + mDexOptLRUThresholdInMills < now) {
6125                    if (DEBUG_DEXOPT) {
6126                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6127                              ((then == 0) ? "never" : new Date(then)));
6128                    }
6129                    i.remove();
6130                    skipped++;
6131                }
6132            }
6133            if (DEBUG_DEXOPT) {
6134                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6135            }
6136        }
6137    }
6138
6139    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6140        List<ResolveInfo> ris = null;
6141        try {
6142            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6143                    intent, null, 0, UserHandle.USER_OWNER);
6144        } catch (RemoteException e) {
6145        }
6146        ArraySet<String> pkgNames = new ArraySet<String>();
6147        if (ris != null) {
6148            for (ResolveInfo ri : ris) {
6149                pkgNames.add(ri.activityInfo.packageName);
6150            }
6151        }
6152        return pkgNames;
6153    }
6154
6155    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6156        if (DEBUG_DEXOPT) {
6157            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6158        }
6159        if (!isFirstBoot()) {
6160            try {
6161                ActivityManagerNative.getDefault().showBootMessage(
6162                        mContext.getResources().getString(R.string.android_upgrading_apk,
6163                                curr, total), true);
6164            } catch (RemoteException e) {
6165            }
6166        }
6167        PackageParser.Package p = pkg;
6168        synchronized (mInstallLock) {
6169            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6170                    false /* force dex */, false /* defer */, true /* include dependencies */);
6171        }
6172    }
6173
6174    @Override
6175    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6176        return performDexOpt(packageName, instructionSet, false);
6177    }
6178
6179    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6180        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6181        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6182        if (!dexopt && !updateUsage) {
6183            // We aren't going to dexopt or update usage, so bail early.
6184            return false;
6185        }
6186        PackageParser.Package p;
6187        final String targetInstructionSet;
6188        synchronized (mPackages) {
6189            p = mPackages.get(packageName);
6190            if (p == null) {
6191                return false;
6192            }
6193            if (updateUsage) {
6194                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6195            }
6196            mPackageUsage.write(false);
6197            if (!dexopt) {
6198                // We aren't going to dexopt, so bail early.
6199                return false;
6200            }
6201
6202            targetInstructionSet = instructionSet != null ? instructionSet :
6203                    getPrimaryInstructionSet(p.applicationInfo);
6204            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6205                return false;
6206            }
6207        }
6208        long callingId = Binder.clearCallingIdentity();
6209        try {
6210            synchronized (mInstallLock) {
6211                final String[] instructionSets = new String[] { targetInstructionSet };
6212                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6213                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6214                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6215            }
6216        } finally {
6217            Binder.restoreCallingIdentity(callingId);
6218        }
6219    }
6220
6221    public ArraySet<String> getPackagesThatNeedDexOpt() {
6222        ArraySet<String> pkgs = null;
6223        synchronized (mPackages) {
6224            for (PackageParser.Package p : mPackages.values()) {
6225                if (DEBUG_DEXOPT) {
6226                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6227                }
6228                if (!p.mDexOptPerformed.isEmpty()) {
6229                    continue;
6230                }
6231                if (pkgs == null) {
6232                    pkgs = new ArraySet<String>();
6233                }
6234                pkgs.add(p.packageName);
6235            }
6236        }
6237        return pkgs;
6238    }
6239
6240    public void shutdown() {
6241        mPackageUsage.write(true);
6242    }
6243
6244    @Override
6245    public void forceDexOpt(String packageName) {
6246        enforceSystemOrRoot("forceDexOpt");
6247
6248        PackageParser.Package pkg;
6249        synchronized (mPackages) {
6250            pkg = mPackages.get(packageName);
6251            if (pkg == null) {
6252                throw new IllegalArgumentException("Missing package: " + packageName);
6253            }
6254        }
6255
6256        synchronized (mInstallLock) {
6257            final String[] instructionSets = new String[] {
6258                    getPrimaryInstructionSet(pkg.applicationInfo) };
6259            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6260                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6261            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6262                throw new IllegalStateException("Failed to dexopt: " + res);
6263            }
6264        }
6265    }
6266
6267    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6268        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6269            Slog.w(TAG, "Unable to update from " + oldPkg.name
6270                    + " to " + newPkg.packageName
6271                    + ": old package not in system partition");
6272            return false;
6273        } else if (mPackages.get(oldPkg.name) != null) {
6274            Slog.w(TAG, "Unable to update from " + oldPkg.name
6275                    + " to " + newPkg.packageName
6276                    + ": old package still exists");
6277            return false;
6278        }
6279        return true;
6280    }
6281
6282    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6283        int[] users = sUserManager.getUserIds();
6284        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6285        if (res < 0) {
6286            return res;
6287        }
6288        for (int user : users) {
6289            if (user != 0) {
6290                res = mInstaller.createUserData(volumeUuid, packageName,
6291                        UserHandle.getUid(user, uid), user, seinfo);
6292                if (res < 0) {
6293                    return res;
6294                }
6295            }
6296        }
6297        return res;
6298    }
6299
6300    private int removeDataDirsLI(String volumeUuid, String packageName) {
6301        int[] users = sUserManager.getUserIds();
6302        int res = 0;
6303        for (int user : users) {
6304            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6305            if (resInner < 0) {
6306                res = resInner;
6307            }
6308        }
6309
6310        return res;
6311    }
6312
6313    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6314        int[] users = sUserManager.getUserIds();
6315        int res = 0;
6316        for (int user : users) {
6317            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6318            if (resInner < 0) {
6319                res = resInner;
6320            }
6321        }
6322        return res;
6323    }
6324
6325    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6326            PackageParser.Package changingLib) {
6327        if (file.path != null) {
6328            usesLibraryFiles.add(file.path);
6329            return;
6330        }
6331        PackageParser.Package p = mPackages.get(file.apk);
6332        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6333            // If we are doing this while in the middle of updating a library apk,
6334            // then we need to make sure to use that new apk for determining the
6335            // dependencies here.  (We haven't yet finished committing the new apk
6336            // to the package manager state.)
6337            if (p == null || p.packageName.equals(changingLib.packageName)) {
6338                p = changingLib;
6339            }
6340        }
6341        if (p != null) {
6342            usesLibraryFiles.addAll(p.getAllCodePaths());
6343        }
6344    }
6345
6346    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6347            PackageParser.Package changingLib) throws PackageManagerException {
6348        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6349            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6350            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6351            for (int i=0; i<N; i++) {
6352                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6353                if (file == null) {
6354                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6355                            "Package " + pkg.packageName + " requires unavailable shared library "
6356                            + pkg.usesLibraries.get(i) + "; failing!");
6357                }
6358                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6359            }
6360            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6361            for (int i=0; i<N; i++) {
6362                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6363                if (file == null) {
6364                    Slog.w(TAG, "Package " + pkg.packageName
6365                            + " desires unavailable shared library "
6366                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6367                } else {
6368                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6369                }
6370            }
6371            N = usesLibraryFiles.size();
6372            if (N > 0) {
6373                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6374            } else {
6375                pkg.usesLibraryFiles = null;
6376            }
6377        }
6378    }
6379
6380    private static boolean hasString(List<String> list, List<String> which) {
6381        if (list == null) {
6382            return false;
6383        }
6384        for (int i=list.size()-1; i>=0; i--) {
6385            for (int j=which.size()-1; j>=0; j--) {
6386                if (which.get(j).equals(list.get(i))) {
6387                    return true;
6388                }
6389            }
6390        }
6391        return false;
6392    }
6393
6394    private void updateAllSharedLibrariesLPw() {
6395        for (PackageParser.Package pkg : mPackages.values()) {
6396            try {
6397                updateSharedLibrariesLPw(pkg, null);
6398            } catch (PackageManagerException e) {
6399                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6400            }
6401        }
6402    }
6403
6404    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6405            PackageParser.Package changingPkg) {
6406        ArrayList<PackageParser.Package> res = null;
6407        for (PackageParser.Package pkg : mPackages.values()) {
6408            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6409                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6410                if (res == null) {
6411                    res = new ArrayList<PackageParser.Package>();
6412                }
6413                res.add(pkg);
6414                try {
6415                    updateSharedLibrariesLPw(pkg, changingPkg);
6416                } catch (PackageManagerException e) {
6417                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6418                }
6419            }
6420        }
6421        return res;
6422    }
6423
6424    /**
6425     * Derive the value of the {@code cpuAbiOverride} based on the provided
6426     * value and an optional stored value from the package settings.
6427     */
6428    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6429        String cpuAbiOverride = null;
6430
6431        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6432            cpuAbiOverride = null;
6433        } else if (abiOverride != null) {
6434            cpuAbiOverride = abiOverride;
6435        } else if (settings != null) {
6436            cpuAbiOverride = settings.cpuAbiOverrideString;
6437        }
6438
6439        return cpuAbiOverride;
6440    }
6441
6442    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6443            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6444        boolean success = false;
6445        try {
6446            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6447                    currentTime, user);
6448            success = true;
6449            return res;
6450        } finally {
6451            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6452                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6453            }
6454        }
6455    }
6456
6457    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6458            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6459        final File scanFile = new File(pkg.codePath);
6460        if (pkg.applicationInfo.getCodePath() == null ||
6461                pkg.applicationInfo.getResourcePath() == null) {
6462            // Bail out. The resource and code paths haven't been set.
6463            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6464                    "Code and resource paths haven't been set correctly");
6465        }
6466
6467        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6468            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6469        } else {
6470            // Only allow system apps to be flagged as core apps.
6471            pkg.coreApp = false;
6472        }
6473
6474        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6475            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6476        }
6477
6478        if (mCustomResolverComponentName != null &&
6479                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6480            setUpCustomResolverActivity(pkg);
6481        }
6482
6483        if (pkg.packageName.equals("android")) {
6484            synchronized (mPackages) {
6485                if (mAndroidApplication != null) {
6486                    Slog.w(TAG, "*************************************************");
6487                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6488                    Slog.w(TAG, " file=" + scanFile);
6489                    Slog.w(TAG, "*************************************************");
6490                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6491                            "Core android package being redefined.  Skipping.");
6492                }
6493
6494                // Set up information for our fall-back user intent resolution activity.
6495                mPlatformPackage = pkg;
6496                pkg.mVersionCode = mSdkVersion;
6497                mAndroidApplication = pkg.applicationInfo;
6498
6499                if (!mResolverReplaced) {
6500                    mResolveActivity.applicationInfo = mAndroidApplication;
6501                    mResolveActivity.name = ResolverActivity.class.getName();
6502                    mResolveActivity.packageName = mAndroidApplication.packageName;
6503                    mResolveActivity.processName = "system:ui";
6504                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6505                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6506                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6507                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6508                    mResolveActivity.exported = true;
6509                    mResolveActivity.enabled = true;
6510                    mResolveInfo.activityInfo = mResolveActivity;
6511                    mResolveInfo.priority = 0;
6512                    mResolveInfo.preferredOrder = 0;
6513                    mResolveInfo.match = 0;
6514                    mResolveComponentName = new ComponentName(
6515                            mAndroidApplication.packageName, mResolveActivity.name);
6516                }
6517            }
6518        }
6519
6520        if (DEBUG_PACKAGE_SCANNING) {
6521            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6522                Log.d(TAG, "Scanning package " + pkg.packageName);
6523        }
6524
6525        if (mPackages.containsKey(pkg.packageName)
6526                || mSharedLibraries.containsKey(pkg.packageName)) {
6527            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6528                    "Application package " + pkg.packageName
6529                    + " already installed.  Skipping duplicate.");
6530        }
6531
6532        // If we're only installing presumed-existing packages, require that the
6533        // scanned APK is both already known and at the path previously established
6534        // for it.  Previously unknown packages we pick up normally, but if we have an
6535        // a priori expectation about this package's install presence, enforce it.
6536        // With a singular exception for new system packages. When an OTA contains
6537        // a new system package, we allow the codepath to change from a system location
6538        // to the user-installed location. If we don't allow this change, any newer,
6539        // user-installed version of the application will be ignored.
6540        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6541            if (mExpectingBetter.containsKey(pkg.packageName)) {
6542                logCriticalInfo(Log.WARN,
6543                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6544            } else {
6545                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6546                if (known != null) {
6547                    if (DEBUG_PACKAGE_SCANNING) {
6548                        Log.d(TAG, "Examining " + pkg.codePath
6549                                + " and requiring known paths " + known.codePathString
6550                                + " & " + known.resourcePathString);
6551                    }
6552                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6553                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6554                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6555                                "Application package " + pkg.packageName
6556                                + " found at " + pkg.applicationInfo.getCodePath()
6557                                + " but expected at " + known.codePathString + "; ignoring.");
6558                    }
6559                }
6560            }
6561        }
6562
6563        // Initialize package source and resource directories
6564        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6565        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6566
6567        SharedUserSetting suid = null;
6568        PackageSetting pkgSetting = null;
6569
6570        if (!isSystemApp(pkg)) {
6571            // Only system apps can use these features.
6572            pkg.mOriginalPackages = null;
6573            pkg.mRealPackage = null;
6574            pkg.mAdoptPermissions = null;
6575        }
6576
6577        // writer
6578        synchronized (mPackages) {
6579            if (pkg.mSharedUserId != null) {
6580                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6581                if (suid == null) {
6582                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6583                            "Creating application package " + pkg.packageName
6584                            + " for shared user failed");
6585                }
6586                if (DEBUG_PACKAGE_SCANNING) {
6587                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6588                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6589                                + "): packages=" + suid.packages);
6590                }
6591            }
6592
6593            // Check if we are renaming from an original package name.
6594            PackageSetting origPackage = null;
6595            String realName = null;
6596            if (pkg.mOriginalPackages != null) {
6597                // This package may need to be renamed to a previously
6598                // installed name.  Let's check on that...
6599                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6600                if (pkg.mOriginalPackages.contains(renamed)) {
6601                    // This package had originally been installed as the
6602                    // original name, and we have already taken care of
6603                    // transitioning to the new one.  Just update the new
6604                    // one to continue using the old name.
6605                    realName = pkg.mRealPackage;
6606                    if (!pkg.packageName.equals(renamed)) {
6607                        // Callers into this function may have already taken
6608                        // care of renaming the package; only do it here if
6609                        // it is not already done.
6610                        pkg.setPackageName(renamed);
6611                    }
6612
6613                } else {
6614                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6615                        if ((origPackage = mSettings.peekPackageLPr(
6616                                pkg.mOriginalPackages.get(i))) != null) {
6617                            // We do have the package already installed under its
6618                            // original name...  should we use it?
6619                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6620                                // New package is not compatible with original.
6621                                origPackage = null;
6622                                continue;
6623                            } else if (origPackage.sharedUser != null) {
6624                                // Make sure uid is compatible between packages.
6625                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6626                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6627                                            + " to " + pkg.packageName + ": old uid "
6628                                            + origPackage.sharedUser.name
6629                                            + " differs from " + pkg.mSharedUserId);
6630                                    origPackage = null;
6631                                    continue;
6632                                }
6633                            } else {
6634                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6635                                        + pkg.packageName + " to old name " + origPackage.name);
6636                            }
6637                            break;
6638                        }
6639                    }
6640                }
6641            }
6642
6643            if (mTransferedPackages.contains(pkg.packageName)) {
6644                Slog.w(TAG, "Package " + pkg.packageName
6645                        + " was transferred to another, but its .apk remains");
6646            }
6647
6648            // Just create the setting, don't add it yet. For already existing packages
6649            // the PkgSetting exists already and doesn't have to be created.
6650            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6651                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6652                    pkg.applicationInfo.primaryCpuAbi,
6653                    pkg.applicationInfo.secondaryCpuAbi,
6654                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6655                    user, false);
6656            if (pkgSetting == null) {
6657                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6658                        "Creating application package " + pkg.packageName + " failed");
6659            }
6660
6661            if (pkgSetting.origPackage != null) {
6662                // If we are first transitioning from an original package,
6663                // fix up the new package's name now.  We need to do this after
6664                // looking up the package under its new name, so getPackageLP
6665                // can take care of fiddling things correctly.
6666                pkg.setPackageName(origPackage.name);
6667
6668                // File a report about this.
6669                String msg = "New package " + pkgSetting.realName
6670                        + " renamed to replace old package " + pkgSetting.name;
6671                reportSettingsProblem(Log.WARN, msg);
6672
6673                // Make a note of it.
6674                mTransferedPackages.add(origPackage.name);
6675
6676                // No longer need to retain this.
6677                pkgSetting.origPackage = null;
6678            }
6679
6680            if (realName != null) {
6681                // Make a note of it.
6682                mTransferedPackages.add(pkg.packageName);
6683            }
6684
6685            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6686                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6687            }
6688
6689            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6690                // Check all shared libraries and map to their actual file path.
6691                // We only do this here for apps not on a system dir, because those
6692                // are the only ones that can fail an install due to this.  We
6693                // will take care of the system apps by updating all of their
6694                // library paths after the scan is done.
6695                updateSharedLibrariesLPw(pkg, null);
6696            }
6697
6698            if (mFoundPolicyFile) {
6699                SELinuxMMAC.assignSeinfoValue(pkg);
6700            }
6701
6702            pkg.applicationInfo.uid = pkgSetting.appId;
6703            pkg.mExtras = pkgSetting;
6704            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6705                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6706                    // We just determined the app is signed correctly, so bring
6707                    // over the latest parsed certs.
6708                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6709                } else {
6710                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6711                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6712                                "Package " + pkg.packageName + " upgrade keys do not match the "
6713                                + "previously installed version");
6714                    } else {
6715                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6716                        String msg = "System package " + pkg.packageName
6717                            + " signature changed; retaining data.";
6718                        reportSettingsProblem(Log.WARN, msg);
6719                    }
6720                }
6721            } else {
6722                try {
6723                    verifySignaturesLP(pkgSetting, pkg);
6724                    // We just determined the app is signed correctly, so bring
6725                    // over the latest parsed certs.
6726                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6727                } catch (PackageManagerException e) {
6728                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6729                        throw e;
6730                    }
6731                    // The signature has changed, but this package is in the system
6732                    // image...  let's recover!
6733                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6734                    // However...  if this package is part of a shared user, but it
6735                    // doesn't match the signature of the shared user, let's fail.
6736                    // What this means is that you can't change the signatures
6737                    // associated with an overall shared user, which doesn't seem all
6738                    // that unreasonable.
6739                    if (pkgSetting.sharedUser != null) {
6740                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6741                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6742                            throw new PackageManagerException(
6743                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6744                                            "Signature mismatch for shared user : "
6745                                            + pkgSetting.sharedUser);
6746                        }
6747                    }
6748                    // File a report about this.
6749                    String msg = "System package " + pkg.packageName
6750                        + " signature changed; retaining data.";
6751                    reportSettingsProblem(Log.WARN, msg);
6752                }
6753            }
6754            // Verify that this new package doesn't have any content providers
6755            // that conflict with existing packages.  Only do this if the
6756            // package isn't already installed, since we don't want to break
6757            // things that are installed.
6758            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6759                final int N = pkg.providers.size();
6760                int i;
6761                for (i=0; i<N; i++) {
6762                    PackageParser.Provider p = pkg.providers.get(i);
6763                    if (p.info.authority != null) {
6764                        String names[] = p.info.authority.split(";");
6765                        for (int j = 0; j < names.length; j++) {
6766                            if (mProvidersByAuthority.containsKey(names[j])) {
6767                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6768                                final String otherPackageName =
6769                                        ((other != null && other.getComponentName() != null) ?
6770                                                other.getComponentName().getPackageName() : "?");
6771                                throw new PackageManagerException(
6772                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6773                                                "Can't install because provider name " + names[j]
6774                                                + " (in package " + pkg.applicationInfo.packageName
6775                                                + ") is already used by " + otherPackageName);
6776                            }
6777                        }
6778                    }
6779                }
6780            }
6781
6782            if (pkg.mAdoptPermissions != null) {
6783                // This package wants to adopt ownership of permissions from
6784                // another package.
6785                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6786                    final String origName = pkg.mAdoptPermissions.get(i);
6787                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6788                    if (orig != null) {
6789                        if (verifyPackageUpdateLPr(orig, pkg)) {
6790                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6791                                    + pkg.packageName);
6792                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6793                        }
6794                    }
6795                }
6796            }
6797        }
6798
6799        final String pkgName = pkg.packageName;
6800
6801        final long scanFileTime = scanFile.lastModified();
6802        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6803        pkg.applicationInfo.processName = fixProcessName(
6804                pkg.applicationInfo.packageName,
6805                pkg.applicationInfo.processName,
6806                pkg.applicationInfo.uid);
6807
6808        File dataPath;
6809        if (mPlatformPackage == pkg) {
6810            // The system package is special.
6811            dataPath = new File(Environment.getDataDirectory(), "system");
6812
6813            pkg.applicationInfo.dataDir = dataPath.getPath();
6814
6815        } else {
6816            // This is a normal package, need to make its data directory.
6817            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6818                    UserHandle.USER_OWNER, pkg.packageName);
6819
6820            boolean uidError = false;
6821            if (dataPath.exists()) {
6822                int currentUid = 0;
6823                try {
6824                    StructStat stat = Os.stat(dataPath.getPath());
6825                    currentUid = stat.st_uid;
6826                } catch (ErrnoException e) {
6827                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6828                }
6829
6830                // If we have mismatched owners for the data path, we have a problem.
6831                if (currentUid != pkg.applicationInfo.uid) {
6832                    boolean recovered = false;
6833                    if (currentUid == 0) {
6834                        // The directory somehow became owned by root.  Wow.
6835                        // This is probably because the system was stopped while
6836                        // installd was in the middle of messing with its libs
6837                        // directory.  Ask installd to fix that.
6838                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6839                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6840                        if (ret >= 0) {
6841                            recovered = true;
6842                            String msg = "Package " + pkg.packageName
6843                                    + " unexpectedly changed to uid 0; recovered to " +
6844                                    + pkg.applicationInfo.uid;
6845                            reportSettingsProblem(Log.WARN, msg);
6846                        }
6847                    }
6848                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6849                            || (scanFlags&SCAN_BOOTING) != 0)) {
6850                        // If this is a system app, we can at least delete its
6851                        // current data so the application will still work.
6852                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6853                        if (ret >= 0) {
6854                            // TODO: Kill the processes first
6855                            // Old data gone!
6856                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6857                                    ? "System package " : "Third party package ";
6858                            String msg = prefix + pkg.packageName
6859                                    + " has changed from uid: "
6860                                    + currentUid + " to "
6861                                    + pkg.applicationInfo.uid + "; old data erased";
6862                            reportSettingsProblem(Log.WARN, msg);
6863                            recovered = true;
6864
6865                            // And now re-install the app.
6866                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6867                                    pkg.applicationInfo.seinfo);
6868                            if (ret == -1) {
6869                                // Ack should not happen!
6870                                msg = prefix + pkg.packageName
6871                                        + " could not have data directory re-created after delete.";
6872                                reportSettingsProblem(Log.WARN, msg);
6873                                throw new PackageManagerException(
6874                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6875                            }
6876                        }
6877                        if (!recovered) {
6878                            mHasSystemUidErrors = true;
6879                        }
6880                    } else if (!recovered) {
6881                        // If we allow this install to proceed, we will be broken.
6882                        // Abort, abort!
6883                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6884                                "scanPackageLI");
6885                    }
6886                    if (!recovered) {
6887                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6888                            + pkg.applicationInfo.uid + "/fs_"
6889                            + currentUid;
6890                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6891                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6892                        String msg = "Package " + pkg.packageName
6893                                + " has mismatched uid: "
6894                                + currentUid + " on disk, "
6895                                + pkg.applicationInfo.uid + " in settings";
6896                        // writer
6897                        synchronized (mPackages) {
6898                            mSettings.mReadMessages.append(msg);
6899                            mSettings.mReadMessages.append('\n');
6900                            uidError = true;
6901                            if (!pkgSetting.uidError) {
6902                                reportSettingsProblem(Log.ERROR, msg);
6903                            }
6904                        }
6905                    }
6906                }
6907                pkg.applicationInfo.dataDir = dataPath.getPath();
6908                if (mShouldRestoreconData) {
6909                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6910                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6911                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6912                }
6913            } else {
6914                if (DEBUG_PACKAGE_SCANNING) {
6915                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6916                        Log.v(TAG, "Want this data dir: " + dataPath);
6917                }
6918                //invoke installer to do the actual installation
6919                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6920                        pkg.applicationInfo.seinfo);
6921                if (ret < 0) {
6922                    // Error from installer
6923                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6924                            "Unable to create data dirs [errorCode=" + ret + "]");
6925                }
6926
6927                if (dataPath.exists()) {
6928                    pkg.applicationInfo.dataDir = dataPath.getPath();
6929                } else {
6930                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6931                    pkg.applicationInfo.dataDir = null;
6932                }
6933            }
6934
6935            pkgSetting.uidError = uidError;
6936        }
6937
6938        final String path = scanFile.getPath();
6939        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6940
6941        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6942            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6943
6944            // Some system apps still use directory structure for native libraries
6945            // in which case we might end up not detecting abi solely based on apk
6946            // structure. Try to detect abi based on directory structure.
6947            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6948                    pkg.applicationInfo.primaryCpuAbi == null) {
6949                setBundledAppAbisAndRoots(pkg, pkgSetting);
6950                setNativeLibraryPaths(pkg);
6951            }
6952
6953        } else {
6954            if ((scanFlags & SCAN_MOVE) != 0) {
6955                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6956                // but we already have this packages package info in the PackageSetting. We just
6957                // use that and derive the native library path based on the new codepath.
6958                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6959                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6960            }
6961
6962            // Set native library paths again. For moves, the path will be updated based on the
6963            // ABIs we've determined above. For non-moves, the path will be updated based on the
6964            // ABIs we determined during compilation, but the path will depend on the final
6965            // package path (after the rename away from the stage path).
6966            setNativeLibraryPaths(pkg);
6967        }
6968
6969        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6970        final int[] userIds = sUserManager.getUserIds();
6971        synchronized (mInstallLock) {
6972            // Make sure all user data directories are ready to roll; we're okay
6973            // if they already exist
6974            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6975                for (int userId : userIds) {
6976                    if (userId != 0) {
6977                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6978                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6979                                pkg.applicationInfo.seinfo);
6980                    }
6981                }
6982            }
6983
6984            // Create a native library symlink only if we have native libraries
6985            // and if the native libraries are 32 bit libraries. We do not provide
6986            // this symlink for 64 bit libraries.
6987            if (pkg.applicationInfo.primaryCpuAbi != null &&
6988                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6989                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6990                for (int userId : userIds) {
6991                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6992                            nativeLibPath, userId) < 0) {
6993                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6994                                "Failed linking native library dir (user=" + userId + ")");
6995                    }
6996                }
6997            }
6998        }
6999
7000        // This is a special case for the "system" package, where the ABI is
7001        // dictated by the zygote configuration (and init.rc). We should keep track
7002        // of this ABI so that we can deal with "normal" applications that run under
7003        // the same UID correctly.
7004        if (mPlatformPackage == pkg) {
7005            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7006                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7007        }
7008
7009        // If there's a mismatch between the abi-override in the package setting
7010        // and the abiOverride specified for the install. Warn about this because we
7011        // would've already compiled the app without taking the package setting into
7012        // account.
7013        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7014            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7015                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7016                        " for package: " + pkg.packageName);
7017            }
7018        }
7019
7020        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7021        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7022        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7023
7024        // Copy the derived override back to the parsed package, so that we can
7025        // update the package settings accordingly.
7026        pkg.cpuAbiOverride = cpuAbiOverride;
7027
7028        if (DEBUG_ABI_SELECTION) {
7029            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7030                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7031                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7032        }
7033
7034        // Push the derived path down into PackageSettings so we know what to
7035        // clean up at uninstall time.
7036        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7037
7038        if (DEBUG_ABI_SELECTION) {
7039            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7040                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7041                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7042        }
7043
7044        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7045            // We don't do this here during boot because we can do it all
7046            // at once after scanning all existing packages.
7047            //
7048            // We also do this *before* we perform dexopt on this package, so that
7049            // we can avoid redundant dexopts, and also to make sure we've got the
7050            // code and package path correct.
7051            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7052                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7053        }
7054
7055        if ((scanFlags & SCAN_NO_DEX) == 0) {
7056            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7057                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7058            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7059                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7060            }
7061        }
7062        if (mFactoryTest && pkg.requestedPermissions.contains(
7063                android.Manifest.permission.FACTORY_TEST)) {
7064            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7065        }
7066
7067        ArrayList<PackageParser.Package> clientLibPkgs = null;
7068
7069        // writer
7070        synchronized (mPackages) {
7071            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7072                // Only system apps can add new shared libraries.
7073                if (pkg.libraryNames != null) {
7074                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7075                        String name = pkg.libraryNames.get(i);
7076                        boolean allowed = false;
7077                        if (pkg.isUpdatedSystemApp()) {
7078                            // New library entries can only be added through the
7079                            // system image.  This is important to get rid of a lot
7080                            // of nasty edge cases: for example if we allowed a non-
7081                            // system update of the app to add a library, then uninstalling
7082                            // the update would make the library go away, and assumptions
7083                            // we made such as through app install filtering would now
7084                            // have allowed apps on the device which aren't compatible
7085                            // with it.  Better to just have the restriction here, be
7086                            // conservative, and create many fewer cases that can negatively
7087                            // impact the user experience.
7088                            final PackageSetting sysPs = mSettings
7089                                    .getDisabledSystemPkgLPr(pkg.packageName);
7090                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7091                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7092                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7093                                        allowed = true;
7094                                        allowed = true;
7095                                        break;
7096                                    }
7097                                }
7098                            }
7099                        } else {
7100                            allowed = true;
7101                        }
7102                        if (allowed) {
7103                            if (!mSharedLibraries.containsKey(name)) {
7104                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7105                            } else if (!name.equals(pkg.packageName)) {
7106                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7107                                        + name + " already exists; skipping");
7108                            }
7109                        } else {
7110                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7111                                    + name + " that is not declared on system image; skipping");
7112                        }
7113                    }
7114                    if ((scanFlags&SCAN_BOOTING) == 0) {
7115                        // If we are not booting, we need to update any applications
7116                        // that are clients of our shared library.  If we are booting,
7117                        // this will all be done once the scan is complete.
7118                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7119                    }
7120                }
7121            }
7122        }
7123
7124        // We also need to dexopt any apps that are dependent on this library.  Note that
7125        // if these fail, we should abort the install since installing the library will
7126        // result in some apps being broken.
7127        if (clientLibPkgs != null) {
7128            if ((scanFlags & SCAN_NO_DEX) == 0) {
7129                for (int i = 0; i < clientLibPkgs.size(); i++) {
7130                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7131                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7132                            null /* instruction sets */, forceDex,
7133                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7134                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7135                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7136                                "scanPackageLI failed to dexopt clientLibPkgs");
7137                    }
7138                }
7139            }
7140        }
7141
7142        // Request the ActivityManager to kill the process(only for existing packages)
7143        // so that we do not end up in a confused state while the user is still using the older
7144        // version of the application while the new one gets installed.
7145        if ((scanFlags & SCAN_REPLACING) != 0) {
7146            killApplication(pkg.applicationInfo.packageName,
7147                        pkg.applicationInfo.uid, "replace pkg");
7148        }
7149
7150        // Also need to kill any apps that are dependent on the library.
7151        if (clientLibPkgs != null) {
7152            for (int i=0; i<clientLibPkgs.size(); i++) {
7153                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7154                killApplication(clientPkg.applicationInfo.packageName,
7155                        clientPkg.applicationInfo.uid, "update lib");
7156            }
7157        }
7158
7159        // Make sure we're not adding any bogus keyset info
7160        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7161        ksms.assertScannedPackageValid(pkg);
7162
7163        // writer
7164        synchronized (mPackages) {
7165            // We don't expect installation to fail beyond this point
7166
7167            // Add the new setting to mSettings
7168            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7169            // Add the new setting to mPackages
7170            mPackages.put(pkg.applicationInfo.packageName, pkg);
7171            // Make sure we don't accidentally delete its data.
7172            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7173            while (iter.hasNext()) {
7174                PackageCleanItem item = iter.next();
7175                if (pkgName.equals(item.packageName)) {
7176                    iter.remove();
7177                }
7178            }
7179
7180            // Take care of first install / last update times.
7181            if (currentTime != 0) {
7182                if (pkgSetting.firstInstallTime == 0) {
7183                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7184                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7185                    pkgSetting.lastUpdateTime = currentTime;
7186                }
7187            } else if (pkgSetting.firstInstallTime == 0) {
7188                // We need *something*.  Take time time stamp of the file.
7189                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7190            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7191                if (scanFileTime != pkgSetting.timeStamp) {
7192                    // A package on the system image has changed; consider this
7193                    // to be an update.
7194                    pkgSetting.lastUpdateTime = scanFileTime;
7195                }
7196            }
7197
7198            // Add the package's KeySets to the global KeySetManagerService
7199            ksms.addScannedPackageLPw(pkg);
7200
7201            int N = pkg.providers.size();
7202            StringBuilder r = null;
7203            int i;
7204            for (i=0; i<N; i++) {
7205                PackageParser.Provider p = pkg.providers.get(i);
7206                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7207                        p.info.processName, pkg.applicationInfo.uid);
7208                mProviders.addProvider(p);
7209                p.syncable = p.info.isSyncable;
7210                if (p.info.authority != null) {
7211                    String names[] = p.info.authority.split(";");
7212                    p.info.authority = null;
7213                    for (int j = 0; j < names.length; j++) {
7214                        if (j == 1 && p.syncable) {
7215                            // We only want the first authority for a provider to possibly be
7216                            // syncable, so if we already added this provider using a different
7217                            // authority clear the syncable flag. We copy the provider before
7218                            // changing it because the mProviders object contains a reference
7219                            // to a provider that we don't want to change.
7220                            // Only do this for the second authority since the resulting provider
7221                            // object can be the same for all future authorities for this provider.
7222                            p = new PackageParser.Provider(p);
7223                            p.syncable = false;
7224                        }
7225                        if (!mProvidersByAuthority.containsKey(names[j])) {
7226                            mProvidersByAuthority.put(names[j], p);
7227                            if (p.info.authority == null) {
7228                                p.info.authority = names[j];
7229                            } else {
7230                                p.info.authority = p.info.authority + ";" + names[j];
7231                            }
7232                            if (DEBUG_PACKAGE_SCANNING) {
7233                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7234                                    Log.d(TAG, "Registered content provider: " + names[j]
7235                                            + ", className = " + p.info.name + ", isSyncable = "
7236                                            + p.info.isSyncable);
7237                            }
7238                        } else {
7239                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7240                            Slog.w(TAG, "Skipping provider name " + names[j] +
7241                                    " (in package " + pkg.applicationInfo.packageName +
7242                                    "): name already used by "
7243                                    + ((other != null && other.getComponentName() != null)
7244                                            ? other.getComponentName().getPackageName() : "?"));
7245                        }
7246                    }
7247                }
7248                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7249                    if (r == null) {
7250                        r = new StringBuilder(256);
7251                    } else {
7252                        r.append(' ');
7253                    }
7254                    r.append(p.info.name);
7255                }
7256            }
7257            if (r != null) {
7258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7259            }
7260
7261            N = pkg.services.size();
7262            r = null;
7263            for (i=0; i<N; i++) {
7264                PackageParser.Service s = pkg.services.get(i);
7265                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7266                        s.info.processName, pkg.applicationInfo.uid);
7267                mServices.addService(s);
7268                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7269                    if (r == null) {
7270                        r = new StringBuilder(256);
7271                    } else {
7272                        r.append(' ');
7273                    }
7274                    r.append(s.info.name);
7275                }
7276            }
7277            if (r != null) {
7278                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7279            }
7280
7281            N = pkg.receivers.size();
7282            r = null;
7283            for (i=0; i<N; i++) {
7284                PackageParser.Activity a = pkg.receivers.get(i);
7285                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7286                        a.info.processName, pkg.applicationInfo.uid);
7287                mReceivers.addActivity(a, "receiver");
7288                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7289                    if (r == null) {
7290                        r = new StringBuilder(256);
7291                    } else {
7292                        r.append(' ');
7293                    }
7294                    r.append(a.info.name);
7295                }
7296            }
7297            if (r != null) {
7298                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7299            }
7300
7301            N = pkg.activities.size();
7302            r = null;
7303            for (i=0; i<N; i++) {
7304                PackageParser.Activity a = pkg.activities.get(i);
7305                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7306                        a.info.processName, pkg.applicationInfo.uid);
7307                mActivities.addActivity(a, "activity");
7308                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7309                    if (r == null) {
7310                        r = new StringBuilder(256);
7311                    } else {
7312                        r.append(' ');
7313                    }
7314                    r.append(a.info.name);
7315                }
7316            }
7317            if (r != null) {
7318                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7319            }
7320
7321            N = pkg.permissionGroups.size();
7322            r = null;
7323            for (i=0; i<N; i++) {
7324                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7325                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7326                if (cur == null) {
7327                    mPermissionGroups.put(pg.info.name, pg);
7328                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7329                        if (r == null) {
7330                            r = new StringBuilder(256);
7331                        } else {
7332                            r.append(' ');
7333                        }
7334                        r.append(pg.info.name);
7335                    }
7336                } else {
7337                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7338                            + pg.info.packageName + " ignored: original from "
7339                            + cur.info.packageName);
7340                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7341                        if (r == null) {
7342                            r = new StringBuilder(256);
7343                        } else {
7344                            r.append(' ');
7345                        }
7346                        r.append("DUP:");
7347                        r.append(pg.info.name);
7348                    }
7349                }
7350            }
7351            if (r != null) {
7352                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7353            }
7354
7355            N = pkg.permissions.size();
7356            r = null;
7357            for (i=0; i<N; i++) {
7358                PackageParser.Permission p = pkg.permissions.get(i);
7359
7360                // Assume by default that we did not install this permission into the system.
7361                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7362
7363                // Now that permission groups have a special meaning, we ignore permission
7364                // groups for legacy apps to prevent unexpected behavior. In particular,
7365                // permissions for one app being granted to someone just becuase they happen
7366                // to be in a group defined by another app (before this had no implications).
7367                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7368                    p.group = mPermissionGroups.get(p.info.group);
7369                    // Warn for a permission in an unknown group.
7370                    if (p.info.group != null && p.group == null) {
7371                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7372                                + p.info.packageName + " in an unknown group " + p.info.group);
7373                    }
7374                }
7375
7376                ArrayMap<String, BasePermission> permissionMap =
7377                        p.tree ? mSettings.mPermissionTrees
7378                                : mSettings.mPermissions;
7379                BasePermission bp = permissionMap.get(p.info.name);
7380
7381                // Allow system apps to redefine non-system permissions
7382                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7383                    final boolean currentOwnerIsSystem = (bp.perm != null
7384                            && isSystemApp(bp.perm.owner));
7385                    if (isSystemApp(p.owner)) {
7386                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7387                            // It's a built-in permission and no owner, take ownership now
7388                            bp.packageSetting = pkgSetting;
7389                            bp.perm = p;
7390                            bp.uid = pkg.applicationInfo.uid;
7391                            bp.sourcePackage = p.info.packageName;
7392                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7393                        } else if (!currentOwnerIsSystem) {
7394                            String msg = "New decl " + p.owner + " of permission  "
7395                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7396                            reportSettingsProblem(Log.WARN, msg);
7397                            bp = null;
7398                        }
7399                    }
7400                }
7401
7402                if (bp == null) {
7403                    bp = new BasePermission(p.info.name, p.info.packageName,
7404                            BasePermission.TYPE_NORMAL);
7405                    permissionMap.put(p.info.name, bp);
7406                }
7407
7408                if (bp.perm == null) {
7409                    if (bp.sourcePackage == null
7410                            || bp.sourcePackage.equals(p.info.packageName)) {
7411                        BasePermission tree = findPermissionTreeLP(p.info.name);
7412                        if (tree == null
7413                                || tree.sourcePackage.equals(p.info.packageName)) {
7414                            bp.packageSetting = pkgSetting;
7415                            bp.perm = p;
7416                            bp.uid = pkg.applicationInfo.uid;
7417                            bp.sourcePackage = p.info.packageName;
7418                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7419                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7420                                if (r == null) {
7421                                    r = new StringBuilder(256);
7422                                } else {
7423                                    r.append(' ');
7424                                }
7425                                r.append(p.info.name);
7426                            }
7427                        } else {
7428                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7429                                    + p.info.packageName + " ignored: base tree "
7430                                    + tree.name + " is from package "
7431                                    + tree.sourcePackage);
7432                        }
7433                    } else {
7434                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7435                                + p.info.packageName + " ignored: original from "
7436                                + bp.sourcePackage);
7437                    }
7438                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7439                    if (r == null) {
7440                        r = new StringBuilder(256);
7441                    } else {
7442                        r.append(' ');
7443                    }
7444                    r.append("DUP:");
7445                    r.append(p.info.name);
7446                }
7447                if (bp.perm == p) {
7448                    bp.protectionLevel = p.info.protectionLevel;
7449                }
7450            }
7451
7452            if (r != null) {
7453                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7454            }
7455
7456            N = pkg.instrumentation.size();
7457            r = null;
7458            for (i=0; i<N; i++) {
7459                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7460                a.info.packageName = pkg.applicationInfo.packageName;
7461                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7462                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7463                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7464                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7465                a.info.dataDir = pkg.applicationInfo.dataDir;
7466
7467                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7468                // need other information about the application, like the ABI and what not ?
7469                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7470                mInstrumentation.put(a.getComponentName(), a);
7471                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7472                    if (r == null) {
7473                        r = new StringBuilder(256);
7474                    } else {
7475                        r.append(' ');
7476                    }
7477                    r.append(a.info.name);
7478                }
7479            }
7480            if (r != null) {
7481                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7482            }
7483
7484            if (pkg.protectedBroadcasts != null) {
7485                N = pkg.protectedBroadcasts.size();
7486                for (i=0; i<N; i++) {
7487                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7488                }
7489            }
7490
7491            pkgSetting.setTimeStamp(scanFileTime);
7492
7493            // Create idmap files for pairs of (packages, overlay packages).
7494            // Note: "android", ie framework-res.apk, is handled by native layers.
7495            if (pkg.mOverlayTarget != null) {
7496                // This is an overlay package.
7497                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7498                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7499                        mOverlays.put(pkg.mOverlayTarget,
7500                                new ArrayMap<String, PackageParser.Package>());
7501                    }
7502                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7503                    map.put(pkg.packageName, pkg);
7504                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7505                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7506                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7507                                "scanPackageLI failed to createIdmap");
7508                    }
7509                }
7510            } else if (mOverlays.containsKey(pkg.packageName) &&
7511                    !pkg.packageName.equals("android")) {
7512                // This is a regular package, with one or more known overlay packages.
7513                createIdmapsForPackageLI(pkg);
7514            }
7515        }
7516
7517        return pkg;
7518    }
7519
7520    /**
7521     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7522     * is derived purely on the basis of the contents of {@code scanFile} and
7523     * {@code cpuAbiOverride}.
7524     *
7525     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7526     */
7527    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7528                                 String cpuAbiOverride, boolean extractLibs)
7529            throws PackageManagerException {
7530        // TODO: We can probably be smarter about this stuff. For installed apps,
7531        // we can calculate this information at install time once and for all. For
7532        // system apps, we can probably assume that this information doesn't change
7533        // after the first boot scan. As things stand, we do lots of unnecessary work.
7534
7535        // Give ourselves some initial paths; we'll come back for another
7536        // pass once we've determined ABI below.
7537        setNativeLibraryPaths(pkg);
7538
7539        // We would never need to extract libs for forward-locked and external packages,
7540        // since the container service will do it for us. We shouldn't attempt to
7541        // extract libs from system app when it was not updated.
7542        if (pkg.isForwardLocked() || isExternal(pkg) ||
7543            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7544            extractLibs = false;
7545        }
7546
7547        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7548        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7549
7550        NativeLibraryHelper.Handle handle = null;
7551        try {
7552            handle = NativeLibraryHelper.Handle.create(scanFile);
7553            // TODO(multiArch): This can be null for apps that didn't go through the
7554            // usual installation process. We can calculate it again, like we
7555            // do during install time.
7556            //
7557            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7558            // unnecessary.
7559            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7560
7561            // Null out the abis so that they can be recalculated.
7562            pkg.applicationInfo.primaryCpuAbi = null;
7563            pkg.applicationInfo.secondaryCpuAbi = null;
7564            if (isMultiArch(pkg.applicationInfo)) {
7565                // Warn if we've set an abiOverride for multi-lib packages..
7566                // By definition, we need to copy both 32 and 64 bit libraries for
7567                // such packages.
7568                if (pkg.cpuAbiOverride != null
7569                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7570                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7571                }
7572
7573                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7574                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7575                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7576                    if (extractLibs) {
7577                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7578                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7579                                useIsaSpecificSubdirs);
7580                    } else {
7581                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7582                    }
7583                }
7584
7585                maybeThrowExceptionForMultiArchCopy(
7586                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7587
7588                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7589                    if (extractLibs) {
7590                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7591                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7592                                useIsaSpecificSubdirs);
7593                    } else {
7594                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7595                    }
7596                }
7597
7598                maybeThrowExceptionForMultiArchCopy(
7599                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7600
7601                if (abi64 >= 0) {
7602                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7603                }
7604
7605                if (abi32 >= 0) {
7606                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7607                    if (abi64 >= 0) {
7608                        pkg.applicationInfo.secondaryCpuAbi = abi;
7609                    } else {
7610                        pkg.applicationInfo.primaryCpuAbi = abi;
7611                    }
7612                }
7613            } else {
7614                String[] abiList = (cpuAbiOverride != null) ?
7615                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7616
7617                // Enable gross and lame hacks for apps that are built with old
7618                // SDK tools. We must scan their APKs for renderscript bitcode and
7619                // not launch them if it's present. Don't bother checking on devices
7620                // that don't have 64 bit support.
7621                boolean needsRenderScriptOverride = false;
7622                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7623                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7624                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7625                    needsRenderScriptOverride = true;
7626                }
7627
7628                final int copyRet;
7629                if (extractLibs) {
7630                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7631                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7632                } else {
7633                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7634                }
7635
7636                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7637                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7638                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7639                }
7640
7641                if (copyRet >= 0) {
7642                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7643                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7644                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7645                } else if (needsRenderScriptOverride) {
7646                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7647                }
7648            }
7649        } catch (IOException ioe) {
7650            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7651        } finally {
7652            IoUtils.closeQuietly(handle);
7653        }
7654
7655        // Now that we've calculated the ABIs and determined if it's an internal app,
7656        // we will go ahead and populate the nativeLibraryPath.
7657        setNativeLibraryPaths(pkg);
7658    }
7659
7660    /**
7661     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7662     * i.e, so that all packages can be run inside a single process if required.
7663     *
7664     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7665     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7666     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7667     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7668     * updating a package that belongs to a shared user.
7669     *
7670     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7671     * adds unnecessary complexity.
7672     */
7673    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7674            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7675        String requiredInstructionSet = null;
7676        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7677            requiredInstructionSet = VMRuntime.getInstructionSet(
7678                     scannedPackage.applicationInfo.primaryCpuAbi);
7679        }
7680
7681        PackageSetting requirer = null;
7682        for (PackageSetting ps : packagesForUser) {
7683            // If packagesForUser contains scannedPackage, we skip it. This will happen
7684            // when scannedPackage is an update of an existing package. Without this check,
7685            // we will never be able to change the ABI of any package belonging to a shared
7686            // user, even if it's compatible with other packages.
7687            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7688                if (ps.primaryCpuAbiString == null) {
7689                    continue;
7690                }
7691
7692                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7693                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7694                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7695                    // this but there's not much we can do.
7696                    String errorMessage = "Instruction set mismatch, "
7697                            + ((requirer == null) ? "[caller]" : requirer)
7698                            + " requires " + requiredInstructionSet + " whereas " + ps
7699                            + " requires " + instructionSet;
7700                    Slog.w(TAG, errorMessage);
7701                }
7702
7703                if (requiredInstructionSet == null) {
7704                    requiredInstructionSet = instructionSet;
7705                    requirer = ps;
7706                }
7707            }
7708        }
7709
7710        if (requiredInstructionSet != null) {
7711            String adjustedAbi;
7712            if (requirer != null) {
7713                // requirer != null implies that either scannedPackage was null or that scannedPackage
7714                // did not require an ABI, in which case we have to adjust scannedPackage to match
7715                // the ABI of the set (which is the same as requirer's ABI)
7716                adjustedAbi = requirer.primaryCpuAbiString;
7717                if (scannedPackage != null) {
7718                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7719                }
7720            } else {
7721                // requirer == null implies that we're updating all ABIs in the set to
7722                // match scannedPackage.
7723                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7724            }
7725
7726            for (PackageSetting ps : packagesForUser) {
7727                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7728                    if (ps.primaryCpuAbiString != null) {
7729                        continue;
7730                    }
7731
7732                    ps.primaryCpuAbiString = adjustedAbi;
7733                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7734                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7735                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7736
7737                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7738                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7739                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7740                            ps.primaryCpuAbiString = null;
7741                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7742                            return;
7743                        } else {
7744                            mInstaller.rmdex(ps.codePathString,
7745                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7746                        }
7747                    }
7748                }
7749            }
7750        }
7751    }
7752
7753    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7754        synchronized (mPackages) {
7755            mResolverReplaced = true;
7756            // Set up information for custom user intent resolution activity.
7757            mResolveActivity.applicationInfo = pkg.applicationInfo;
7758            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7759            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7760            mResolveActivity.processName = pkg.applicationInfo.packageName;
7761            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7762            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7763                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7764            mResolveActivity.theme = 0;
7765            mResolveActivity.exported = true;
7766            mResolveActivity.enabled = true;
7767            mResolveInfo.activityInfo = mResolveActivity;
7768            mResolveInfo.priority = 0;
7769            mResolveInfo.preferredOrder = 0;
7770            mResolveInfo.match = 0;
7771            mResolveComponentName = mCustomResolverComponentName;
7772            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7773                    mResolveComponentName);
7774        }
7775    }
7776
7777    private static String calculateBundledApkRoot(final String codePathString) {
7778        final File codePath = new File(codePathString);
7779        final File codeRoot;
7780        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7781            codeRoot = Environment.getRootDirectory();
7782        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7783            codeRoot = Environment.getOemDirectory();
7784        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7785            codeRoot = Environment.getVendorDirectory();
7786        } else {
7787            // Unrecognized code path; take its top real segment as the apk root:
7788            // e.g. /something/app/blah.apk => /something
7789            try {
7790                File f = codePath.getCanonicalFile();
7791                File parent = f.getParentFile();    // non-null because codePath is a file
7792                File tmp;
7793                while ((tmp = parent.getParentFile()) != null) {
7794                    f = parent;
7795                    parent = tmp;
7796                }
7797                codeRoot = f;
7798                Slog.w(TAG, "Unrecognized code path "
7799                        + codePath + " - using " + codeRoot);
7800            } catch (IOException e) {
7801                // Can't canonicalize the code path -- shenanigans?
7802                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7803                return Environment.getRootDirectory().getPath();
7804            }
7805        }
7806        return codeRoot.getPath();
7807    }
7808
7809    /**
7810     * Derive and set the location of native libraries for the given package,
7811     * which varies depending on where and how the package was installed.
7812     */
7813    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7814        final ApplicationInfo info = pkg.applicationInfo;
7815        final String codePath = pkg.codePath;
7816        final File codeFile = new File(codePath);
7817        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7818        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7819
7820        info.nativeLibraryRootDir = null;
7821        info.nativeLibraryRootRequiresIsa = false;
7822        info.nativeLibraryDir = null;
7823        info.secondaryNativeLibraryDir = null;
7824
7825        if (isApkFile(codeFile)) {
7826            // Monolithic install
7827            if (bundledApp) {
7828                // If "/system/lib64/apkname" exists, assume that is the per-package
7829                // native library directory to use; otherwise use "/system/lib/apkname".
7830                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7831                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7832                        getPrimaryInstructionSet(info));
7833
7834                // This is a bundled system app so choose the path based on the ABI.
7835                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7836                // is just the default path.
7837                final String apkName = deriveCodePathName(codePath);
7838                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7839                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7840                        apkName).getAbsolutePath();
7841
7842                if (info.secondaryCpuAbi != null) {
7843                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7844                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7845                            secondaryLibDir, apkName).getAbsolutePath();
7846                }
7847            } else if (asecApp) {
7848                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7849                        .getAbsolutePath();
7850            } else {
7851                final String apkName = deriveCodePathName(codePath);
7852                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7853                        .getAbsolutePath();
7854            }
7855
7856            info.nativeLibraryRootRequiresIsa = false;
7857            info.nativeLibraryDir = info.nativeLibraryRootDir;
7858        } else {
7859            // Cluster install
7860            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7861            info.nativeLibraryRootRequiresIsa = true;
7862
7863            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7864                    getPrimaryInstructionSet(info)).getAbsolutePath();
7865
7866            if (info.secondaryCpuAbi != null) {
7867                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7868                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7869            }
7870        }
7871    }
7872
7873    /**
7874     * Calculate the abis and roots for a bundled app. These can uniquely
7875     * be determined from the contents of the system partition, i.e whether
7876     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7877     * of this information, and instead assume that the system was built
7878     * sensibly.
7879     */
7880    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7881                                           PackageSetting pkgSetting) {
7882        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7883
7884        // If "/system/lib64/apkname" exists, assume that is the per-package
7885        // native library directory to use; otherwise use "/system/lib/apkname".
7886        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7887        setBundledAppAbi(pkg, apkRoot, apkName);
7888        // pkgSetting might be null during rescan following uninstall of updates
7889        // to a bundled app, so accommodate that possibility.  The settings in
7890        // that case will be established later from the parsed package.
7891        //
7892        // If the settings aren't null, sync them up with what we've just derived.
7893        // note that apkRoot isn't stored in the package settings.
7894        if (pkgSetting != null) {
7895            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7896            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7897        }
7898    }
7899
7900    /**
7901     * Deduces the ABI of a bundled app and sets the relevant fields on the
7902     * parsed pkg object.
7903     *
7904     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7905     *        under which system libraries are installed.
7906     * @param apkName the name of the installed package.
7907     */
7908    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7909        final File codeFile = new File(pkg.codePath);
7910
7911        final boolean has64BitLibs;
7912        final boolean has32BitLibs;
7913        if (isApkFile(codeFile)) {
7914            // Monolithic install
7915            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7916            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7917        } else {
7918            // Cluster install
7919            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7920            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7921                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7922                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7923                has64BitLibs = (new File(rootDir, isa)).exists();
7924            } else {
7925                has64BitLibs = false;
7926            }
7927            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7928                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7929                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7930                has32BitLibs = (new File(rootDir, isa)).exists();
7931            } else {
7932                has32BitLibs = false;
7933            }
7934        }
7935
7936        if (has64BitLibs && !has32BitLibs) {
7937            // The package has 64 bit libs, but not 32 bit libs. Its primary
7938            // ABI should be 64 bit. We can safely assume here that the bundled
7939            // native libraries correspond to the most preferred ABI in the list.
7940
7941            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7942            pkg.applicationInfo.secondaryCpuAbi = null;
7943        } else if (has32BitLibs && !has64BitLibs) {
7944            // The package has 32 bit libs but not 64 bit libs. Its primary
7945            // ABI should be 32 bit.
7946
7947            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7948            pkg.applicationInfo.secondaryCpuAbi = null;
7949        } else if (has32BitLibs && has64BitLibs) {
7950            // The application has both 64 and 32 bit bundled libraries. We check
7951            // here that the app declares multiArch support, and warn if it doesn't.
7952            //
7953            // We will be lenient here and record both ABIs. The primary will be the
7954            // ABI that's higher on the list, i.e, a device that's configured to prefer
7955            // 64 bit apps will see a 64 bit primary ABI,
7956
7957            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7958                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7959            }
7960
7961            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7962                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7963                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7964            } else {
7965                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7966                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7967            }
7968        } else {
7969            pkg.applicationInfo.primaryCpuAbi = null;
7970            pkg.applicationInfo.secondaryCpuAbi = null;
7971        }
7972    }
7973
7974    private void killApplication(String pkgName, int appId, String reason) {
7975        // Request the ActivityManager to kill the process(only for existing packages)
7976        // so that we do not end up in a confused state while the user is still using the older
7977        // version of the application while the new one gets installed.
7978        IActivityManager am = ActivityManagerNative.getDefault();
7979        if (am != null) {
7980            try {
7981                am.killApplicationWithAppId(pkgName, appId, reason);
7982            } catch (RemoteException e) {
7983            }
7984        }
7985    }
7986
7987    void removePackageLI(PackageSetting ps, boolean chatty) {
7988        if (DEBUG_INSTALL) {
7989            if (chatty)
7990                Log.d(TAG, "Removing package " + ps.name);
7991        }
7992
7993        // writer
7994        synchronized (mPackages) {
7995            mPackages.remove(ps.name);
7996            final PackageParser.Package pkg = ps.pkg;
7997            if (pkg != null) {
7998                cleanPackageDataStructuresLILPw(pkg, chatty);
7999            }
8000        }
8001    }
8002
8003    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8004        if (DEBUG_INSTALL) {
8005            if (chatty)
8006                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8007        }
8008
8009        // writer
8010        synchronized (mPackages) {
8011            mPackages.remove(pkg.applicationInfo.packageName);
8012            cleanPackageDataStructuresLILPw(pkg, chatty);
8013        }
8014    }
8015
8016    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8017        int N = pkg.providers.size();
8018        StringBuilder r = null;
8019        int i;
8020        for (i=0; i<N; i++) {
8021            PackageParser.Provider p = pkg.providers.get(i);
8022            mProviders.removeProvider(p);
8023            if (p.info.authority == null) {
8024
8025                /* There was another ContentProvider with this authority when
8026                 * this app was installed so this authority is null,
8027                 * Ignore it as we don't have to unregister the provider.
8028                 */
8029                continue;
8030            }
8031            String names[] = p.info.authority.split(";");
8032            for (int j = 0; j < names.length; j++) {
8033                if (mProvidersByAuthority.get(names[j]) == p) {
8034                    mProvidersByAuthority.remove(names[j]);
8035                    if (DEBUG_REMOVE) {
8036                        if (chatty)
8037                            Log.d(TAG, "Unregistered content provider: " + names[j]
8038                                    + ", className = " + p.info.name + ", isSyncable = "
8039                                    + p.info.isSyncable);
8040                    }
8041                }
8042            }
8043            if (DEBUG_REMOVE && chatty) {
8044                if (r == null) {
8045                    r = new StringBuilder(256);
8046                } else {
8047                    r.append(' ');
8048                }
8049                r.append(p.info.name);
8050            }
8051        }
8052        if (r != null) {
8053            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8054        }
8055
8056        N = pkg.services.size();
8057        r = null;
8058        for (i=0; i<N; i++) {
8059            PackageParser.Service s = pkg.services.get(i);
8060            mServices.removeService(s);
8061            if (chatty) {
8062                if (r == null) {
8063                    r = new StringBuilder(256);
8064                } else {
8065                    r.append(' ');
8066                }
8067                r.append(s.info.name);
8068            }
8069        }
8070        if (r != null) {
8071            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8072        }
8073
8074        N = pkg.receivers.size();
8075        r = null;
8076        for (i=0; i<N; i++) {
8077            PackageParser.Activity a = pkg.receivers.get(i);
8078            mReceivers.removeActivity(a, "receiver");
8079            if (DEBUG_REMOVE && chatty) {
8080                if (r == null) {
8081                    r = new StringBuilder(256);
8082                } else {
8083                    r.append(' ');
8084                }
8085                r.append(a.info.name);
8086            }
8087        }
8088        if (r != null) {
8089            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8090        }
8091
8092        N = pkg.activities.size();
8093        r = null;
8094        for (i=0; i<N; i++) {
8095            PackageParser.Activity a = pkg.activities.get(i);
8096            mActivities.removeActivity(a, "activity");
8097            if (DEBUG_REMOVE && chatty) {
8098                if (r == null) {
8099                    r = new StringBuilder(256);
8100                } else {
8101                    r.append(' ');
8102                }
8103                r.append(a.info.name);
8104            }
8105        }
8106        if (r != null) {
8107            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8108        }
8109
8110        N = pkg.permissions.size();
8111        r = null;
8112        for (i=0; i<N; i++) {
8113            PackageParser.Permission p = pkg.permissions.get(i);
8114            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8115            if (bp == null) {
8116                bp = mSettings.mPermissionTrees.get(p.info.name);
8117            }
8118            if (bp != null && bp.perm == p) {
8119                bp.perm = null;
8120                if (DEBUG_REMOVE && chatty) {
8121                    if (r == null) {
8122                        r = new StringBuilder(256);
8123                    } else {
8124                        r.append(' ');
8125                    }
8126                    r.append(p.info.name);
8127                }
8128            }
8129            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8130                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8131                if (appOpPerms != null) {
8132                    appOpPerms.remove(pkg.packageName);
8133                }
8134            }
8135        }
8136        if (r != null) {
8137            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8138        }
8139
8140        N = pkg.requestedPermissions.size();
8141        r = null;
8142        for (i=0; i<N; i++) {
8143            String perm = pkg.requestedPermissions.get(i);
8144            BasePermission bp = mSettings.mPermissions.get(perm);
8145            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8146                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8147                if (appOpPerms != null) {
8148                    appOpPerms.remove(pkg.packageName);
8149                    if (appOpPerms.isEmpty()) {
8150                        mAppOpPermissionPackages.remove(perm);
8151                    }
8152                }
8153            }
8154        }
8155        if (r != null) {
8156            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8157        }
8158
8159        N = pkg.instrumentation.size();
8160        r = null;
8161        for (i=0; i<N; i++) {
8162            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8163            mInstrumentation.remove(a.getComponentName());
8164            if (DEBUG_REMOVE && chatty) {
8165                if (r == null) {
8166                    r = new StringBuilder(256);
8167                } else {
8168                    r.append(' ');
8169                }
8170                r.append(a.info.name);
8171            }
8172        }
8173        if (r != null) {
8174            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8175        }
8176
8177        r = null;
8178        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8179            // Only system apps can hold shared libraries.
8180            if (pkg.libraryNames != null) {
8181                for (i=0; i<pkg.libraryNames.size(); i++) {
8182                    String name = pkg.libraryNames.get(i);
8183                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8184                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8185                        mSharedLibraries.remove(name);
8186                        if (DEBUG_REMOVE && chatty) {
8187                            if (r == null) {
8188                                r = new StringBuilder(256);
8189                            } else {
8190                                r.append(' ');
8191                            }
8192                            r.append(name);
8193                        }
8194                    }
8195                }
8196            }
8197        }
8198        if (r != null) {
8199            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8200        }
8201    }
8202
8203    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8204        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8205            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8206                return true;
8207            }
8208        }
8209        return false;
8210    }
8211
8212    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8213    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8214    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8215
8216    private void updatePermissionsLPw(String changingPkg,
8217            PackageParser.Package pkgInfo, int flags) {
8218        // Make sure there are no dangling permission trees.
8219        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8220        while (it.hasNext()) {
8221            final BasePermission bp = it.next();
8222            if (bp.packageSetting == null) {
8223                // We may not yet have parsed the package, so just see if
8224                // we still know about its settings.
8225                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8226            }
8227            if (bp.packageSetting == null) {
8228                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8229                        + " from package " + bp.sourcePackage);
8230                it.remove();
8231            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8232                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8233                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8234                            + " from package " + bp.sourcePackage);
8235                    flags |= UPDATE_PERMISSIONS_ALL;
8236                    it.remove();
8237                }
8238            }
8239        }
8240
8241        // Make sure all dynamic permissions have been assigned to a package,
8242        // and make sure there are no dangling permissions.
8243        it = mSettings.mPermissions.values().iterator();
8244        while (it.hasNext()) {
8245            final BasePermission bp = it.next();
8246            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8247                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8248                        + bp.name + " pkg=" + bp.sourcePackage
8249                        + " info=" + bp.pendingInfo);
8250                if (bp.packageSetting == null && bp.pendingInfo != null) {
8251                    final BasePermission tree = findPermissionTreeLP(bp.name);
8252                    if (tree != null && tree.perm != null) {
8253                        bp.packageSetting = tree.packageSetting;
8254                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8255                                new PermissionInfo(bp.pendingInfo));
8256                        bp.perm.info.packageName = tree.perm.info.packageName;
8257                        bp.perm.info.name = bp.name;
8258                        bp.uid = tree.uid;
8259                    }
8260                }
8261            }
8262            if (bp.packageSetting == null) {
8263                // We may not yet have parsed the package, so just see if
8264                // we still know about its settings.
8265                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8266            }
8267            if (bp.packageSetting == null) {
8268                Slog.w(TAG, "Removing dangling permission: " + bp.name
8269                        + " from package " + bp.sourcePackage);
8270                it.remove();
8271            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8272                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8273                    Slog.i(TAG, "Removing old permission: " + bp.name
8274                            + " from package " + bp.sourcePackage);
8275                    flags |= UPDATE_PERMISSIONS_ALL;
8276                    it.remove();
8277                }
8278            }
8279        }
8280
8281        // Now update the permissions for all packages, in particular
8282        // replace the granted permissions of the system packages.
8283        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8284            for (PackageParser.Package pkg : mPackages.values()) {
8285                if (pkg != pkgInfo) {
8286                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8287                            changingPkg);
8288                }
8289            }
8290        }
8291
8292        if (pkgInfo != null) {
8293            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8294        }
8295    }
8296
8297    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8298            String packageOfInterest) {
8299        // IMPORTANT: There are two types of permissions: install and runtime.
8300        // Install time permissions are granted when the app is installed to
8301        // all device users and users added in the future. Runtime permissions
8302        // are granted at runtime explicitly to specific users. Normal and signature
8303        // protected permissions are install time permissions. Dangerous permissions
8304        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8305        // otherwise they are runtime permissions. This function does not manage
8306        // runtime permissions except for the case an app targeting Lollipop MR1
8307        // being upgraded to target a newer SDK, in which case dangerous permissions
8308        // are transformed from install time to runtime ones.
8309
8310        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8311        if (ps == null) {
8312            return;
8313        }
8314
8315        PermissionsState permissionsState = ps.getPermissionsState();
8316        PermissionsState origPermissions = permissionsState;
8317
8318        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8319
8320        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8321
8322        boolean changedInstallPermission = false;
8323
8324        if (replace) {
8325            ps.installPermissionsFixed = false;
8326            if (!ps.isSharedUser()) {
8327                origPermissions = new PermissionsState(permissionsState);
8328                permissionsState.reset();
8329            }
8330        }
8331
8332        permissionsState.setGlobalGids(mGlobalGids);
8333
8334        final int N = pkg.requestedPermissions.size();
8335        for (int i=0; i<N; i++) {
8336            final String name = pkg.requestedPermissions.get(i);
8337            final BasePermission bp = mSettings.mPermissions.get(name);
8338
8339            if (DEBUG_INSTALL) {
8340                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8341            }
8342
8343            if (bp == null || bp.packageSetting == null) {
8344                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8345                    Slog.w(TAG, "Unknown permission " + name
8346                            + " in package " + pkg.packageName);
8347                }
8348                continue;
8349            }
8350
8351            final String perm = bp.name;
8352            boolean allowedSig = false;
8353            int grant = GRANT_DENIED;
8354
8355            // Keep track of app op permissions.
8356            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8357                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8358                if (pkgs == null) {
8359                    pkgs = new ArraySet<>();
8360                    mAppOpPermissionPackages.put(bp.name, pkgs);
8361                }
8362                pkgs.add(pkg.packageName);
8363            }
8364
8365            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8366            switch (level) {
8367                case PermissionInfo.PROTECTION_NORMAL: {
8368                    // For all apps normal permissions are install time ones.
8369                    grant = GRANT_INSTALL;
8370                } break;
8371
8372                case PermissionInfo.PROTECTION_DANGEROUS: {
8373                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8374                        // For legacy apps dangerous permissions are install time ones.
8375                        grant = GRANT_INSTALL_LEGACY;
8376                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8377                        // For legacy apps that became modern, install becomes runtime.
8378                        grant = GRANT_UPGRADE;
8379                    } else {
8380                        // For modern apps keep runtime permissions unchanged.
8381                        grant = GRANT_RUNTIME;
8382                    }
8383                } break;
8384
8385                case PermissionInfo.PROTECTION_SIGNATURE: {
8386                    // For all apps signature permissions are install time ones.
8387                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8388                    if (allowedSig) {
8389                        grant = GRANT_INSTALL;
8390                    }
8391                } break;
8392            }
8393
8394            if (DEBUG_INSTALL) {
8395                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8396            }
8397
8398            if (grant != GRANT_DENIED) {
8399                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8400                    // If this is an existing, non-system package, then
8401                    // we can't add any new permissions to it.
8402                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8403                        // Except...  if this is a permission that was added
8404                        // to the platform (note: need to only do this when
8405                        // updating the platform).
8406                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8407                            grant = GRANT_DENIED;
8408                        }
8409                    }
8410                }
8411
8412                switch (grant) {
8413                    case GRANT_INSTALL: {
8414                        // Revoke this as runtime permission to handle the case of
8415                        // a runtime permission being downgraded to an install one.
8416                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8417                            if (origPermissions.getRuntimePermissionState(
8418                                    bp.name, userId) != null) {
8419                                // Revoke the runtime permission and clear the flags.
8420                                origPermissions.revokeRuntimePermission(bp, userId);
8421                                origPermissions.updatePermissionFlags(bp, userId,
8422                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8423                                // If we revoked a permission permission, we have to write.
8424                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8425                                        changedRuntimePermissionUserIds, userId);
8426                            }
8427                        }
8428                        // Grant an install permission.
8429                        if (permissionsState.grantInstallPermission(bp) !=
8430                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8431                            changedInstallPermission = true;
8432                        }
8433                    } break;
8434
8435                    case GRANT_INSTALL_LEGACY: {
8436                        // Grant an install permission.
8437                        if (permissionsState.grantInstallPermission(bp) !=
8438                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8439                            changedInstallPermission = true;
8440                        }
8441                    } break;
8442
8443                    case GRANT_RUNTIME: {
8444                        // Grant previously granted runtime permissions.
8445                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8446                            PermissionState permissionState = origPermissions
8447                                    .getRuntimePermissionState(bp.name, userId);
8448                            final int flags = permissionState != null
8449                                    ? permissionState.getFlags() : 0;
8450                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8451                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8452                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8453                                    // If we cannot put the permission as it was, we have to write.
8454                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8455                                            changedRuntimePermissionUserIds, userId);
8456                                }
8457                            }
8458                            // Propagate the permission flags.
8459                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8460                        }
8461                    } break;
8462
8463                    case GRANT_UPGRADE: {
8464                        // Grant runtime permissions for a previously held install permission.
8465                        PermissionState permissionState = origPermissions
8466                                .getInstallPermissionState(bp.name);
8467                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8468
8469                        if (origPermissions.revokeInstallPermission(bp)
8470                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8471                            // We will be transferring the permission flags, so clear them.
8472                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8473                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8474                            changedInstallPermission = true;
8475                        }
8476
8477                        // If the permission is not to be promoted to runtime we ignore it and
8478                        // also its other flags as they are not applicable to install permissions.
8479                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8480                            for (int userId : currentUserIds) {
8481                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8482                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8483                                    // Transfer the permission flags.
8484                                    permissionsState.updatePermissionFlags(bp, userId,
8485                                            flags, flags);
8486                                    // If we granted the permission, we have to write.
8487                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8488                                            changedRuntimePermissionUserIds, userId);
8489                                }
8490                            }
8491                        }
8492                    } break;
8493
8494                    default: {
8495                        if (packageOfInterest == null
8496                                || packageOfInterest.equals(pkg.packageName)) {
8497                            Slog.w(TAG, "Not granting permission " + perm
8498                                    + " to package " + pkg.packageName
8499                                    + " because it was previously installed without");
8500                        }
8501                    } break;
8502                }
8503            } else {
8504                if (permissionsState.revokeInstallPermission(bp) !=
8505                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8506                    // Also drop the permission flags.
8507                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8508                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8509                    changedInstallPermission = true;
8510                    Slog.i(TAG, "Un-granting permission " + perm
8511                            + " from package " + pkg.packageName
8512                            + " (protectionLevel=" + bp.protectionLevel
8513                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8514                            + ")");
8515                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8516                    // Don't print warning for app op permissions, since it is fine for them
8517                    // not to be granted, there is a UI for the user to decide.
8518                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8519                        Slog.w(TAG, "Not granting permission " + perm
8520                                + " to package " + pkg.packageName
8521                                + " (protectionLevel=" + bp.protectionLevel
8522                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8523                                + ")");
8524                    }
8525                }
8526            }
8527        }
8528
8529        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8530                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8531            // This is the first that we have heard about this package, so the
8532            // permissions we have now selected are fixed until explicitly
8533            // changed.
8534            ps.installPermissionsFixed = true;
8535        }
8536
8537        // Persist the runtime permissions state for users with changes.
8538        for (int userId : changedRuntimePermissionUserIds) {
8539            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8540        }
8541    }
8542
8543    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8544        boolean allowed = false;
8545        final int NP = PackageParser.NEW_PERMISSIONS.length;
8546        for (int ip=0; ip<NP; ip++) {
8547            final PackageParser.NewPermissionInfo npi
8548                    = PackageParser.NEW_PERMISSIONS[ip];
8549            if (npi.name.equals(perm)
8550                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8551                allowed = true;
8552                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8553                        + pkg.packageName);
8554                break;
8555            }
8556        }
8557        return allowed;
8558    }
8559
8560    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8561            BasePermission bp, PermissionsState origPermissions) {
8562        boolean allowed;
8563        allowed = (compareSignatures(
8564                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8565                        == PackageManager.SIGNATURE_MATCH)
8566                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8567                        == PackageManager.SIGNATURE_MATCH);
8568        if (!allowed && (bp.protectionLevel
8569                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8570            if (isSystemApp(pkg)) {
8571                // For updated system applications, a system permission
8572                // is granted only if it had been defined by the original application.
8573                if (pkg.isUpdatedSystemApp()) {
8574                    final PackageSetting sysPs = mSettings
8575                            .getDisabledSystemPkgLPr(pkg.packageName);
8576                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8577                        // If the original was granted this permission, we take
8578                        // that grant decision as read and propagate it to the
8579                        // update.
8580                        if (sysPs.isPrivileged()) {
8581                            allowed = true;
8582                        }
8583                    } else {
8584                        // The system apk may have been updated with an older
8585                        // version of the one on the data partition, but which
8586                        // granted a new system permission that it didn't have
8587                        // before.  In this case we do want to allow the app to
8588                        // now get the new permission if the ancestral apk is
8589                        // privileged to get it.
8590                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8591                            for (int j=0;
8592                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8593                                if (perm.equals(
8594                                        sysPs.pkg.requestedPermissions.get(j))) {
8595                                    allowed = true;
8596                                    break;
8597                                }
8598                            }
8599                        }
8600                    }
8601                } else {
8602                    allowed = isPrivilegedApp(pkg);
8603                }
8604            }
8605        }
8606        if (!allowed) {
8607            if (!allowed && (bp.protectionLevel
8608                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8609                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8610                // If this was a previously normal/dangerous permission that got moved
8611                // to a system permission as part of the runtime permission redesign, then
8612                // we still want to blindly grant it to old apps.
8613                allowed = true;
8614            }
8615            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8616                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8617                // If this permission is to be granted to the system installer and
8618                // this app is an installer, then it gets the permission.
8619                allowed = true;
8620            }
8621            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8622                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8623                // If this permission is to be granted to the system verifier and
8624                // this app is a verifier, then it gets the permission.
8625                allowed = true;
8626            }
8627            if (!allowed && (bp.protectionLevel
8628                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8629                    && isSystemApp(pkg)) {
8630                // Any pre-installed system app is allowed to get this permission.
8631                allowed = true;
8632            }
8633            if (!allowed && (bp.protectionLevel
8634                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8635                // For development permissions, a development permission
8636                // is granted only if it was already granted.
8637                allowed = origPermissions.hasInstallPermission(perm);
8638            }
8639        }
8640        return allowed;
8641    }
8642
8643    final class ActivityIntentResolver
8644            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8645        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8646                boolean defaultOnly, int userId) {
8647            if (!sUserManager.exists(userId)) return null;
8648            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8649            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8650        }
8651
8652        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8653                int userId) {
8654            if (!sUserManager.exists(userId)) return null;
8655            mFlags = flags;
8656            return super.queryIntent(intent, resolvedType,
8657                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8658        }
8659
8660        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8661                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8662            if (!sUserManager.exists(userId)) return null;
8663            if (packageActivities == null) {
8664                return null;
8665            }
8666            mFlags = flags;
8667            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8668            final int N = packageActivities.size();
8669            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8670                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8671
8672            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8673            for (int i = 0; i < N; ++i) {
8674                intentFilters = packageActivities.get(i).intents;
8675                if (intentFilters != null && intentFilters.size() > 0) {
8676                    PackageParser.ActivityIntentInfo[] array =
8677                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8678                    intentFilters.toArray(array);
8679                    listCut.add(array);
8680                }
8681            }
8682            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8683        }
8684
8685        public final void addActivity(PackageParser.Activity a, String type) {
8686            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8687            mActivities.put(a.getComponentName(), a);
8688            if (DEBUG_SHOW_INFO)
8689                Log.v(
8690                TAG, "  " + type + " " +
8691                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8692            if (DEBUG_SHOW_INFO)
8693                Log.v(TAG, "    Class=" + a.info.name);
8694            final int NI = a.intents.size();
8695            for (int j=0; j<NI; j++) {
8696                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8697                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8698                    intent.setPriority(0);
8699                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8700                            + a.className + " with priority > 0, forcing to 0");
8701                }
8702                if (DEBUG_SHOW_INFO) {
8703                    Log.v(TAG, "    IntentFilter:");
8704                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8705                }
8706                if (!intent.debugCheck()) {
8707                    Log.w(TAG, "==> For Activity " + a.info.name);
8708                }
8709                addFilter(intent);
8710            }
8711        }
8712
8713        public final void removeActivity(PackageParser.Activity a, String type) {
8714            mActivities.remove(a.getComponentName());
8715            if (DEBUG_SHOW_INFO) {
8716                Log.v(TAG, "  " + type + " "
8717                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8718                                : a.info.name) + ":");
8719                Log.v(TAG, "    Class=" + a.info.name);
8720            }
8721            final int NI = a.intents.size();
8722            for (int j=0; j<NI; j++) {
8723                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8724                if (DEBUG_SHOW_INFO) {
8725                    Log.v(TAG, "    IntentFilter:");
8726                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8727                }
8728                removeFilter(intent);
8729            }
8730        }
8731
8732        @Override
8733        protected boolean allowFilterResult(
8734                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8735            ActivityInfo filterAi = filter.activity.info;
8736            for (int i=dest.size()-1; i>=0; i--) {
8737                ActivityInfo destAi = dest.get(i).activityInfo;
8738                if (destAi.name == filterAi.name
8739                        && destAi.packageName == filterAi.packageName) {
8740                    return false;
8741                }
8742            }
8743            return true;
8744        }
8745
8746        @Override
8747        protected ActivityIntentInfo[] newArray(int size) {
8748            return new ActivityIntentInfo[size];
8749        }
8750
8751        @Override
8752        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8753            if (!sUserManager.exists(userId)) return true;
8754            PackageParser.Package p = filter.activity.owner;
8755            if (p != null) {
8756                PackageSetting ps = (PackageSetting)p.mExtras;
8757                if (ps != null) {
8758                    // System apps are never considered stopped for purposes of
8759                    // filtering, because there may be no way for the user to
8760                    // actually re-launch them.
8761                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8762                            && ps.getStopped(userId);
8763                }
8764            }
8765            return false;
8766        }
8767
8768        @Override
8769        protected boolean isPackageForFilter(String packageName,
8770                PackageParser.ActivityIntentInfo info) {
8771            return packageName.equals(info.activity.owner.packageName);
8772        }
8773
8774        @Override
8775        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8776                int match, int userId) {
8777            if (!sUserManager.exists(userId)) return null;
8778            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8779                return null;
8780            }
8781            final PackageParser.Activity activity = info.activity;
8782            if (mSafeMode && (activity.info.applicationInfo.flags
8783                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8784                return null;
8785            }
8786            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8787            if (ps == null) {
8788                return null;
8789            }
8790            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8791                    ps.readUserState(userId), userId);
8792            if (ai == null) {
8793                return null;
8794            }
8795            final ResolveInfo res = new ResolveInfo();
8796            res.activityInfo = ai;
8797            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8798                res.filter = info;
8799            }
8800            if (info != null) {
8801                res.handleAllWebDataURI = info.handleAllWebDataURI();
8802            }
8803            res.priority = info.getPriority();
8804            res.preferredOrder = activity.owner.mPreferredOrder;
8805            //System.out.println("Result: " + res.activityInfo.className +
8806            //                   " = " + res.priority);
8807            res.match = match;
8808            res.isDefault = info.hasDefault;
8809            res.labelRes = info.labelRes;
8810            res.nonLocalizedLabel = info.nonLocalizedLabel;
8811            if (userNeedsBadging(userId)) {
8812                res.noResourceId = true;
8813            } else {
8814                res.icon = info.icon;
8815            }
8816            res.iconResourceId = info.icon;
8817            res.system = res.activityInfo.applicationInfo.isSystemApp();
8818            return res;
8819        }
8820
8821        @Override
8822        protected void sortResults(List<ResolveInfo> results) {
8823            Collections.sort(results, mResolvePrioritySorter);
8824        }
8825
8826        @Override
8827        protected void dumpFilter(PrintWriter out, String prefix,
8828                PackageParser.ActivityIntentInfo filter) {
8829            out.print(prefix); out.print(
8830                    Integer.toHexString(System.identityHashCode(filter.activity)));
8831                    out.print(' ');
8832                    filter.activity.printComponentShortName(out);
8833                    out.print(" filter ");
8834                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8835        }
8836
8837        @Override
8838        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8839            return filter.activity;
8840        }
8841
8842        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8843            PackageParser.Activity activity = (PackageParser.Activity)label;
8844            out.print(prefix); out.print(
8845                    Integer.toHexString(System.identityHashCode(activity)));
8846                    out.print(' ');
8847                    activity.printComponentShortName(out);
8848            if (count > 1) {
8849                out.print(" ("); out.print(count); out.print(" filters)");
8850            }
8851            out.println();
8852        }
8853
8854//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8855//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8856//            final List<ResolveInfo> retList = Lists.newArrayList();
8857//            while (i.hasNext()) {
8858//                final ResolveInfo resolveInfo = i.next();
8859//                if (isEnabledLP(resolveInfo.activityInfo)) {
8860//                    retList.add(resolveInfo);
8861//                }
8862//            }
8863//            return retList;
8864//        }
8865
8866        // Keys are String (activity class name), values are Activity.
8867        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8868                = new ArrayMap<ComponentName, PackageParser.Activity>();
8869        private int mFlags;
8870    }
8871
8872    private final class ServiceIntentResolver
8873            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8874        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8875                boolean defaultOnly, int userId) {
8876            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8877            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8878        }
8879
8880        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8881                int userId) {
8882            if (!sUserManager.exists(userId)) return null;
8883            mFlags = flags;
8884            return super.queryIntent(intent, resolvedType,
8885                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8886        }
8887
8888        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8889                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8890            if (!sUserManager.exists(userId)) return null;
8891            if (packageServices == null) {
8892                return null;
8893            }
8894            mFlags = flags;
8895            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8896            final int N = packageServices.size();
8897            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8898                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8899
8900            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8901            for (int i = 0; i < N; ++i) {
8902                intentFilters = packageServices.get(i).intents;
8903                if (intentFilters != null && intentFilters.size() > 0) {
8904                    PackageParser.ServiceIntentInfo[] array =
8905                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8906                    intentFilters.toArray(array);
8907                    listCut.add(array);
8908                }
8909            }
8910            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8911        }
8912
8913        public final void addService(PackageParser.Service s) {
8914            mServices.put(s.getComponentName(), s);
8915            if (DEBUG_SHOW_INFO) {
8916                Log.v(TAG, "  "
8917                        + (s.info.nonLocalizedLabel != null
8918                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8919                Log.v(TAG, "    Class=" + s.info.name);
8920            }
8921            final int NI = s.intents.size();
8922            int j;
8923            for (j=0; j<NI; j++) {
8924                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8925                if (DEBUG_SHOW_INFO) {
8926                    Log.v(TAG, "    IntentFilter:");
8927                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8928                }
8929                if (!intent.debugCheck()) {
8930                    Log.w(TAG, "==> For Service " + s.info.name);
8931                }
8932                addFilter(intent);
8933            }
8934        }
8935
8936        public final void removeService(PackageParser.Service s) {
8937            mServices.remove(s.getComponentName());
8938            if (DEBUG_SHOW_INFO) {
8939                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8940                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8941                Log.v(TAG, "    Class=" + s.info.name);
8942            }
8943            final int NI = s.intents.size();
8944            int j;
8945            for (j=0; j<NI; j++) {
8946                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8947                if (DEBUG_SHOW_INFO) {
8948                    Log.v(TAG, "    IntentFilter:");
8949                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8950                }
8951                removeFilter(intent);
8952            }
8953        }
8954
8955        @Override
8956        protected boolean allowFilterResult(
8957                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8958            ServiceInfo filterSi = filter.service.info;
8959            for (int i=dest.size()-1; i>=0; i--) {
8960                ServiceInfo destAi = dest.get(i).serviceInfo;
8961                if (destAi.name == filterSi.name
8962                        && destAi.packageName == filterSi.packageName) {
8963                    return false;
8964                }
8965            }
8966            return true;
8967        }
8968
8969        @Override
8970        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8971            return new PackageParser.ServiceIntentInfo[size];
8972        }
8973
8974        @Override
8975        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8976            if (!sUserManager.exists(userId)) return true;
8977            PackageParser.Package p = filter.service.owner;
8978            if (p != null) {
8979                PackageSetting ps = (PackageSetting)p.mExtras;
8980                if (ps != null) {
8981                    // System apps are never considered stopped for purposes of
8982                    // filtering, because there may be no way for the user to
8983                    // actually re-launch them.
8984                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8985                            && ps.getStopped(userId);
8986                }
8987            }
8988            return false;
8989        }
8990
8991        @Override
8992        protected boolean isPackageForFilter(String packageName,
8993                PackageParser.ServiceIntentInfo info) {
8994            return packageName.equals(info.service.owner.packageName);
8995        }
8996
8997        @Override
8998        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8999                int match, int userId) {
9000            if (!sUserManager.exists(userId)) return null;
9001            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9002            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9003                return null;
9004            }
9005            final PackageParser.Service service = info.service;
9006            if (mSafeMode && (service.info.applicationInfo.flags
9007                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9008                return null;
9009            }
9010            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9011            if (ps == null) {
9012                return null;
9013            }
9014            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9015                    ps.readUserState(userId), userId);
9016            if (si == null) {
9017                return null;
9018            }
9019            final ResolveInfo res = new ResolveInfo();
9020            res.serviceInfo = si;
9021            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9022                res.filter = filter;
9023            }
9024            res.priority = info.getPriority();
9025            res.preferredOrder = service.owner.mPreferredOrder;
9026            res.match = match;
9027            res.isDefault = info.hasDefault;
9028            res.labelRes = info.labelRes;
9029            res.nonLocalizedLabel = info.nonLocalizedLabel;
9030            res.icon = info.icon;
9031            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9032            return res;
9033        }
9034
9035        @Override
9036        protected void sortResults(List<ResolveInfo> results) {
9037            Collections.sort(results, mResolvePrioritySorter);
9038        }
9039
9040        @Override
9041        protected void dumpFilter(PrintWriter out, String prefix,
9042                PackageParser.ServiceIntentInfo filter) {
9043            out.print(prefix); out.print(
9044                    Integer.toHexString(System.identityHashCode(filter.service)));
9045                    out.print(' ');
9046                    filter.service.printComponentShortName(out);
9047                    out.print(" filter ");
9048                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9049        }
9050
9051        @Override
9052        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9053            return filter.service;
9054        }
9055
9056        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9057            PackageParser.Service service = (PackageParser.Service)label;
9058            out.print(prefix); out.print(
9059                    Integer.toHexString(System.identityHashCode(service)));
9060                    out.print(' ');
9061                    service.printComponentShortName(out);
9062            if (count > 1) {
9063                out.print(" ("); out.print(count); out.print(" filters)");
9064            }
9065            out.println();
9066        }
9067
9068//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9069//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9070//            final List<ResolveInfo> retList = Lists.newArrayList();
9071//            while (i.hasNext()) {
9072//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9073//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9074//                    retList.add(resolveInfo);
9075//                }
9076//            }
9077//            return retList;
9078//        }
9079
9080        // Keys are String (activity class name), values are Activity.
9081        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9082                = new ArrayMap<ComponentName, PackageParser.Service>();
9083        private int mFlags;
9084    };
9085
9086    private final class ProviderIntentResolver
9087            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9088        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9089                boolean defaultOnly, int userId) {
9090            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9091            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9092        }
9093
9094        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9095                int userId) {
9096            if (!sUserManager.exists(userId))
9097                return null;
9098            mFlags = flags;
9099            return super.queryIntent(intent, resolvedType,
9100                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9101        }
9102
9103        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9104                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9105            if (!sUserManager.exists(userId))
9106                return null;
9107            if (packageProviders == null) {
9108                return null;
9109            }
9110            mFlags = flags;
9111            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9112            final int N = packageProviders.size();
9113            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9114                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9115
9116            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9117            for (int i = 0; i < N; ++i) {
9118                intentFilters = packageProviders.get(i).intents;
9119                if (intentFilters != null && intentFilters.size() > 0) {
9120                    PackageParser.ProviderIntentInfo[] array =
9121                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9122                    intentFilters.toArray(array);
9123                    listCut.add(array);
9124                }
9125            }
9126            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9127        }
9128
9129        public final void addProvider(PackageParser.Provider p) {
9130            if (mProviders.containsKey(p.getComponentName())) {
9131                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9132                return;
9133            }
9134
9135            mProviders.put(p.getComponentName(), p);
9136            if (DEBUG_SHOW_INFO) {
9137                Log.v(TAG, "  "
9138                        + (p.info.nonLocalizedLabel != null
9139                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9140                Log.v(TAG, "    Class=" + p.info.name);
9141            }
9142            final int NI = p.intents.size();
9143            int j;
9144            for (j = 0; j < NI; j++) {
9145                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9146                if (DEBUG_SHOW_INFO) {
9147                    Log.v(TAG, "    IntentFilter:");
9148                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9149                }
9150                if (!intent.debugCheck()) {
9151                    Log.w(TAG, "==> For Provider " + p.info.name);
9152                }
9153                addFilter(intent);
9154            }
9155        }
9156
9157        public final void removeProvider(PackageParser.Provider p) {
9158            mProviders.remove(p.getComponentName());
9159            if (DEBUG_SHOW_INFO) {
9160                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9161                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9162                Log.v(TAG, "    Class=" + p.info.name);
9163            }
9164            final int NI = p.intents.size();
9165            int j;
9166            for (j = 0; j < NI; j++) {
9167                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9168                if (DEBUG_SHOW_INFO) {
9169                    Log.v(TAG, "    IntentFilter:");
9170                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9171                }
9172                removeFilter(intent);
9173            }
9174        }
9175
9176        @Override
9177        protected boolean allowFilterResult(
9178                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9179            ProviderInfo filterPi = filter.provider.info;
9180            for (int i = dest.size() - 1; i >= 0; i--) {
9181                ProviderInfo destPi = dest.get(i).providerInfo;
9182                if (destPi.name == filterPi.name
9183                        && destPi.packageName == filterPi.packageName) {
9184                    return false;
9185                }
9186            }
9187            return true;
9188        }
9189
9190        @Override
9191        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9192            return new PackageParser.ProviderIntentInfo[size];
9193        }
9194
9195        @Override
9196        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9197            if (!sUserManager.exists(userId))
9198                return true;
9199            PackageParser.Package p = filter.provider.owner;
9200            if (p != null) {
9201                PackageSetting ps = (PackageSetting) p.mExtras;
9202                if (ps != null) {
9203                    // System apps are never considered stopped for purposes of
9204                    // filtering, because there may be no way for the user to
9205                    // actually re-launch them.
9206                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9207                            && ps.getStopped(userId);
9208                }
9209            }
9210            return false;
9211        }
9212
9213        @Override
9214        protected boolean isPackageForFilter(String packageName,
9215                PackageParser.ProviderIntentInfo info) {
9216            return packageName.equals(info.provider.owner.packageName);
9217        }
9218
9219        @Override
9220        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9221                int match, int userId) {
9222            if (!sUserManager.exists(userId))
9223                return null;
9224            final PackageParser.ProviderIntentInfo info = filter;
9225            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9226                return null;
9227            }
9228            final PackageParser.Provider provider = info.provider;
9229            if (mSafeMode && (provider.info.applicationInfo.flags
9230                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9231                return null;
9232            }
9233            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9234            if (ps == null) {
9235                return null;
9236            }
9237            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9238                    ps.readUserState(userId), userId);
9239            if (pi == null) {
9240                return null;
9241            }
9242            final ResolveInfo res = new ResolveInfo();
9243            res.providerInfo = pi;
9244            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9245                res.filter = filter;
9246            }
9247            res.priority = info.getPriority();
9248            res.preferredOrder = provider.owner.mPreferredOrder;
9249            res.match = match;
9250            res.isDefault = info.hasDefault;
9251            res.labelRes = info.labelRes;
9252            res.nonLocalizedLabel = info.nonLocalizedLabel;
9253            res.icon = info.icon;
9254            res.system = res.providerInfo.applicationInfo.isSystemApp();
9255            return res;
9256        }
9257
9258        @Override
9259        protected void sortResults(List<ResolveInfo> results) {
9260            Collections.sort(results, mResolvePrioritySorter);
9261        }
9262
9263        @Override
9264        protected void dumpFilter(PrintWriter out, String prefix,
9265                PackageParser.ProviderIntentInfo filter) {
9266            out.print(prefix);
9267            out.print(
9268                    Integer.toHexString(System.identityHashCode(filter.provider)));
9269            out.print(' ');
9270            filter.provider.printComponentShortName(out);
9271            out.print(" filter ");
9272            out.println(Integer.toHexString(System.identityHashCode(filter)));
9273        }
9274
9275        @Override
9276        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9277            return filter.provider;
9278        }
9279
9280        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9281            PackageParser.Provider provider = (PackageParser.Provider)label;
9282            out.print(prefix); out.print(
9283                    Integer.toHexString(System.identityHashCode(provider)));
9284                    out.print(' ');
9285                    provider.printComponentShortName(out);
9286            if (count > 1) {
9287                out.print(" ("); out.print(count); out.print(" filters)");
9288            }
9289            out.println();
9290        }
9291
9292        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9293                = new ArrayMap<ComponentName, PackageParser.Provider>();
9294        private int mFlags;
9295    };
9296
9297    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9298            new Comparator<ResolveInfo>() {
9299        public int compare(ResolveInfo r1, ResolveInfo r2) {
9300            int v1 = r1.priority;
9301            int v2 = r2.priority;
9302            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9303            if (v1 != v2) {
9304                return (v1 > v2) ? -1 : 1;
9305            }
9306            v1 = r1.preferredOrder;
9307            v2 = r2.preferredOrder;
9308            if (v1 != v2) {
9309                return (v1 > v2) ? -1 : 1;
9310            }
9311            if (r1.isDefault != r2.isDefault) {
9312                return r1.isDefault ? -1 : 1;
9313            }
9314            v1 = r1.match;
9315            v2 = r2.match;
9316            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9317            if (v1 != v2) {
9318                return (v1 > v2) ? -1 : 1;
9319            }
9320            if (r1.system != r2.system) {
9321                return r1.system ? -1 : 1;
9322            }
9323            return 0;
9324        }
9325    };
9326
9327    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9328            new Comparator<ProviderInfo>() {
9329        public int compare(ProviderInfo p1, ProviderInfo p2) {
9330            final int v1 = p1.initOrder;
9331            final int v2 = p2.initOrder;
9332            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9333        }
9334    };
9335
9336    final void sendPackageBroadcast(final String action, final String pkg,
9337            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9338            final int[] userIds) {
9339        mHandler.post(new Runnable() {
9340            @Override
9341            public void run() {
9342                try {
9343                    final IActivityManager am = ActivityManagerNative.getDefault();
9344                    if (am == null) return;
9345                    final int[] resolvedUserIds;
9346                    if (userIds == null) {
9347                        resolvedUserIds = am.getRunningUserIds();
9348                    } else {
9349                        resolvedUserIds = userIds;
9350                    }
9351                    for (int id : resolvedUserIds) {
9352                        final Intent intent = new Intent(action,
9353                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9354                        if (extras != null) {
9355                            intent.putExtras(extras);
9356                        }
9357                        if (targetPkg != null) {
9358                            intent.setPackage(targetPkg);
9359                        }
9360                        // Modify the UID when posting to other users
9361                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9362                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9363                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9364                            intent.putExtra(Intent.EXTRA_UID, uid);
9365                        }
9366                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9367                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9368                        if (DEBUG_BROADCASTS) {
9369                            RuntimeException here = new RuntimeException("here");
9370                            here.fillInStackTrace();
9371                            Slog.d(TAG, "Sending to user " + id + ": "
9372                                    + intent.toShortString(false, true, false, false)
9373                                    + " " + intent.getExtras(), here);
9374                        }
9375                        am.broadcastIntent(null, intent, null, finishedReceiver,
9376                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9377                                null, finishedReceiver != null, false, id);
9378                    }
9379                } catch (RemoteException ex) {
9380                }
9381            }
9382        });
9383    }
9384
9385    /**
9386     * Check if the external storage media is available. This is true if there
9387     * is a mounted external storage medium or if the external storage is
9388     * emulated.
9389     */
9390    private boolean isExternalMediaAvailable() {
9391        return mMediaMounted || Environment.isExternalStorageEmulated();
9392    }
9393
9394    @Override
9395    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9396        // writer
9397        synchronized (mPackages) {
9398            if (!isExternalMediaAvailable()) {
9399                // If the external storage is no longer mounted at this point,
9400                // the caller may not have been able to delete all of this
9401                // packages files and can not delete any more.  Bail.
9402                return null;
9403            }
9404            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9405            if (lastPackage != null) {
9406                pkgs.remove(lastPackage);
9407            }
9408            if (pkgs.size() > 0) {
9409                return pkgs.get(0);
9410            }
9411        }
9412        return null;
9413    }
9414
9415    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9416        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9417                userId, andCode ? 1 : 0, packageName);
9418        if (mSystemReady) {
9419            msg.sendToTarget();
9420        } else {
9421            if (mPostSystemReadyMessages == null) {
9422                mPostSystemReadyMessages = new ArrayList<>();
9423            }
9424            mPostSystemReadyMessages.add(msg);
9425        }
9426    }
9427
9428    void startCleaningPackages() {
9429        // reader
9430        synchronized (mPackages) {
9431            if (!isExternalMediaAvailable()) {
9432                return;
9433            }
9434            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9435                return;
9436            }
9437        }
9438        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9439        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9440        IActivityManager am = ActivityManagerNative.getDefault();
9441        if (am != null) {
9442            try {
9443                am.startService(null, intent, null, mContext.getOpPackageName(),
9444                        UserHandle.USER_OWNER);
9445            } catch (RemoteException e) {
9446            }
9447        }
9448    }
9449
9450    @Override
9451    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9452            int installFlags, String installerPackageName, VerificationParams verificationParams,
9453            String packageAbiOverride) {
9454        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9455                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9456    }
9457
9458    @Override
9459    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9460            int installFlags, String installerPackageName, VerificationParams verificationParams,
9461            String packageAbiOverride, int userId) {
9462        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9463
9464        final int callingUid = Binder.getCallingUid();
9465        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9466
9467        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9468            try {
9469                if (observer != null) {
9470                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9471                }
9472            } catch (RemoteException re) {
9473            }
9474            return;
9475        }
9476
9477        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9478            installFlags |= PackageManager.INSTALL_FROM_ADB;
9479
9480        } else {
9481            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9482            // about installerPackageName.
9483
9484            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9485            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9486        }
9487
9488        UserHandle user;
9489        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9490            user = UserHandle.ALL;
9491        } else {
9492            user = new UserHandle(userId);
9493        }
9494
9495        // Only system components can circumvent runtime permissions when installing.
9496        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9497                && mContext.checkCallingOrSelfPermission(Manifest.permission
9498                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9499            throw new SecurityException("You need the "
9500                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9501                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9502        }
9503
9504        verificationParams.setInstallerUid(callingUid);
9505
9506        final File originFile = new File(originPath);
9507        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9508
9509        final Message msg = mHandler.obtainMessage(INIT_COPY);
9510        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9511                null, verificationParams, user, packageAbiOverride, null);
9512        mHandler.sendMessage(msg);
9513    }
9514
9515    void installStage(String packageName, File stagedDir, String stagedCid,
9516            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9517            String installerPackageName, int installerUid, UserHandle user) {
9518        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9519                params.referrerUri, installerUid, null);
9520        verifParams.setInstallerUid(installerUid);
9521
9522        final OriginInfo origin;
9523        if (stagedDir != null) {
9524            origin = OriginInfo.fromStagedFile(stagedDir);
9525        } else {
9526            origin = OriginInfo.fromStagedContainer(stagedCid);
9527        }
9528
9529        final Message msg = mHandler.obtainMessage(INIT_COPY);
9530        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9531                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9532                params.grantedRuntimePermissions);
9533        mHandler.sendMessage(msg);
9534    }
9535
9536    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9537        Bundle extras = new Bundle(1);
9538        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9539
9540        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9541                packageName, extras, null, null, new int[] {userId});
9542        try {
9543            IActivityManager am = ActivityManagerNative.getDefault();
9544            final boolean isSystem =
9545                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9546            if (isSystem && am.isUserRunning(userId, false)) {
9547                // The just-installed/enabled app is bundled on the system, so presumed
9548                // to be able to run automatically without needing an explicit launch.
9549                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9550                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9551                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9552                        .setPackage(packageName);
9553                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9554                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9555            }
9556        } catch (RemoteException e) {
9557            // shouldn't happen
9558            Slog.w(TAG, "Unable to bootstrap installed package", e);
9559        }
9560    }
9561
9562    @Override
9563    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9564            int userId) {
9565        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9566        PackageSetting pkgSetting;
9567        final int uid = Binder.getCallingUid();
9568        enforceCrossUserPermission(uid, userId, true, true,
9569                "setApplicationHiddenSetting for user " + userId);
9570
9571        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9572            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9573            return false;
9574        }
9575
9576        long callingId = Binder.clearCallingIdentity();
9577        try {
9578            boolean sendAdded = false;
9579            boolean sendRemoved = false;
9580            // writer
9581            synchronized (mPackages) {
9582                pkgSetting = mSettings.mPackages.get(packageName);
9583                if (pkgSetting == null) {
9584                    return false;
9585                }
9586                if (pkgSetting.getHidden(userId) != hidden) {
9587                    pkgSetting.setHidden(hidden, userId);
9588                    mSettings.writePackageRestrictionsLPr(userId);
9589                    if (hidden) {
9590                        sendRemoved = true;
9591                    } else {
9592                        sendAdded = true;
9593                    }
9594                }
9595            }
9596            if (sendAdded) {
9597                sendPackageAddedForUser(packageName, pkgSetting, userId);
9598                return true;
9599            }
9600            if (sendRemoved) {
9601                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9602                        "hiding pkg");
9603                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9604                return true;
9605            }
9606        } finally {
9607            Binder.restoreCallingIdentity(callingId);
9608        }
9609        return false;
9610    }
9611
9612    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9613            int userId) {
9614        final PackageRemovedInfo info = new PackageRemovedInfo();
9615        info.removedPackage = packageName;
9616        info.removedUsers = new int[] {userId};
9617        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9618        info.sendBroadcast(false, false, false);
9619    }
9620
9621    /**
9622     * Returns true if application is not found or there was an error. Otherwise it returns
9623     * the hidden state of the package for the given user.
9624     */
9625    @Override
9626    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9627        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9628        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9629                false, "getApplicationHidden for user " + userId);
9630        PackageSetting pkgSetting;
9631        long callingId = Binder.clearCallingIdentity();
9632        try {
9633            // writer
9634            synchronized (mPackages) {
9635                pkgSetting = mSettings.mPackages.get(packageName);
9636                if (pkgSetting == null) {
9637                    return true;
9638                }
9639                return pkgSetting.getHidden(userId);
9640            }
9641        } finally {
9642            Binder.restoreCallingIdentity(callingId);
9643        }
9644    }
9645
9646    /**
9647     * @hide
9648     */
9649    @Override
9650    public int installExistingPackageAsUser(String packageName, int userId) {
9651        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9652                null);
9653        PackageSetting pkgSetting;
9654        final int uid = Binder.getCallingUid();
9655        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9656                + userId);
9657        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9658            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9659        }
9660
9661        long callingId = Binder.clearCallingIdentity();
9662        try {
9663            boolean sendAdded = false;
9664
9665            // writer
9666            synchronized (mPackages) {
9667                pkgSetting = mSettings.mPackages.get(packageName);
9668                if (pkgSetting == null) {
9669                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9670                }
9671                if (!pkgSetting.getInstalled(userId)) {
9672                    pkgSetting.setInstalled(true, userId);
9673                    pkgSetting.setHidden(false, userId);
9674                    mSettings.writePackageRestrictionsLPr(userId);
9675                    sendAdded = true;
9676                }
9677            }
9678
9679            if (sendAdded) {
9680                sendPackageAddedForUser(packageName, pkgSetting, userId);
9681            }
9682        } finally {
9683            Binder.restoreCallingIdentity(callingId);
9684        }
9685
9686        return PackageManager.INSTALL_SUCCEEDED;
9687    }
9688
9689    boolean isUserRestricted(int userId, String restrictionKey) {
9690        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9691        if (restrictions.getBoolean(restrictionKey, false)) {
9692            Log.w(TAG, "User is restricted: " + restrictionKey);
9693            return true;
9694        }
9695        return false;
9696    }
9697
9698    @Override
9699    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9700        mContext.enforceCallingOrSelfPermission(
9701                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9702                "Only package verification agents can verify applications");
9703
9704        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9705        final PackageVerificationResponse response = new PackageVerificationResponse(
9706                verificationCode, Binder.getCallingUid());
9707        msg.arg1 = id;
9708        msg.obj = response;
9709        mHandler.sendMessage(msg);
9710    }
9711
9712    @Override
9713    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9714            long millisecondsToDelay) {
9715        mContext.enforceCallingOrSelfPermission(
9716                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9717                "Only package verification agents can extend verification timeouts");
9718
9719        final PackageVerificationState state = mPendingVerification.get(id);
9720        final PackageVerificationResponse response = new PackageVerificationResponse(
9721                verificationCodeAtTimeout, Binder.getCallingUid());
9722
9723        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9724            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9725        }
9726        if (millisecondsToDelay < 0) {
9727            millisecondsToDelay = 0;
9728        }
9729        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9730                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9731            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9732        }
9733
9734        if ((state != null) && !state.timeoutExtended()) {
9735            state.extendTimeout();
9736
9737            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9738            msg.arg1 = id;
9739            msg.obj = response;
9740            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9741        }
9742    }
9743
9744    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9745            int verificationCode, UserHandle user) {
9746        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9747        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9748        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9749        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9750        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9751
9752        mContext.sendBroadcastAsUser(intent, user,
9753                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9754    }
9755
9756    private ComponentName matchComponentForVerifier(String packageName,
9757            List<ResolveInfo> receivers) {
9758        ActivityInfo targetReceiver = null;
9759
9760        final int NR = receivers.size();
9761        for (int i = 0; i < NR; i++) {
9762            final ResolveInfo info = receivers.get(i);
9763            if (info.activityInfo == null) {
9764                continue;
9765            }
9766
9767            if (packageName.equals(info.activityInfo.packageName)) {
9768                targetReceiver = info.activityInfo;
9769                break;
9770            }
9771        }
9772
9773        if (targetReceiver == null) {
9774            return null;
9775        }
9776
9777        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9778    }
9779
9780    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9781            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9782        if (pkgInfo.verifiers.length == 0) {
9783            return null;
9784        }
9785
9786        final int N = pkgInfo.verifiers.length;
9787        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9788        for (int i = 0; i < N; i++) {
9789            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9790
9791            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9792                    receivers);
9793            if (comp == null) {
9794                continue;
9795            }
9796
9797            final int verifierUid = getUidForVerifier(verifierInfo);
9798            if (verifierUid == -1) {
9799                continue;
9800            }
9801
9802            if (DEBUG_VERIFY) {
9803                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9804                        + " with the correct signature");
9805            }
9806            sufficientVerifiers.add(comp);
9807            verificationState.addSufficientVerifier(verifierUid);
9808        }
9809
9810        return sufficientVerifiers;
9811    }
9812
9813    private int getUidForVerifier(VerifierInfo verifierInfo) {
9814        synchronized (mPackages) {
9815            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9816            if (pkg == null) {
9817                return -1;
9818            } else if (pkg.mSignatures.length != 1) {
9819                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9820                        + " has more than one signature; ignoring");
9821                return -1;
9822            }
9823
9824            /*
9825             * If the public key of the package's signature does not match
9826             * our expected public key, then this is a different package and
9827             * we should skip.
9828             */
9829
9830            final byte[] expectedPublicKey;
9831            try {
9832                final Signature verifierSig = pkg.mSignatures[0];
9833                final PublicKey publicKey = verifierSig.getPublicKey();
9834                expectedPublicKey = publicKey.getEncoded();
9835            } catch (CertificateException e) {
9836                return -1;
9837            }
9838
9839            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9840
9841            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9842                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9843                        + " does not have the expected public key; ignoring");
9844                return -1;
9845            }
9846
9847            return pkg.applicationInfo.uid;
9848        }
9849    }
9850
9851    @Override
9852    public void finishPackageInstall(int token) {
9853        enforceSystemOrRoot("Only the system is allowed to finish installs");
9854
9855        if (DEBUG_INSTALL) {
9856            Slog.v(TAG, "BM finishing package install for " + token);
9857        }
9858
9859        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9860        mHandler.sendMessage(msg);
9861    }
9862
9863    /**
9864     * Get the verification agent timeout.
9865     *
9866     * @return verification timeout in milliseconds
9867     */
9868    private long getVerificationTimeout() {
9869        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9870                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9871                DEFAULT_VERIFICATION_TIMEOUT);
9872    }
9873
9874    /**
9875     * Get the default verification agent response code.
9876     *
9877     * @return default verification response code
9878     */
9879    private int getDefaultVerificationResponse() {
9880        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9881                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9882                DEFAULT_VERIFICATION_RESPONSE);
9883    }
9884
9885    /**
9886     * Check whether or not package verification has been enabled.
9887     *
9888     * @return true if verification should be performed
9889     */
9890    private boolean isVerificationEnabled(int userId, int installFlags) {
9891        if (!DEFAULT_VERIFY_ENABLE) {
9892            return false;
9893        }
9894
9895        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9896
9897        // Check if installing from ADB
9898        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9899            // Do not run verification in a test harness environment
9900            if (ActivityManager.isRunningInTestHarness()) {
9901                return false;
9902            }
9903            if (ensureVerifyAppsEnabled) {
9904                return true;
9905            }
9906            // Check if the developer does not want package verification for ADB installs
9907            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9908                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9909                return false;
9910            }
9911        }
9912
9913        if (ensureVerifyAppsEnabled) {
9914            return true;
9915        }
9916
9917        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9918                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9919    }
9920
9921    @Override
9922    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9923            throws RemoteException {
9924        mContext.enforceCallingOrSelfPermission(
9925                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9926                "Only intentfilter verification agents can verify applications");
9927
9928        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9929        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9930                Binder.getCallingUid(), verificationCode, failedDomains);
9931        msg.arg1 = id;
9932        msg.obj = response;
9933        mHandler.sendMessage(msg);
9934    }
9935
9936    @Override
9937    public int getIntentVerificationStatus(String packageName, int userId) {
9938        synchronized (mPackages) {
9939            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9940        }
9941    }
9942
9943    @Override
9944    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9945        mContext.enforceCallingOrSelfPermission(
9946                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9947
9948        boolean result = false;
9949        synchronized (mPackages) {
9950            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9951        }
9952        if (result) {
9953            scheduleWritePackageRestrictionsLocked(userId);
9954        }
9955        return result;
9956    }
9957
9958    @Override
9959    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9960        synchronized (mPackages) {
9961            return mSettings.getIntentFilterVerificationsLPr(packageName);
9962        }
9963    }
9964
9965    @Override
9966    public List<IntentFilter> getAllIntentFilters(String packageName) {
9967        if (TextUtils.isEmpty(packageName)) {
9968            return Collections.<IntentFilter>emptyList();
9969        }
9970        synchronized (mPackages) {
9971            PackageParser.Package pkg = mPackages.get(packageName);
9972            if (pkg == null || pkg.activities == null) {
9973                return Collections.<IntentFilter>emptyList();
9974            }
9975            final int count = pkg.activities.size();
9976            ArrayList<IntentFilter> result = new ArrayList<>();
9977            for (int n=0; n<count; n++) {
9978                PackageParser.Activity activity = pkg.activities.get(n);
9979                if (activity.intents != null || activity.intents.size() > 0) {
9980                    result.addAll(activity.intents);
9981                }
9982            }
9983            return result;
9984        }
9985    }
9986
9987    @Override
9988    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9989        mContext.enforceCallingOrSelfPermission(
9990                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9991
9992        synchronized (mPackages) {
9993            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9994            if (packageName != null) {
9995                result |= updateIntentVerificationStatus(packageName,
9996                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9997                        userId);
9998                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9999                        packageName, userId);
10000            }
10001            return result;
10002        }
10003    }
10004
10005    @Override
10006    public String getDefaultBrowserPackageName(int userId) {
10007        synchronized (mPackages) {
10008            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10009        }
10010    }
10011
10012    /**
10013     * Get the "allow unknown sources" setting.
10014     *
10015     * @return the current "allow unknown sources" setting
10016     */
10017    private int getUnknownSourcesSettings() {
10018        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10019                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10020                -1);
10021    }
10022
10023    @Override
10024    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10025        final int uid = Binder.getCallingUid();
10026        // writer
10027        synchronized (mPackages) {
10028            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10029            if (targetPackageSetting == null) {
10030                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10031            }
10032
10033            PackageSetting installerPackageSetting;
10034            if (installerPackageName != null) {
10035                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10036                if (installerPackageSetting == null) {
10037                    throw new IllegalArgumentException("Unknown installer package: "
10038                            + installerPackageName);
10039                }
10040            } else {
10041                installerPackageSetting = null;
10042            }
10043
10044            Signature[] callerSignature;
10045            Object obj = mSettings.getUserIdLPr(uid);
10046            if (obj != null) {
10047                if (obj instanceof SharedUserSetting) {
10048                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10049                } else if (obj instanceof PackageSetting) {
10050                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10051                } else {
10052                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10053                }
10054            } else {
10055                throw new SecurityException("Unknown calling uid " + uid);
10056            }
10057
10058            // Verify: can't set installerPackageName to a package that is
10059            // not signed with the same cert as the caller.
10060            if (installerPackageSetting != null) {
10061                if (compareSignatures(callerSignature,
10062                        installerPackageSetting.signatures.mSignatures)
10063                        != PackageManager.SIGNATURE_MATCH) {
10064                    throw new SecurityException(
10065                            "Caller does not have same cert as new installer package "
10066                            + installerPackageName);
10067                }
10068            }
10069
10070            // Verify: if target already has an installer package, it must
10071            // be signed with the same cert as the caller.
10072            if (targetPackageSetting.installerPackageName != null) {
10073                PackageSetting setting = mSettings.mPackages.get(
10074                        targetPackageSetting.installerPackageName);
10075                // If the currently set package isn't valid, then it's always
10076                // okay to change it.
10077                if (setting != null) {
10078                    if (compareSignatures(callerSignature,
10079                            setting.signatures.mSignatures)
10080                            != PackageManager.SIGNATURE_MATCH) {
10081                        throw new SecurityException(
10082                                "Caller does not have same cert as old installer package "
10083                                + targetPackageSetting.installerPackageName);
10084                    }
10085                }
10086            }
10087
10088            // Okay!
10089            targetPackageSetting.installerPackageName = installerPackageName;
10090            scheduleWriteSettingsLocked();
10091        }
10092    }
10093
10094    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10095        // Queue up an async operation since the package installation may take a little while.
10096        mHandler.post(new Runnable() {
10097            public void run() {
10098                mHandler.removeCallbacks(this);
10099                 // Result object to be returned
10100                PackageInstalledInfo res = new PackageInstalledInfo();
10101                res.returnCode = currentStatus;
10102                res.uid = -1;
10103                res.pkg = null;
10104                res.removedInfo = new PackageRemovedInfo();
10105                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10106                    args.doPreInstall(res.returnCode);
10107                    synchronized (mInstallLock) {
10108                        installPackageLI(args, res);
10109                    }
10110                    args.doPostInstall(res.returnCode, res.uid);
10111                }
10112
10113                // A restore should be performed at this point if (a) the install
10114                // succeeded, (b) the operation is not an update, and (c) the new
10115                // package has not opted out of backup participation.
10116                final boolean update = res.removedInfo.removedPackage != null;
10117                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10118                boolean doRestore = !update
10119                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10120
10121                // Set up the post-install work request bookkeeping.  This will be used
10122                // and cleaned up by the post-install event handling regardless of whether
10123                // there's a restore pass performed.  Token values are >= 1.
10124                int token;
10125                if (mNextInstallToken < 0) mNextInstallToken = 1;
10126                token = mNextInstallToken++;
10127
10128                PostInstallData data = new PostInstallData(args, res);
10129                mRunningInstalls.put(token, data);
10130                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10131
10132                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10133                    // Pass responsibility to the Backup Manager.  It will perform a
10134                    // restore if appropriate, then pass responsibility back to the
10135                    // Package Manager to run the post-install observer callbacks
10136                    // and broadcasts.
10137                    IBackupManager bm = IBackupManager.Stub.asInterface(
10138                            ServiceManager.getService(Context.BACKUP_SERVICE));
10139                    if (bm != null) {
10140                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10141                                + " to BM for possible restore");
10142                        try {
10143                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10144                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10145                            } else {
10146                                doRestore = false;
10147                            }
10148                        } catch (RemoteException e) {
10149                            // can't happen; the backup manager is local
10150                        } catch (Exception e) {
10151                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10152                            doRestore = false;
10153                        }
10154                    } else {
10155                        Slog.e(TAG, "Backup Manager not found!");
10156                        doRestore = false;
10157                    }
10158                }
10159
10160                if (!doRestore) {
10161                    // No restore possible, or the Backup Manager was mysteriously not
10162                    // available -- just fire the post-install work request directly.
10163                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10164                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10165                    mHandler.sendMessage(msg);
10166                }
10167            }
10168        });
10169    }
10170
10171    private abstract class HandlerParams {
10172        private static final int MAX_RETRIES = 4;
10173
10174        /**
10175         * Number of times startCopy() has been attempted and had a non-fatal
10176         * error.
10177         */
10178        private int mRetries = 0;
10179
10180        /** User handle for the user requesting the information or installation. */
10181        private final UserHandle mUser;
10182
10183        HandlerParams(UserHandle user) {
10184            mUser = user;
10185        }
10186
10187        UserHandle getUser() {
10188            return mUser;
10189        }
10190
10191        final boolean startCopy() {
10192            boolean res;
10193            try {
10194                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10195
10196                if (++mRetries > MAX_RETRIES) {
10197                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10198                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10199                    handleServiceError();
10200                    return false;
10201                } else {
10202                    handleStartCopy();
10203                    res = true;
10204                }
10205            } catch (RemoteException e) {
10206                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10207                mHandler.sendEmptyMessage(MCS_RECONNECT);
10208                res = false;
10209            }
10210            handleReturnCode();
10211            return res;
10212        }
10213
10214        final void serviceError() {
10215            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10216            handleServiceError();
10217            handleReturnCode();
10218        }
10219
10220        abstract void handleStartCopy() throws RemoteException;
10221        abstract void handleServiceError();
10222        abstract void handleReturnCode();
10223    }
10224
10225    class MeasureParams extends HandlerParams {
10226        private final PackageStats mStats;
10227        private boolean mSuccess;
10228
10229        private final IPackageStatsObserver mObserver;
10230
10231        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10232            super(new UserHandle(stats.userHandle));
10233            mObserver = observer;
10234            mStats = stats;
10235        }
10236
10237        @Override
10238        public String toString() {
10239            return "MeasureParams{"
10240                + Integer.toHexString(System.identityHashCode(this))
10241                + " " + mStats.packageName + "}";
10242        }
10243
10244        @Override
10245        void handleStartCopy() throws RemoteException {
10246            synchronized (mInstallLock) {
10247                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10248            }
10249
10250            if (mSuccess) {
10251                final boolean mounted;
10252                if (Environment.isExternalStorageEmulated()) {
10253                    mounted = true;
10254                } else {
10255                    final String status = Environment.getExternalStorageState();
10256                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10257                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10258                }
10259
10260                if (mounted) {
10261                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10262
10263                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10264                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10265
10266                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10267                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10268
10269                    // Always subtract cache size, since it's a subdirectory
10270                    mStats.externalDataSize -= mStats.externalCacheSize;
10271
10272                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10273                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10274
10275                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10276                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10277                }
10278            }
10279        }
10280
10281        @Override
10282        void handleReturnCode() {
10283            if (mObserver != null) {
10284                try {
10285                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10286                } catch (RemoteException e) {
10287                    Slog.i(TAG, "Observer no longer exists.");
10288                }
10289            }
10290        }
10291
10292        @Override
10293        void handleServiceError() {
10294            Slog.e(TAG, "Could not measure application " + mStats.packageName
10295                            + " external storage");
10296        }
10297    }
10298
10299    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10300            throws RemoteException {
10301        long result = 0;
10302        for (File path : paths) {
10303            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10304        }
10305        return result;
10306    }
10307
10308    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10309        for (File path : paths) {
10310            try {
10311                mcs.clearDirectory(path.getAbsolutePath());
10312            } catch (RemoteException e) {
10313            }
10314        }
10315    }
10316
10317    static class OriginInfo {
10318        /**
10319         * Location where install is coming from, before it has been
10320         * copied/renamed into place. This could be a single monolithic APK
10321         * file, or a cluster directory. This location may be untrusted.
10322         */
10323        final File file;
10324        final String cid;
10325
10326        /**
10327         * Flag indicating that {@link #file} or {@link #cid} has already been
10328         * staged, meaning downstream users don't need to defensively copy the
10329         * contents.
10330         */
10331        final boolean staged;
10332
10333        /**
10334         * Flag indicating that {@link #file} or {@link #cid} is an already
10335         * installed app that is being moved.
10336         */
10337        final boolean existing;
10338
10339        final String resolvedPath;
10340        final File resolvedFile;
10341
10342        static OriginInfo fromNothing() {
10343            return new OriginInfo(null, null, false, false);
10344        }
10345
10346        static OriginInfo fromUntrustedFile(File file) {
10347            return new OriginInfo(file, null, false, false);
10348        }
10349
10350        static OriginInfo fromExistingFile(File file) {
10351            return new OriginInfo(file, null, false, true);
10352        }
10353
10354        static OriginInfo fromStagedFile(File file) {
10355            return new OriginInfo(file, null, true, false);
10356        }
10357
10358        static OriginInfo fromStagedContainer(String cid) {
10359            return new OriginInfo(null, cid, true, false);
10360        }
10361
10362        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10363            this.file = file;
10364            this.cid = cid;
10365            this.staged = staged;
10366            this.existing = existing;
10367
10368            if (cid != null) {
10369                resolvedPath = PackageHelper.getSdDir(cid);
10370                resolvedFile = new File(resolvedPath);
10371            } else if (file != null) {
10372                resolvedPath = file.getAbsolutePath();
10373                resolvedFile = file;
10374            } else {
10375                resolvedPath = null;
10376                resolvedFile = null;
10377            }
10378        }
10379    }
10380
10381    class MoveInfo {
10382        final int moveId;
10383        final String fromUuid;
10384        final String toUuid;
10385        final String packageName;
10386        final String dataAppName;
10387        final int appId;
10388        final String seinfo;
10389
10390        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10391                String dataAppName, int appId, String seinfo) {
10392            this.moveId = moveId;
10393            this.fromUuid = fromUuid;
10394            this.toUuid = toUuid;
10395            this.packageName = packageName;
10396            this.dataAppName = dataAppName;
10397            this.appId = appId;
10398            this.seinfo = seinfo;
10399        }
10400    }
10401
10402    class InstallParams extends HandlerParams {
10403        final OriginInfo origin;
10404        final MoveInfo move;
10405        final IPackageInstallObserver2 observer;
10406        int installFlags;
10407        final String installerPackageName;
10408        final String volumeUuid;
10409        final VerificationParams verificationParams;
10410        private InstallArgs mArgs;
10411        private int mRet;
10412        final String packageAbiOverride;
10413        final String[] grantedRuntimePermissions;
10414
10415
10416        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10417                int installFlags, String installerPackageName, String volumeUuid,
10418                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10419                String[] grantedPermissions) {
10420            super(user);
10421            this.origin = origin;
10422            this.move = move;
10423            this.observer = observer;
10424            this.installFlags = installFlags;
10425            this.installerPackageName = installerPackageName;
10426            this.volumeUuid = volumeUuid;
10427            this.verificationParams = verificationParams;
10428            this.packageAbiOverride = packageAbiOverride;
10429            this.grantedRuntimePermissions = grantedPermissions;
10430        }
10431
10432        @Override
10433        public String toString() {
10434            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10435                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10436        }
10437
10438        public ManifestDigest getManifestDigest() {
10439            if (verificationParams == null) {
10440                return null;
10441            }
10442            return verificationParams.getManifestDigest();
10443        }
10444
10445        private int installLocationPolicy(PackageInfoLite pkgLite) {
10446            String packageName = pkgLite.packageName;
10447            int installLocation = pkgLite.installLocation;
10448            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10449            // reader
10450            synchronized (mPackages) {
10451                PackageParser.Package pkg = mPackages.get(packageName);
10452                if (pkg != null) {
10453                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10454                        // Check for downgrading.
10455                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10456                            try {
10457                                checkDowngrade(pkg, pkgLite);
10458                            } catch (PackageManagerException e) {
10459                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10460                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10461                            }
10462                        }
10463                        // Check for updated system application.
10464                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10465                            if (onSd) {
10466                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10467                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10468                            }
10469                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10470                        } else {
10471                            if (onSd) {
10472                                // Install flag overrides everything.
10473                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10474                            }
10475                            // If current upgrade specifies particular preference
10476                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10477                                // Application explicitly specified internal.
10478                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10479                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10480                                // App explictly prefers external. Let policy decide
10481                            } else {
10482                                // Prefer previous location
10483                                if (isExternal(pkg)) {
10484                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10485                                }
10486                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10487                            }
10488                        }
10489                    } else {
10490                        // Invalid install. Return error code
10491                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10492                    }
10493                }
10494            }
10495            // All the special cases have been taken care of.
10496            // Return result based on recommended install location.
10497            if (onSd) {
10498                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10499            }
10500            return pkgLite.recommendedInstallLocation;
10501        }
10502
10503        /*
10504         * Invoke remote method to get package information and install
10505         * location values. Override install location based on default
10506         * policy if needed and then create install arguments based
10507         * on the install location.
10508         */
10509        public void handleStartCopy() throws RemoteException {
10510            int ret = PackageManager.INSTALL_SUCCEEDED;
10511
10512            // If we're already staged, we've firmly committed to an install location
10513            if (origin.staged) {
10514                if (origin.file != null) {
10515                    installFlags |= PackageManager.INSTALL_INTERNAL;
10516                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10517                } else if (origin.cid != null) {
10518                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10519                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10520                } else {
10521                    throw new IllegalStateException("Invalid stage location");
10522                }
10523            }
10524
10525            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10526            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10527
10528            PackageInfoLite pkgLite = null;
10529
10530            if (onInt && onSd) {
10531                // Check if both bits are set.
10532                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10533                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10534            } else {
10535                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10536                        packageAbiOverride);
10537
10538                /*
10539                 * If we have too little free space, try to free cache
10540                 * before giving up.
10541                 */
10542                if (!origin.staged && pkgLite.recommendedInstallLocation
10543                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10544                    // TODO: focus freeing disk space on the target device
10545                    final StorageManager storage = StorageManager.from(mContext);
10546                    final long lowThreshold = storage.getStorageLowBytes(
10547                            Environment.getDataDirectory());
10548
10549                    final long sizeBytes = mContainerService.calculateInstalledSize(
10550                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10551
10552                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10553                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10554                                installFlags, packageAbiOverride);
10555                    }
10556
10557                    /*
10558                     * The cache free must have deleted the file we
10559                     * downloaded to install.
10560                     *
10561                     * TODO: fix the "freeCache" call to not delete
10562                     *       the file we care about.
10563                     */
10564                    if (pkgLite.recommendedInstallLocation
10565                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10566                        pkgLite.recommendedInstallLocation
10567                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10568                    }
10569                }
10570            }
10571
10572            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10573                int loc = pkgLite.recommendedInstallLocation;
10574                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10575                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10576                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10577                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10578                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10579                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10580                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10581                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10582                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10583                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10584                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10585                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10586                } else {
10587                    // Override with defaults if needed.
10588                    loc = installLocationPolicy(pkgLite);
10589                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10590                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10591                    } else if (!onSd && !onInt) {
10592                        // Override install location with flags
10593                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10594                            // Set the flag to install on external media.
10595                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10596                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10597                        } else {
10598                            // Make sure the flag for installing on external
10599                            // media is unset
10600                            installFlags |= PackageManager.INSTALL_INTERNAL;
10601                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10602                        }
10603                    }
10604                }
10605            }
10606
10607            final InstallArgs args = createInstallArgs(this);
10608            mArgs = args;
10609
10610            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10611                 /*
10612                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10613                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10614                 */
10615                int userIdentifier = getUser().getIdentifier();
10616                if (userIdentifier == UserHandle.USER_ALL
10617                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10618                    userIdentifier = UserHandle.USER_OWNER;
10619                }
10620
10621                /*
10622                 * Determine if we have any installed package verifiers. If we
10623                 * do, then we'll defer to them to verify the packages.
10624                 */
10625                final int requiredUid = mRequiredVerifierPackage == null ? -1
10626                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10627                if (!origin.existing && requiredUid != -1
10628                        && isVerificationEnabled(userIdentifier, installFlags)) {
10629                    final Intent verification = new Intent(
10630                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10631                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10632                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10633                            PACKAGE_MIME_TYPE);
10634                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10635
10636                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10637                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10638                            0 /* TODO: Which userId? */);
10639
10640                    if (DEBUG_VERIFY) {
10641                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10642                                + verification.toString() + " with " + pkgLite.verifiers.length
10643                                + " optional verifiers");
10644                    }
10645
10646                    final int verificationId = mPendingVerificationToken++;
10647
10648                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10649
10650                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10651                            installerPackageName);
10652
10653                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10654                            installFlags);
10655
10656                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10657                            pkgLite.packageName);
10658
10659                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10660                            pkgLite.versionCode);
10661
10662                    if (verificationParams != null) {
10663                        if (verificationParams.getVerificationURI() != null) {
10664                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10665                                 verificationParams.getVerificationURI());
10666                        }
10667                        if (verificationParams.getOriginatingURI() != null) {
10668                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10669                                  verificationParams.getOriginatingURI());
10670                        }
10671                        if (verificationParams.getReferrer() != null) {
10672                            verification.putExtra(Intent.EXTRA_REFERRER,
10673                                  verificationParams.getReferrer());
10674                        }
10675                        if (verificationParams.getOriginatingUid() >= 0) {
10676                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10677                                  verificationParams.getOriginatingUid());
10678                        }
10679                        if (verificationParams.getInstallerUid() >= 0) {
10680                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10681                                  verificationParams.getInstallerUid());
10682                        }
10683                    }
10684
10685                    final PackageVerificationState verificationState = new PackageVerificationState(
10686                            requiredUid, args);
10687
10688                    mPendingVerification.append(verificationId, verificationState);
10689
10690                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10691                            receivers, verificationState);
10692
10693                    // Apps installed for "all" users use the device owner to verify the app
10694                    UserHandle verifierUser = getUser();
10695                    if (verifierUser == UserHandle.ALL) {
10696                        verifierUser = UserHandle.OWNER;
10697                    }
10698
10699                    /*
10700                     * If any sufficient verifiers were listed in the package
10701                     * manifest, attempt to ask them.
10702                     */
10703                    if (sufficientVerifiers != null) {
10704                        final int N = sufficientVerifiers.size();
10705                        if (N == 0) {
10706                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10707                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10708                        } else {
10709                            for (int i = 0; i < N; i++) {
10710                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10711
10712                                final Intent sufficientIntent = new Intent(verification);
10713                                sufficientIntent.setComponent(verifierComponent);
10714                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10715                            }
10716                        }
10717                    }
10718
10719                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10720                            mRequiredVerifierPackage, receivers);
10721                    if (ret == PackageManager.INSTALL_SUCCEEDED
10722                            && mRequiredVerifierPackage != null) {
10723                        /*
10724                         * Send the intent to the required verification agent,
10725                         * but only start the verification timeout after the
10726                         * target BroadcastReceivers have run.
10727                         */
10728                        verification.setComponent(requiredVerifierComponent);
10729                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10730                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10731                                new BroadcastReceiver() {
10732                                    @Override
10733                                    public void onReceive(Context context, Intent intent) {
10734                                        final Message msg = mHandler
10735                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10736                                        msg.arg1 = verificationId;
10737                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10738                                    }
10739                                }, null, 0, null, null);
10740
10741                        /*
10742                         * We don't want the copy to proceed until verification
10743                         * succeeds, so null out this field.
10744                         */
10745                        mArgs = null;
10746                    }
10747                } else {
10748                    /*
10749                     * No package verification is enabled, so immediately start
10750                     * the remote call to initiate copy using temporary file.
10751                     */
10752                    ret = args.copyApk(mContainerService, true);
10753                }
10754            }
10755
10756            mRet = ret;
10757        }
10758
10759        @Override
10760        void handleReturnCode() {
10761            // If mArgs is null, then MCS couldn't be reached. When it
10762            // reconnects, it will try again to install. At that point, this
10763            // will succeed.
10764            if (mArgs != null) {
10765                processPendingInstall(mArgs, mRet);
10766            }
10767        }
10768
10769        @Override
10770        void handleServiceError() {
10771            mArgs = createInstallArgs(this);
10772            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10773        }
10774
10775        public boolean isForwardLocked() {
10776            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10777        }
10778    }
10779
10780    /**
10781     * Used during creation of InstallArgs
10782     *
10783     * @param installFlags package installation flags
10784     * @return true if should be installed on external storage
10785     */
10786    private static boolean installOnExternalAsec(int installFlags) {
10787        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10788            return false;
10789        }
10790        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10791            return true;
10792        }
10793        return false;
10794    }
10795
10796    /**
10797     * Used during creation of InstallArgs
10798     *
10799     * @param installFlags package installation flags
10800     * @return true if should be installed as forward locked
10801     */
10802    private static boolean installForwardLocked(int installFlags) {
10803        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10804    }
10805
10806    private InstallArgs createInstallArgs(InstallParams params) {
10807        if (params.move != null) {
10808            return new MoveInstallArgs(params);
10809        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10810            return new AsecInstallArgs(params);
10811        } else {
10812            return new FileInstallArgs(params);
10813        }
10814    }
10815
10816    /**
10817     * Create args that describe an existing installed package. Typically used
10818     * when cleaning up old installs, or used as a move source.
10819     */
10820    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10821            String resourcePath, String[] instructionSets) {
10822        final boolean isInAsec;
10823        if (installOnExternalAsec(installFlags)) {
10824            /* Apps on SD card are always in ASEC containers. */
10825            isInAsec = true;
10826        } else if (installForwardLocked(installFlags)
10827                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10828            /*
10829             * Forward-locked apps are only in ASEC containers if they're the
10830             * new style
10831             */
10832            isInAsec = true;
10833        } else {
10834            isInAsec = false;
10835        }
10836
10837        if (isInAsec) {
10838            return new AsecInstallArgs(codePath, instructionSets,
10839                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10840        } else {
10841            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10842        }
10843    }
10844
10845    static abstract class InstallArgs {
10846        /** @see InstallParams#origin */
10847        final OriginInfo origin;
10848        /** @see InstallParams#move */
10849        final MoveInfo move;
10850
10851        final IPackageInstallObserver2 observer;
10852        // Always refers to PackageManager flags only
10853        final int installFlags;
10854        final String installerPackageName;
10855        final String volumeUuid;
10856        final ManifestDigest manifestDigest;
10857        final UserHandle user;
10858        final String abiOverride;
10859        final String[] installGrantPermissions;
10860
10861        // The list of instruction sets supported by this app. This is currently
10862        // only used during the rmdex() phase to clean up resources. We can get rid of this
10863        // if we move dex files under the common app path.
10864        /* nullable */ String[] instructionSets;
10865
10866        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10867                int installFlags, String installerPackageName, String volumeUuid,
10868                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10869                String abiOverride, String[] installGrantPermissions) {
10870            this.origin = origin;
10871            this.move = move;
10872            this.installFlags = installFlags;
10873            this.observer = observer;
10874            this.installerPackageName = installerPackageName;
10875            this.volumeUuid = volumeUuid;
10876            this.manifestDigest = manifestDigest;
10877            this.user = user;
10878            this.instructionSets = instructionSets;
10879            this.abiOverride = abiOverride;
10880            this.installGrantPermissions = installGrantPermissions;
10881        }
10882
10883        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10884        abstract int doPreInstall(int status);
10885
10886        /**
10887         * Rename package into final resting place. All paths on the given
10888         * scanned package should be updated to reflect the rename.
10889         */
10890        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10891        abstract int doPostInstall(int status, int uid);
10892
10893        /** @see PackageSettingBase#codePathString */
10894        abstract String getCodePath();
10895        /** @see PackageSettingBase#resourcePathString */
10896        abstract String getResourcePath();
10897
10898        // Need installer lock especially for dex file removal.
10899        abstract void cleanUpResourcesLI();
10900        abstract boolean doPostDeleteLI(boolean delete);
10901
10902        /**
10903         * Called before the source arguments are copied. This is used mostly
10904         * for MoveParams when it needs to read the source file to put it in the
10905         * destination.
10906         */
10907        int doPreCopy() {
10908            return PackageManager.INSTALL_SUCCEEDED;
10909        }
10910
10911        /**
10912         * Called after the source arguments are copied. This is used mostly for
10913         * MoveParams when it needs to read the source file to put it in the
10914         * destination.
10915         *
10916         * @return
10917         */
10918        int doPostCopy(int uid) {
10919            return PackageManager.INSTALL_SUCCEEDED;
10920        }
10921
10922        protected boolean isFwdLocked() {
10923            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10924        }
10925
10926        protected boolean isExternalAsec() {
10927            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10928        }
10929
10930        UserHandle getUser() {
10931            return user;
10932        }
10933    }
10934
10935    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10936        if (!allCodePaths.isEmpty()) {
10937            if (instructionSets == null) {
10938                throw new IllegalStateException("instructionSet == null");
10939            }
10940            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10941            for (String codePath : allCodePaths) {
10942                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10943                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10944                    if (retCode < 0) {
10945                        Slog.w(TAG, "Couldn't remove dex file for package: "
10946                                + " at location " + codePath + ", retcode=" + retCode);
10947                        // we don't consider this to be a failure of the core package deletion
10948                    }
10949                }
10950            }
10951        }
10952    }
10953
10954    /**
10955     * Logic to handle installation of non-ASEC applications, including copying
10956     * and renaming logic.
10957     */
10958    class FileInstallArgs extends InstallArgs {
10959        private File codeFile;
10960        private File resourceFile;
10961
10962        // Example topology:
10963        // /data/app/com.example/base.apk
10964        // /data/app/com.example/split_foo.apk
10965        // /data/app/com.example/lib/arm/libfoo.so
10966        // /data/app/com.example/lib/arm64/libfoo.so
10967        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10968
10969        /** New install */
10970        FileInstallArgs(InstallParams params) {
10971            super(params.origin, params.move, params.observer, params.installFlags,
10972                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10973                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10974                    params.grantedRuntimePermissions);
10975            if (isFwdLocked()) {
10976                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10977            }
10978        }
10979
10980        /** Existing install */
10981        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10982            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10983                    null, null);
10984            this.codeFile = (codePath != null) ? new File(codePath) : null;
10985            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10986        }
10987
10988        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10989            if (origin.staged) {
10990                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10991                codeFile = origin.file;
10992                resourceFile = origin.file;
10993                return PackageManager.INSTALL_SUCCEEDED;
10994            }
10995
10996            try {
10997                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10998                codeFile = tempDir;
10999                resourceFile = tempDir;
11000            } catch (IOException e) {
11001                Slog.w(TAG, "Failed to create copy file: " + e);
11002                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11003            }
11004
11005            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11006                @Override
11007                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11008                    if (!FileUtils.isValidExtFilename(name)) {
11009                        throw new IllegalArgumentException("Invalid filename: " + name);
11010                    }
11011                    try {
11012                        final File file = new File(codeFile, name);
11013                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11014                                O_RDWR | O_CREAT, 0644);
11015                        Os.chmod(file.getAbsolutePath(), 0644);
11016                        return new ParcelFileDescriptor(fd);
11017                    } catch (ErrnoException e) {
11018                        throw new RemoteException("Failed to open: " + e.getMessage());
11019                    }
11020                }
11021            };
11022
11023            int ret = PackageManager.INSTALL_SUCCEEDED;
11024            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11025            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11026                Slog.e(TAG, "Failed to copy package");
11027                return ret;
11028            }
11029
11030            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11031            NativeLibraryHelper.Handle handle = null;
11032            try {
11033                handle = NativeLibraryHelper.Handle.create(codeFile);
11034                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11035                        abiOverride);
11036            } catch (IOException e) {
11037                Slog.e(TAG, "Copying native libraries failed", e);
11038                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11039            } finally {
11040                IoUtils.closeQuietly(handle);
11041            }
11042
11043            return ret;
11044        }
11045
11046        int doPreInstall(int status) {
11047            if (status != PackageManager.INSTALL_SUCCEEDED) {
11048                cleanUp();
11049            }
11050            return status;
11051        }
11052
11053        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11054            if (status != PackageManager.INSTALL_SUCCEEDED) {
11055                cleanUp();
11056                return false;
11057            }
11058
11059            final File targetDir = codeFile.getParentFile();
11060            final File beforeCodeFile = codeFile;
11061            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11062
11063            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11064            try {
11065                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11066            } catch (ErrnoException e) {
11067                Slog.w(TAG, "Failed to rename", e);
11068                return false;
11069            }
11070
11071            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11072                Slog.w(TAG, "Failed to restorecon");
11073                return false;
11074            }
11075
11076            // Reflect the rename internally
11077            codeFile = afterCodeFile;
11078            resourceFile = afterCodeFile;
11079
11080            // Reflect the rename in scanned details
11081            pkg.codePath = afterCodeFile.getAbsolutePath();
11082            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11083                    pkg.baseCodePath);
11084            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11085                    pkg.splitCodePaths);
11086
11087            // Reflect the rename in app info
11088            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11089            pkg.applicationInfo.setCodePath(pkg.codePath);
11090            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11091            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11092            pkg.applicationInfo.setResourcePath(pkg.codePath);
11093            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11094            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11095
11096            return true;
11097        }
11098
11099        int doPostInstall(int status, int uid) {
11100            if (status != PackageManager.INSTALL_SUCCEEDED) {
11101                cleanUp();
11102            }
11103            return status;
11104        }
11105
11106        @Override
11107        String getCodePath() {
11108            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11109        }
11110
11111        @Override
11112        String getResourcePath() {
11113            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11114        }
11115
11116        private boolean cleanUp() {
11117            if (codeFile == null || !codeFile.exists()) {
11118                return false;
11119            }
11120
11121            if (codeFile.isDirectory()) {
11122                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11123            } else {
11124                codeFile.delete();
11125            }
11126
11127            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11128                resourceFile.delete();
11129            }
11130
11131            return true;
11132        }
11133
11134        void cleanUpResourcesLI() {
11135            // Try enumerating all code paths before deleting
11136            List<String> allCodePaths = Collections.EMPTY_LIST;
11137            if (codeFile != null && codeFile.exists()) {
11138                try {
11139                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11140                    allCodePaths = pkg.getAllCodePaths();
11141                } catch (PackageParserException e) {
11142                    // Ignored; we tried our best
11143                }
11144            }
11145
11146            cleanUp();
11147            removeDexFiles(allCodePaths, instructionSets);
11148        }
11149
11150        boolean doPostDeleteLI(boolean delete) {
11151            // XXX err, shouldn't we respect the delete flag?
11152            cleanUpResourcesLI();
11153            return true;
11154        }
11155    }
11156
11157    private boolean isAsecExternal(String cid) {
11158        final String asecPath = PackageHelper.getSdFilesystem(cid);
11159        return !asecPath.startsWith(mAsecInternalPath);
11160    }
11161
11162    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11163            PackageManagerException {
11164        if (copyRet < 0) {
11165            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11166                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11167                throw new PackageManagerException(copyRet, message);
11168            }
11169        }
11170    }
11171
11172    /**
11173     * Extract the MountService "container ID" from the full code path of an
11174     * .apk.
11175     */
11176    static String cidFromCodePath(String fullCodePath) {
11177        int eidx = fullCodePath.lastIndexOf("/");
11178        String subStr1 = fullCodePath.substring(0, eidx);
11179        int sidx = subStr1.lastIndexOf("/");
11180        return subStr1.substring(sidx+1, eidx);
11181    }
11182
11183    /**
11184     * Logic to handle installation of ASEC applications, including copying and
11185     * renaming logic.
11186     */
11187    class AsecInstallArgs extends InstallArgs {
11188        static final String RES_FILE_NAME = "pkg.apk";
11189        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11190
11191        String cid;
11192        String packagePath;
11193        String resourcePath;
11194
11195        /** New install */
11196        AsecInstallArgs(InstallParams params) {
11197            super(params.origin, params.move, params.observer, params.installFlags,
11198                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11199                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11200                    params.grantedRuntimePermissions);
11201        }
11202
11203        /** Existing install */
11204        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11205                        boolean isExternal, boolean isForwardLocked) {
11206            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11207                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11208                    instructionSets, null, null);
11209            // Hackily pretend we're still looking at a full code path
11210            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11211                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11212            }
11213
11214            // Extract cid from fullCodePath
11215            int eidx = fullCodePath.lastIndexOf("/");
11216            String subStr1 = fullCodePath.substring(0, eidx);
11217            int sidx = subStr1.lastIndexOf("/");
11218            cid = subStr1.substring(sidx+1, eidx);
11219            setMountPath(subStr1);
11220        }
11221
11222        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11223            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11224                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11225                    instructionSets, null, null);
11226            this.cid = cid;
11227            setMountPath(PackageHelper.getSdDir(cid));
11228        }
11229
11230        void createCopyFile() {
11231            cid = mInstallerService.allocateExternalStageCidLegacy();
11232        }
11233
11234        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11235            if (origin.staged) {
11236                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11237                cid = origin.cid;
11238                setMountPath(PackageHelper.getSdDir(cid));
11239                return PackageManager.INSTALL_SUCCEEDED;
11240            }
11241
11242            if (temp) {
11243                createCopyFile();
11244            } else {
11245                /*
11246                 * Pre-emptively destroy the container since it's destroyed if
11247                 * copying fails due to it existing anyway.
11248                 */
11249                PackageHelper.destroySdDir(cid);
11250            }
11251
11252            final String newMountPath = imcs.copyPackageToContainer(
11253                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11254                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11255
11256            if (newMountPath != null) {
11257                setMountPath(newMountPath);
11258                return PackageManager.INSTALL_SUCCEEDED;
11259            } else {
11260                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11261            }
11262        }
11263
11264        @Override
11265        String getCodePath() {
11266            return packagePath;
11267        }
11268
11269        @Override
11270        String getResourcePath() {
11271            return resourcePath;
11272        }
11273
11274        int doPreInstall(int status) {
11275            if (status != PackageManager.INSTALL_SUCCEEDED) {
11276                // Destroy container
11277                PackageHelper.destroySdDir(cid);
11278            } else {
11279                boolean mounted = PackageHelper.isContainerMounted(cid);
11280                if (!mounted) {
11281                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11282                            Process.SYSTEM_UID);
11283                    if (newMountPath != null) {
11284                        setMountPath(newMountPath);
11285                    } else {
11286                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11287                    }
11288                }
11289            }
11290            return status;
11291        }
11292
11293        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11294            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11295            String newMountPath = null;
11296            if (PackageHelper.isContainerMounted(cid)) {
11297                // Unmount the container
11298                if (!PackageHelper.unMountSdDir(cid)) {
11299                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11300                    return false;
11301                }
11302            }
11303            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11304                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11305                        " which might be stale. Will try to clean up.");
11306                // Clean up the stale container and proceed to recreate.
11307                if (!PackageHelper.destroySdDir(newCacheId)) {
11308                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11309                    return false;
11310                }
11311                // Successfully cleaned up stale container. Try to rename again.
11312                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11313                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11314                            + " inspite of cleaning it up.");
11315                    return false;
11316                }
11317            }
11318            if (!PackageHelper.isContainerMounted(newCacheId)) {
11319                Slog.w(TAG, "Mounting container " + newCacheId);
11320                newMountPath = PackageHelper.mountSdDir(newCacheId,
11321                        getEncryptKey(), Process.SYSTEM_UID);
11322            } else {
11323                newMountPath = PackageHelper.getSdDir(newCacheId);
11324            }
11325            if (newMountPath == null) {
11326                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11327                return false;
11328            }
11329            Log.i(TAG, "Succesfully renamed " + cid +
11330                    " to " + newCacheId +
11331                    " at new path: " + newMountPath);
11332            cid = newCacheId;
11333
11334            final File beforeCodeFile = new File(packagePath);
11335            setMountPath(newMountPath);
11336            final File afterCodeFile = new File(packagePath);
11337
11338            // Reflect the rename in scanned details
11339            pkg.codePath = afterCodeFile.getAbsolutePath();
11340            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11341                    pkg.baseCodePath);
11342            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11343                    pkg.splitCodePaths);
11344
11345            // Reflect the rename in app info
11346            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11347            pkg.applicationInfo.setCodePath(pkg.codePath);
11348            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11349            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11350            pkg.applicationInfo.setResourcePath(pkg.codePath);
11351            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11352            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11353
11354            return true;
11355        }
11356
11357        private void setMountPath(String mountPath) {
11358            final File mountFile = new File(mountPath);
11359
11360            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11361            if (monolithicFile.exists()) {
11362                packagePath = monolithicFile.getAbsolutePath();
11363                if (isFwdLocked()) {
11364                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11365                } else {
11366                    resourcePath = packagePath;
11367                }
11368            } else {
11369                packagePath = mountFile.getAbsolutePath();
11370                resourcePath = packagePath;
11371            }
11372        }
11373
11374        int doPostInstall(int status, int uid) {
11375            if (status != PackageManager.INSTALL_SUCCEEDED) {
11376                cleanUp();
11377            } else {
11378                final int groupOwner;
11379                final String protectedFile;
11380                if (isFwdLocked()) {
11381                    groupOwner = UserHandle.getSharedAppGid(uid);
11382                    protectedFile = RES_FILE_NAME;
11383                } else {
11384                    groupOwner = -1;
11385                    protectedFile = null;
11386                }
11387
11388                if (uid < Process.FIRST_APPLICATION_UID
11389                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11390                    Slog.e(TAG, "Failed to finalize " + cid);
11391                    PackageHelper.destroySdDir(cid);
11392                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11393                }
11394
11395                boolean mounted = PackageHelper.isContainerMounted(cid);
11396                if (!mounted) {
11397                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11398                }
11399            }
11400            return status;
11401        }
11402
11403        private void cleanUp() {
11404            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11405
11406            // Destroy secure container
11407            PackageHelper.destroySdDir(cid);
11408        }
11409
11410        private List<String> getAllCodePaths() {
11411            final File codeFile = new File(getCodePath());
11412            if (codeFile != null && codeFile.exists()) {
11413                try {
11414                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11415                    return pkg.getAllCodePaths();
11416                } catch (PackageParserException e) {
11417                    // Ignored; we tried our best
11418                }
11419            }
11420            return Collections.EMPTY_LIST;
11421        }
11422
11423        void cleanUpResourcesLI() {
11424            // Enumerate all code paths before deleting
11425            cleanUpResourcesLI(getAllCodePaths());
11426        }
11427
11428        private void cleanUpResourcesLI(List<String> allCodePaths) {
11429            cleanUp();
11430            removeDexFiles(allCodePaths, instructionSets);
11431        }
11432
11433        String getPackageName() {
11434            return getAsecPackageName(cid);
11435        }
11436
11437        boolean doPostDeleteLI(boolean delete) {
11438            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11439            final List<String> allCodePaths = getAllCodePaths();
11440            boolean mounted = PackageHelper.isContainerMounted(cid);
11441            if (mounted) {
11442                // Unmount first
11443                if (PackageHelper.unMountSdDir(cid)) {
11444                    mounted = false;
11445                }
11446            }
11447            if (!mounted && delete) {
11448                cleanUpResourcesLI(allCodePaths);
11449            }
11450            return !mounted;
11451        }
11452
11453        @Override
11454        int doPreCopy() {
11455            if (isFwdLocked()) {
11456                if (!PackageHelper.fixSdPermissions(cid,
11457                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11458                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11459                }
11460            }
11461
11462            return PackageManager.INSTALL_SUCCEEDED;
11463        }
11464
11465        @Override
11466        int doPostCopy(int uid) {
11467            if (isFwdLocked()) {
11468                if (uid < Process.FIRST_APPLICATION_UID
11469                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11470                                RES_FILE_NAME)) {
11471                    Slog.e(TAG, "Failed to finalize " + cid);
11472                    PackageHelper.destroySdDir(cid);
11473                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11474                }
11475            }
11476
11477            return PackageManager.INSTALL_SUCCEEDED;
11478        }
11479    }
11480
11481    /**
11482     * Logic to handle movement of existing installed applications.
11483     */
11484    class MoveInstallArgs extends InstallArgs {
11485        private File codeFile;
11486        private File resourceFile;
11487
11488        /** New install */
11489        MoveInstallArgs(InstallParams params) {
11490            super(params.origin, params.move, params.observer, params.installFlags,
11491                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11492                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11493                    params.grantedRuntimePermissions);
11494        }
11495
11496        int copyApk(IMediaContainerService imcs, boolean temp) {
11497            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11498                    + move.fromUuid + " to " + move.toUuid);
11499            synchronized (mInstaller) {
11500                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11501                        move.dataAppName, move.appId, move.seinfo) != 0) {
11502                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11503                }
11504            }
11505
11506            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11507            resourceFile = codeFile;
11508            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11509
11510            return PackageManager.INSTALL_SUCCEEDED;
11511        }
11512
11513        int doPreInstall(int status) {
11514            if (status != PackageManager.INSTALL_SUCCEEDED) {
11515                cleanUp(move.toUuid);
11516            }
11517            return status;
11518        }
11519
11520        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11521            if (status != PackageManager.INSTALL_SUCCEEDED) {
11522                cleanUp(move.toUuid);
11523                return false;
11524            }
11525
11526            // Reflect the move in app info
11527            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11528            pkg.applicationInfo.setCodePath(pkg.codePath);
11529            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11530            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11531            pkg.applicationInfo.setResourcePath(pkg.codePath);
11532            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11533            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11534
11535            return true;
11536        }
11537
11538        int doPostInstall(int status, int uid) {
11539            if (status == PackageManager.INSTALL_SUCCEEDED) {
11540                cleanUp(move.fromUuid);
11541            } else {
11542                cleanUp(move.toUuid);
11543            }
11544            return status;
11545        }
11546
11547        @Override
11548        String getCodePath() {
11549            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11550        }
11551
11552        @Override
11553        String getResourcePath() {
11554            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11555        }
11556
11557        private boolean cleanUp(String volumeUuid) {
11558            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11559                    move.dataAppName);
11560            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11561            synchronized (mInstallLock) {
11562                // Clean up both app data and code
11563                removeDataDirsLI(volumeUuid, move.packageName);
11564                if (codeFile.isDirectory()) {
11565                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11566                } else {
11567                    codeFile.delete();
11568                }
11569            }
11570            return true;
11571        }
11572
11573        void cleanUpResourcesLI() {
11574            throw new UnsupportedOperationException();
11575        }
11576
11577        boolean doPostDeleteLI(boolean delete) {
11578            throw new UnsupportedOperationException();
11579        }
11580    }
11581
11582    static String getAsecPackageName(String packageCid) {
11583        int idx = packageCid.lastIndexOf("-");
11584        if (idx == -1) {
11585            return packageCid;
11586        }
11587        return packageCid.substring(0, idx);
11588    }
11589
11590    // Utility method used to create code paths based on package name and available index.
11591    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11592        String idxStr = "";
11593        int idx = 1;
11594        // Fall back to default value of idx=1 if prefix is not
11595        // part of oldCodePath
11596        if (oldCodePath != null) {
11597            String subStr = oldCodePath;
11598            // Drop the suffix right away
11599            if (suffix != null && subStr.endsWith(suffix)) {
11600                subStr = subStr.substring(0, subStr.length() - suffix.length());
11601            }
11602            // If oldCodePath already contains prefix find out the
11603            // ending index to either increment or decrement.
11604            int sidx = subStr.lastIndexOf(prefix);
11605            if (sidx != -1) {
11606                subStr = subStr.substring(sidx + prefix.length());
11607                if (subStr != null) {
11608                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11609                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11610                    }
11611                    try {
11612                        idx = Integer.parseInt(subStr);
11613                        if (idx <= 1) {
11614                            idx++;
11615                        } else {
11616                            idx--;
11617                        }
11618                    } catch(NumberFormatException e) {
11619                    }
11620                }
11621            }
11622        }
11623        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11624        return prefix + idxStr;
11625    }
11626
11627    private File getNextCodePath(File targetDir, String packageName) {
11628        int suffix = 1;
11629        File result;
11630        do {
11631            result = new File(targetDir, packageName + "-" + suffix);
11632            suffix++;
11633        } while (result.exists());
11634        return result;
11635    }
11636
11637    // Utility method that returns the relative package path with respect
11638    // to the installation directory. Like say for /data/data/com.test-1.apk
11639    // string com.test-1 is returned.
11640    static String deriveCodePathName(String codePath) {
11641        if (codePath == null) {
11642            return null;
11643        }
11644        final File codeFile = new File(codePath);
11645        final String name = codeFile.getName();
11646        if (codeFile.isDirectory()) {
11647            return name;
11648        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11649            final int lastDot = name.lastIndexOf('.');
11650            return name.substring(0, lastDot);
11651        } else {
11652            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11653            return null;
11654        }
11655    }
11656
11657    class PackageInstalledInfo {
11658        String name;
11659        int uid;
11660        // The set of users that originally had this package installed.
11661        int[] origUsers;
11662        // The set of users that now have this package installed.
11663        int[] newUsers;
11664        PackageParser.Package pkg;
11665        int returnCode;
11666        String returnMsg;
11667        PackageRemovedInfo removedInfo;
11668
11669        public void setError(int code, String msg) {
11670            returnCode = code;
11671            returnMsg = msg;
11672            Slog.w(TAG, msg);
11673        }
11674
11675        public void setError(String msg, PackageParserException e) {
11676            returnCode = e.error;
11677            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11678            Slog.w(TAG, msg, e);
11679        }
11680
11681        public void setError(String msg, PackageManagerException e) {
11682            returnCode = e.error;
11683            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11684            Slog.w(TAG, msg, e);
11685        }
11686
11687        // In some error cases we want to convey more info back to the observer
11688        String origPackage;
11689        String origPermission;
11690    }
11691
11692    /*
11693     * Install a non-existing package.
11694     */
11695    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11696            UserHandle user, String installerPackageName, String volumeUuid,
11697            PackageInstalledInfo res) {
11698        // Remember this for later, in case we need to rollback this install
11699        String pkgName = pkg.packageName;
11700
11701        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11702        final boolean dataDirExists = Environment
11703                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11704        synchronized(mPackages) {
11705            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11706                // A package with the same name is already installed, though
11707                // it has been renamed to an older name.  The package we
11708                // are trying to install should be installed as an update to
11709                // the existing one, but that has not been requested, so bail.
11710                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11711                        + " without first uninstalling package running as "
11712                        + mSettings.mRenamedPackages.get(pkgName));
11713                return;
11714            }
11715            if (mPackages.containsKey(pkgName)) {
11716                // Don't allow installation over an existing package with the same name.
11717                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11718                        + " without first uninstalling.");
11719                return;
11720            }
11721        }
11722
11723        try {
11724            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11725                    System.currentTimeMillis(), user);
11726
11727            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11728            // delete the partially installed application. the data directory will have to be
11729            // restored if it was already existing
11730            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11731                // remove package from internal structures.  Note that we want deletePackageX to
11732                // delete the package data and cache directories that it created in
11733                // scanPackageLocked, unless those directories existed before we even tried to
11734                // install.
11735                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11736                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11737                                res.removedInfo, true);
11738            }
11739
11740        } catch (PackageManagerException e) {
11741            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11742        }
11743    }
11744
11745    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11746        // Can't rotate keys during boot or if sharedUser.
11747        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11748                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11749            return false;
11750        }
11751        // app is using upgradeKeySets; make sure all are valid
11752        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11753        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11754        for (int i = 0; i < upgradeKeySets.length; i++) {
11755            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11756                Slog.wtf(TAG, "Package "
11757                         + (oldPs.name != null ? oldPs.name : "<null>")
11758                         + " contains upgrade-key-set reference to unknown key-set: "
11759                         + upgradeKeySets[i]
11760                         + " reverting to signatures check.");
11761                return false;
11762            }
11763        }
11764        return true;
11765    }
11766
11767    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11768        // Upgrade keysets are being used.  Determine if new package has a superset of the
11769        // required keys.
11770        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11771        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11772        for (int i = 0; i < upgradeKeySets.length; i++) {
11773            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11774            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11775                return true;
11776            }
11777        }
11778        return false;
11779    }
11780
11781    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11782            UserHandle user, String installerPackageName, String volumeUuid,
11783            PackageInstalledInfo res) {
11784        final PackageParser.Package oldPackage;
11785        final String pkgName = pkg.packageName;
11786        final int[] allUsers;
11787        final boolean[] perUserInstalled;
11788
11789        // First find the old package info and check signatures
11790        synchronized(mPackages) {
11791            oldPackage = mPackages.get(pkgName);
11792            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11793            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11794            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11795                if(!checkUpgradeKeySetLP(ps, pkg)) {
11796                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11797                            "New package not signed by keys specified by upgrade-keysets: "
11798                            + pkgName);
11799                    return;
11800                }
11801            } else {
11802                // default to original signature matching
11803                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11804                    != PackageManager.SIGNATURE_MATCH) {
11805                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11806                            "New package has a different signature: " + pkgName);
11807                    return;
11808                }
11809            }
11810
11811            // In case of rollback, remember per-user/profile install state
11812            allUsers = sUserManager.getUserIds();
11813            perUserInstalled = new boolean[allUsers.length];
11814            for (int i = 0; i < allUsers.length; i++) {
11815                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11816            }
11817        }
11818
11819        boolean sysPkg = (isSystemApp(oldPackage));
11820        if (sysPkg) {
11821            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11822                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11823        } else {
11824            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11825                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11826        }
11827    }
11828
11829    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11830            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11831            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11832            String volumeUuid, PackageInstalledInfo res) {
11833        String pkgName = deletedPackage.packageName;
11834        boolean deletedPkg = true;
11835        boolean updatedSettings = false;
11836
11837        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11838                + deletedPackage);
11839        long origUpdateTime;
11840        if (pkg.mExtras != null) {
11841            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11842        } else {
11843            origUpdateTime = 0;
11844        }
11845
11846        // First delete the existing package while retaining the data directory
11847        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11848                res.removedInfo, true)) {
11849            // If the existing package wasn't successfully deleted
11850            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11851            deletedPkg = false;
11852        } else {
11853            // Successfully deleted the old package; proceed with replace.
11854
11855            // If deleted package lived in a container, give users a chance to
11856            // relinquish resources before killing.
11857            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11858                if (DEBUG_INSTALL) {
11859                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11860                }
11861                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11862                final ArrayList<String> pkgList = new ArrayList<String>(1);
11863                pkgList.add(deletedPackage.applicationInfo.packageName);
11864                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11865            }
11866
11867            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11868            try {
11869                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11870                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11871                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11872                        perUserInstalled, res, user);
11873                updatedSettings = true;
11874            } catch (PackageManagerException e) {
11875                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11876            }
11877        }
11878
11879        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11880            // remove package from internal structures.  Note that we want deletePackageX to
11881            // delete the package data and cache directories that it created in
11882            // scanPackageLocked, unless those directories existed before we even tried to
11883            // install.
11884            if(updatedSettings) {
11885                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11886                deletePackageLI(
11887                        pkgName, null, true, allUsers, perUserInstalled,
11888                        PackageManager.DELETE_KEEP_DATA,
11889                                res.removedInfo, true);
11890            }
11891            // Since we failed to install the new package we need to restore the old
11892            // package that we deleted.
11893            if (deletedPkg) {
11894                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11895                File restoreFile = new File(deletedPackage.codePath);
11896                // Parse old package
11897                boolean oldExternal = isExternal(deletedPackage);
11898                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11899                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11900                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11901                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11902                try {
11903                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11904                } catch (PackageManagerException e) {
11905                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11906                            + e.getMessage());
11907                    return;
11908                }
11909                // Restore of old package succeeded. Update permissions.
11910                // writer
11911                synchronized (mPackages) {
11912                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11913                            UPDATE_PERMISSIONS_ALL);
11914                    // can downgrade to reader
11915                    mSettings.writeLPr();
11916                }
11917                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11918            }
11919        }
11920    }
11921
11922    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11923            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11924            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11925            String volumeUuid, PackageInstalledInfo res) {
11926        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11927                + ", old=" + deletedPackage);
11928        boolean disabledSystem = false;
11929        boolean updatedSettings = false;
11930        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11931        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11932                != 0) {
11933            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11934        }
11935        String packageName = deletedPackage.packageName;
11936        if (packageName == null) {
11937            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11938                    "Attempt to delete null packageName.");
11939            return;
11940        }
11941        PackageParser.Package oldPkg;
11942        PackageSetting oldPkgSetting;
11943        // reader
11944        synchronized (mPackages) {
11945            oldPkg = mPackages.get(packageName);
11946            oldPkgSetting = mSettings.mPackages.get(packageName);
11947            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11948                    (oldPkgSetting == null)) {
11949                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11950                        "Couldn't find package:" + packageName + " information");
11951                return;
11952            }
11953        }
11954
11955        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11956
11957        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11958        res.removedInfo.removedPackage = packageName;
11959        // Remove existing system package
11960        removePackageLI(oldPkgSetting, true);
11961        // writer
11962        synchronized (mPackages) {
11963            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11964            if (!disabledSystem && deletedPackage != null) {
11965                // We didn't need to disable the .apk as a current system package,
11966                // which means we are replacing another update that is already
11967                // installed.  We need to make sure to delete the older one's .apk.
11968                res.removedInfo.args = createInstallArgsForExisting(0,
11969                        deletedPackage.applicationInfo.getCodePath(),
11970                        deletedPackage.applicationInfo.getResourcePath(),
11971                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11972            } else {
11973                res.removedInfo.args = null;
11974            }
11975        }
11976
11977        // Successfully disabled the old package. Now proceed with re-installation
11978        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11979
11980        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11981        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11982
11983        PackageParser.Package newPackage = null;
11984        try {
11985            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11986            if (newPackage.mExtras != null) {
11987                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11988                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11989                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11990
11991                // is the update attempting to change shared user? that isn't going to work...
11992                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11993                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11994                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11995                            + " to " + newPkgSetting.sharedUser);
11996                    updatedSettings = true;
11997                }
11998            }
11999
12000            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12001                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12002                        perUserInstalled, res, user);
12003                updatedSettings = true;
12004            }
12005
12006        } catch (PackageManagerException e) {
12007            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12008        }
12009
12010        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12011            // Re installation failed. Restore old information
12012            // Remove new pkg information
12013            if (newPackage != null) {
12014                removeInstalledPackageLI(newPackage, true);
12015            }
12016            // Add back the old system package
12017            try {
12018                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12019            } catch (PackageManagerException e) {
12020                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12021            }
12022            // Restore the old system information in Settings
12023            synchronized (mPackages) {
12024                if (disabledSystem) {
12025                    mSettings.enableSystemPackageLPw(packageName);
12026                }
12027                if (updatedSettings) {
12028                    mSettings.setInstallerPackageName(packageName,
12029                            oldPkgSetting.installerPackageName);
12030                }
12031                mSettings.writeLPr();
12032            }
12033        }
12034    }
12035
12036    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12037            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12038            UserHandle user) {
12039        String pkgName = newPackage.packageName;
12040        synchronized (mPackages) {
12041            //write settings. the installStatus will be incomplete at this stage.
12042            //note that the new package setting would have already been
12043            //added to mPackages. It hasn't been persisted yet.
12044            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12045            mSettings.writeLPr();
12046        }
12047
12048        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12049
12050        synchronized (mPackages) {
12051            updatePermissionsLPw(newPackage.packageName, newPackage,
12052                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12053                            ? UPDATE_PERMISSIONS_ALL : 0));
12054            // For system-bundled packages, we assume that installing an upgraded version
12055            // of the package implies that the user actually wants to run that new code,
12056            // so we enable the package.
12057            PackageSetting ps = mSettings.mPackages.get(pkgName);
12058            if (ps != null) {
12059                if (isSystemApp(newPackage)) {
12060                    // NB: implicit assumption that system package upgrades apply to all users
12061                    if (DEBUG_INSTALL) {
12062                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12063                    }
12064                    if (res.origUsers != null) {
12065                        for (int userHandle : res.origUsers) {
12066                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12067                                    userHandle, installerPackageName);
12068                        }
12069                    }
12070                    // Also convey the prior install/uninstall state
12071                    if (allUsers != null && perUserInstalled != null) {
12072                        for (int i = 0; i < allUsers.length; i++) {
12073                            if (DEBUG_INSTALL) {
12074                                Slog.d(TAG, "    user " + allUsers[i]
12075                                        + " => " + perUserInstalled[i]);
12076                            }
12077                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12078                        }
12079                        // these install state changes will be persisted in the
12080                        // upcoming call to mSettings.writeLPr().
12081                    }
12082                }
12083                // It's implied that when a user requests installation, they want the app to be
12084                // installed and enabled.
12085                int userId = user.getIdentifier();
12086                if (userId != UserHandle.USER_ALL) {
12087                    ps.setInstalled(true, userId);
12088                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12089                }
12090            }
12091            res.name = pkgName;
12092            res.uid = newPackage.applicationInfo.uid;
12093            res.pkg = newPackage;
12094            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12095            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12096            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12097            //to update install status
12098            mSettings.writeLPr();
12099        }
12100    }
12101
12102    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12103        final int installFlags = args.installFlags;
12104        final String installerPackageName = args.installerPackageName;
12105        final String volumeUuid = args.volumeUuid;
12106        final File tmpPackageFile = new File(args.getCodePath());
12107        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12108        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12109                || (args.volumeUuid != null));
12110        boolean replace = false;
12111        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12112        if (args.move != null) {
12113            // moving a complete application; perfom an initial scan on the new install location
12114            scanFlags |= SCAN_INITIAL;
12115        }
12116        // Result object to be returned
12117        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12118
12119        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12120        // Retrieve PackageSettings and parse package
12121        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12122                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12123                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12124        PackageParser pp = new PackageParser();
12125        pp.setSeparateProcesses(mSeparateProcesses);
12126        pp.setDisplayMetrics(mMetrics);
12127
12128        final PackageParser.Package pkg;
12129        try {
12130            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12131        } catch (PackageParserException e) {
12132            res.setError("Failed parse during installPackageLI", e);
12133            return;
12134        }
12135
12136        // Mark that we have an install time CPU ABI override.
12137        pkg.cpuAbiOverride = args.abiOverride;
12138
12139        String pkgName = res.name = pkg.packageName;
12140        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12141            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12142                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12143                return;
12144            }
12145        }
12146
12147        try {
12148            pp.collectCertificates(pkg, parseFlags);
12149            pp.collectManifestDigest(pkg);
12150        } catch (PackageParserException e) {
12151            res.setError("Failed collect during installPackageLI", e);
12152            return;
12153        }
12154
12155        /* If the installer passed in a manifest digest, compare it now. */
12156        if (args.manifestDigest != null) {
12157            if (DEBUG_INSTALL) {
12158                final String parsedManifest = pkg.manifestDigest == null ? "null"
12159                        : pkg.manifestDigest.toString();
12160                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12161                        + parsedManifest);
12162            }
12163
12164            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12165                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12166                return;
12167            }
12168        } else if (DEBUG_INSTALL) {
12169            final String parsedManifest = pkg.manifestDigest == null
12170                    ? "null" : pkg.manifestDigest.toString();
12171            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12172        }
12173
12174        // Get rid of all references to package scan path via parser.
12175        pp = null;
12176        String oldCodePath = null;
12177        boolean systemApp = false;
12178        synchronized (mPackages) {
12179            // Check if installing already existing package
12180            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12181                String oldName = mSettings.mRenamedPackages.get(pkgName);
12182                if (pkg.mOriginalPackages != null
12183                        && pkg.mOriginalPackages.contains(oldName)
12184                        && mPackages.containsKey(oldName)) {
12185                    // This package is derived from an original package,
12186                    // and this device has been updating from that original
12187                    // name.  We must continue using the original name, so
12188                    // rename the new package here.
12189                    pkg.setPackageName(oldName);
12190                    pkgName = pkg.packageName;
12191                    replace = true;
12192                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12193                            + oldName + " pkgName=" + pkgName);
12194                } else if (mPackages.containsKey(pkgName)) {
12195                    // This package, under its official name, already exists
12196                    // on the device; we should replace it.
12197                    replace = true;
12198                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12199                }
12200
12201                // Prevent apps opting out from runtime permissions
12202                if (replace) {
12203                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12204                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12205                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12206                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12207                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12208                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12209                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12210                                        + " doesn't support runtime permissions but the old"
12211                                        + " target SDK " + oldTargetSdk + " does.");
12212                        return;
12213                    }
12214                }
12215            }
12216
12217            PackageSetting ps = mSettings.mPackages.get(pkgName);
12218            if (ps != null) {
12219                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12220
12221                // Quick sanity check that we're signed correctly if updating;
12222                // we'll check this again later when scanning, but we want to
12223                // bail early here before tripping over redefined permissions.
12224                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12225                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12226                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12227                                + pkg.packageName + " upgrade keys do not match the "
12228                                + "previously installed version");
12229                        return;
12230                    }
12231                } else {
12232                    try {
12233                        verifySignaturesLP(ps, pkg);
12234                    } catch (PackageManagerException e) {
12235                        res.setError(e.error, e.getMessage());
12236                        return;
12237                    }
12238                }
12239
12240                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12241                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12242                    systemApp = (ps.pkg.applicationInfo.flags &
12243                            ApplicationInfo.FLAG_SYSTEM) != 0;
12244                }
12245                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12246            }
12247
12248            // Check whether the newly-scanned package wants to define an already-defined perm
12249            int N = pkg.permissions.size();
12250            for (int i = N-1; i >= 0; i--) {
12251                PackageParser.Permission perm = pkg.permissions.get(i);
12252                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12253                if (bp != null) {
12254                    // If the defining package is signed with our cert, it's okay.  This
12255                    // also includes the "updating the same package" case, of course.
12256                    // "updating same package" could also involve key-rotation.
12257                    final boolean sigsOk;
12258                    if (bp.sourcePackage.equals(pkg.packageName)
12259                            && (bp.packageSetting instanceof PackageSetting)
12260                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12261                                    scanFlags))) {
12262                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12263                    } else {
12264                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12265                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12266                    }
12267                    if (!sigsOk) {
12268                        // If the owning package is the system itself, we log but allow
12269                        // install to proceed; we fail the install on all other permission
12270                        // redefinitions.
12271                        if (!bp.sourcePackage.equals("android")) {
12272                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12273                                    + pkg.packageName + " attempting to redeclare permission "
12274                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12275                            res.origPermission = perm.info.name;
12276                            res.origPackage = bp.sourcePackage;
12277                            return;
12278                        } else {
12279                            Slog.w(TAG, "Package " + pkg.packageName
12280                                    + " attempting to redeclare system permission "
12281                                    + perm.info.name + "; ignoring new declaration");
12282                            pkg.permissions.remove(i);
12283                        }
12284                    }
12285                }
12286            }
12287
12288        }
12289
12290        if (systemApp && onExternal) {
12291            // Disable updates to system apps on sdcard
12292            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12293                    "Cannot install updates to system apps on sdcard");
12294            return;
12295        }
12296
12297        if (args.move != null) {
12298            // We did an in-place move, so dex is ready to roll
12299            scanFlags |= SCAN_NO_DEX;
12300            scanFlags |= SCAN_MOVE;
12301
12302            synchronized (mPackages) {
12303                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12304                if (ps == null) {
12305                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12306                            "Missing settings for moved package " + pkgName);
12307                }
12308
12309                // We moved the entire application as-is, so bring over the
12310                // previously derived ABI information.
12311                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12312                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12313            }
12314
12315        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12316            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12317            scanFlags |= SCAN_NO_DEX;
12318
12319            try {
12320                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12321                        true /* extract libs */);
12322            } catch (PackageManagerException pme) {
12323                Slog.e(TAG, "Error deriving application ABI", pme);
12324                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12325                return;
12326            }
12327
12328            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12329            int result = mPackageDexOptimizer
12330                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12331                            false /* defer */, false /* inclDependencies */);
12332            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12333                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12334                return;
12335            }
12336        }
12337
12338        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12339            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12340            return;
12341        }
12342
12343        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12344
12345        if (replace) {
12346            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12347                    installerPackageName, volumeUuid, res);
12348        } else {
12349            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12350                    args.user, installerPackageName, volumeUuid, res);
12351        }
12352        synchronized (mPackages) {
12353            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12354            if (ps != null) {
12355                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12356            }
12357        }
12358    }
12359
12360    private void startIntentFilterVerifications(int userId, boolean replacing,
12361            PackageParser.Package pkg) {
12362        if (mIntentFilterVerifierComponent == null) {
12363            Slog.w(TAG, "No IntentFilter verification will not be done as "
12364                    + "there is no IntentFilterVerifier available!");
12365            return;
12366        }
12367
12368        final int verifierUid = getPackageUid(
12369                mIntentFilterVerifierComponent.getPackageName(),
12370                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12371
12372        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12373        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12374        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12375        mHandler.sendMessage(msg);
12376    }
12377
12378    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12379            PackageParser.Package pkg) {
12380        int size = pkg.activities.size();
12381        if (size == 0) {
12382            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12383                    "No activity, so no need to verify any IntentFilter!");
12384            return;
12385        }
12386
12387        final boolean hasDomainURLs = hasDomainURLs(pkg);
12388        if (!hasDomainURLs) {
12389            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12390                    "No domain URLs, so no need to verify any IntentFilter!");
12391            return;
12392        }
12393
12394        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12395                + " if any IntentFilter from the " + size
12396                + " Activities needs verification ...");
12397
12398        int count = 0;
12399        final String packageName = pkg.packageName;
12400
12401        synchronized (mPackages) {
12402            // If this is a new install and we see that we've already run verification for this
12403            // package, we have nothing to do: it means the state was restored from backup.
12404            if (!replacing) {
12405                IntentFilterVerificationInfo ivi =
12406                        mSettings.getIntentFilterVerificationLPr(packageName);
12407                if (ivi != null) {
12408                    if (DEBUG_DOMAIN_VERIFICATION) {
12409                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12410                                + ivi.getStatusString());
12411                    }
12412                    return;
12413                }
12414            }
12415
12416            // If any filters need to be verified, then all need to be.
12417            boolean needToVerify = false;
12418            for (PackageParser.Activity a : pkg.activities) {
12419                for (ActivityIntentInfo filter : a.intents) {
12420                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12421                        if (DEBUG_DOMAIN_VERIFICATION) {
12422                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12423                        }
12424                        needToVerify = true;
12425                        break;
12426                    }
12427                }
12428            }
12429
12430            if (needToVerify) {
12431                final int verificationId = mIntentFilterVerificationToken++;
12432                for (PackageParser.Activity a : pkg.activities) {
12433                    for (ActivityIntentInfo filter : a.intents) {
12434                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12435                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12436                                    "Verification needed for IntentFilter:" + filter.toString());
12437                            mIntentFilterVerifier.addOneIntentFilterVerification(
12438                                    verifierUid, userId, verificationId, filter, packageName);
12439                            count++;
12440                        }
12441                    }
12442                }
12443            }
12444        }
12445
12446        if (count > 0) {
12447            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12448                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12449                    +  " for userId:" + userId);
12450            mIntentFilterVerifier.startVerifications(userId);
12451        } else {
12452            if (DEBUG_DOMAIN_VERIFICATION) {
12453                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12454            }
12455        }
12456    }
12457
12458    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12459        final ComponentName cn  = filter.activity.getComponentName();
12460        final String packageName = cn.getPackageName();
12461
12462        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12463                packageName);
12464        if (ivi == null) {
12465            return true;
12466        }
12467        int status = ivi.getStatus();
12468        switch (status) {
12469            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12470            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12471                return true;
12472
12473            default:
12474                // Nothing to do
12475                return false;
12476        }
12477    }
12478
12479    private static boolean isMultiArch(PackageSetting ps) {
12480        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12481    }
12482
12483    private static boolean isMultiArch(ApplicationInfo info) {
12484        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12485    }
12486
12487    private static boolean isExternal(PackageParser.Package pkg) {
12488        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12489    }
12490
12491    private static boolean isExternal(PackageSetting ps) {
12492        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12493    }
12494
12495    private static boolean isExternal(ApplicationInfo info) {
12496        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12497    }
12498
12499    private static boolean isSystemApp(PackageParser.Package pkg) {
12500        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12501    }
12502
12503    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12504        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12505    }
12506
12507    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12508        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12509    }
12510
12511    private static boolean isSystemApp(PackageSetting ps) {
12512        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12513    }
12514
12515    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12516        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12517    }
12518
12519    private int packageFlagsToInstallFlags(PackageSetting ps) {
12520        int installFlags = 0;
12521        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12522            // This existing package was an external ASEC install when we have
12523            // the external flag without a UUID
12524            installFlags |= PackageManager.INSTALL_EXTERNAL;
12525        }
12526        if (ps.isForwardLocked()) {
12527            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12528        }
12529        return installFlags;
12530    }
12531
12532    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12533        if (isExternal(pkg)) {
12534            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12535                return mSettings.getExternalVersion();
12536            } else {
12537                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12538            }
12539        } else {
12540            return mSettings.getInternalVersion();
12541        }
12542    }
12543
12544    private void deleteTempPackageFiles() {
12545        final FilenameFilter filter = new FilenameFilter() {
12546            public boolean accept(File dir, String name) {
12547                return name.startsWith("vmdl") && name.endsWith(".tmp");
12548            }
12549        };
12550        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12551            file.delete();
12552        }
12553    }
12554
12555    @Override
12556    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12557            int flags) {
12558        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12559                flags);
12560    }
12561
12562    @Override
12563    public void deletePackage(final String packageName,
12564            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12565        mContext.enforceCallingOrSelfPermission(
12566                android.Manifest.permission.DELETE_PACKAGES, null);
12567        Preconditions.checkNotNull(packageName);
12568        Preconditions.checkNotNull(observer);
12569        final int uid = Binder.getCallingUid();
12570        if (UserHandle.getUserId(uid) != userId) {
12571            mContext.enforceCallingPermission(
12572                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12573                    "deletePackage for user " + userId);
12574        }
12575        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12576            try {
12577                observer.onPackageDeleted(packageName,
12578                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12579            } catch (RemoteException re) {
12580            }
12581            return;
12582        }
12583
12584        boolean uninstallBlocked = false;
12585        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12586            int[] users = sUserManager.getUserIds();
12587            for (int i = 0; i < users.length; ++i) {
12588                if (getBlockUninstallForUser(packageName, users[i])) {
12589                    uninstallBlocked = true;
12590                    break;
12591                }
12592            }
12593        } else {
12594            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12595        }
12596        if (uninstallBlocked) {
12597            try {
12598                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12599                        null);
12600            } catch (RemoteException re) {
12601            }
12602            return;
12603        }
12604
12605        if (DEBUG_REMOVE) {
12606            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12607        }
12608        // Queue up an async operation since the package deletion may take a little while.
12609        mHandler.post(new Runnable() {
12610            public void run() {
12611                mHandler.removeCallbacks(this);
12612                final int returnCode = deletePackageX(packageName, userId, flags);
12613                if (observer != null) {
12614                    try {
12615                        observer.onPackageDeleted(packageName, returnCode, null);
12616                    } catch (RemoteException e) {
12617                        Log.i(TAG, "Observer no longer exists.");
12618                    } //end catch
12619                } //end if
12620            } //end run
12621        });
12622    }
12623
12624    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12625        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12626                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12627        try {
12628            if (dpm != null) {
12629                if (dpm.isDeviceOwner(packageName)) {
12630                    return true;
12631                }
12632                int[] users;
12633                if (userId == UserHandle.USER_ALL) {
12634                    users = sUserManager.getUserIds();
12635                } else {
12636                    users = new int[]{userId};
12637                }
12638                for (int i = 0; i < users.length; ++i) {
12639                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12640                        return true;
12641                    }
12642                }
12643            }
12644        } catch (RemoteException e) {
12645        }
12646        return false;
12647    }
12648
12649    /**
12650     *  This method is an internal method that could be get invoked either
12651     *  to delete an installed package or to clean up a failed installation.
12652     *  After deleting an installed package, a broadcast is sent to notify any
12653     *  listeners that the package has been installed. For cleaning up a failed
12654     *  installation, the broadcast is not necessary since the package's
12655     *  installation wouldn't have sent the initial broadcast either
12656     *  The key steps in deleting a package are
12657     *  deleting the package information in internal structures like mPackages,
12658     *  deleting the packages base directories through installd
12659     *  updating mSettings to reflect current status
12660     *  persisting settings for later use
12661     *  sending a broadcast if necessary
12662     */
12663    private int deletePackageX(String packageName, int userId, int flags) {
12664        final PackageRemovedInfo info = new PackageRemovedInfo();
12665        final boolean res;
12666
12667        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12668                ? UserHandle.ALL : new UserHandle(userId);
12669
12670        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12671            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12672            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12673        }
12674
12675        boolean removedForAllUsers = false;
12676        boolean systemUpdate = false;
12677
12678        // for the uninstall-updates case and restricted profiles, remember the per-
12679        // userhandle installed state
12680        int[] allUsers;
12681        boolean[] perUserInstalled;
12682        synchronized (mPackages) {
12683            PackageSetting ps = mSettings.mPackages.get(packageName);
12684            allUsers = sUserManager.getUserIds();
12685            perUserInstalled = new boolean[allUsers.length];
12686            for (int i = 0; i < allUsers.length; i++) {
12687                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12688            }
12689        }
12690
12691        synchronized (mInstallLock) {
12692            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12693            res = deletePackageLI(packageName, removeForUser,
12694                    true, allUsers, perUserInstalled,
12695                    flags | REMOVE_CHATTY, info, true);
12696            systemUpdate = info.isRemovedPackageSystemUpdate;
12697            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12698                removedForAllUsers = true;
12699            }
12700            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12701                    + " removedForAllUsers=" + removedForAllUsers);
12702        }
12703
12704        if (res) {
12705            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12706
12707            // If the removed package was a system update, the old system package
12708            // was re-enabled; we need to broadcast this information
12709            if (systemUpdate) {
12710                Bundle extras = new Bundle(1);
12711                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12712                        ? info.removedAppId : info.uid);
12713                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12714
12715                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12716                        extras, null, null, null);
12717                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12718                        extras, null, null, null);
12719                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12720                        null, packageName, null, null);
12721            }
12722        }
12723        // Force a gc here.
12724        Runtime.getRuntime().gc();
12725        // Delete the resources here after sending the broadcast to let
12726        // other processes clean up before deleting resources.
12727        if (info.args != null) {
12728            synchronized (mInstallLock) {
12729                info.args.doPostDeleteLI(true);
12730            }
12731        }
12732
12733        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12734    }
12735
12736    class PackageRemovedInfo {
12737        String removedPackage;
12738        int uid = -1;
12739        int removedAppId = -1;
12740        int[] removedUsers = null;
12741        boolean isRemovedPackageSystemUpdate = false;
12742        // Clean up resources deleted packages.
12743        InstallArgs args = null;
12744
12745        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12746            Bundle extras = new Bundle(1);
12747            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12748            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12749            if (replacing) {
12750                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12751            }
12752            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12753            if (removedPackage != null) {
12754                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12755                        extras, null, null, removedUsers);
12756                if (fullRemove && !replacing) {
12757                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12758                            extras, null, null, removedUsers);
12759                }
12760            }
12761            if (removedAppId >= 0) {
12762                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12763                        removedUsers);
12764            }
12765        }
12766    }
12767
12768    /*
12769     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12770     * flag is not set, the data directory is removed as well.
12771     * make sure this flag is set for partially installed apps. If not its meaningless to
12772     * delete a partially installed application.
12773     */
12774    private void removePackageDataLI(PackageSetting ps,
12775            int[] allUserHandles, boolean[] perUserInstalled,
12776            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12777        String packageName = ps.name;
12778        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12779        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12780        // Retrieve object to delete permissions for shared user later on
12781        final PackageSetting deletedPs;
12782        // reader
12783        synchronized (mPackages) {
12784            deletedPs = mSettings.mPackages.get(packageName);
12785            if (outInfo != null) {
12786                outInfo.removedPackage = packageName;
12787                outInfo.removedUsers = deletedPs != null
12788                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12789                        : null;
12790            }
12791        }
12792        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12793            removeDataDirsLI(ps.volumeUuid, packageName);
12794            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12795        }
12796        // writer
12797        synchronized (mPackages) {
12798            if (deletedPs != null) {
12799                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12800                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12801                    clearDefaultBrowserIfNeeded(packageName);
12802                    if (outInfo != null) {
12803                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12804                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12805                    }
12806                    updatePermissionsLPw(deletedPs.name, null, 0);
12807                    if (deletedPs.sharedUser != null) {
12808                        // Remove permissions associated with package. Since runtime
12809                        // permissions are per user we have to kill the removed package
12810                        // or packages running under the shared user of the removed
12811                        // package if revoking the permissions requested only by the removed
12812                        // package is successful and this causes a change in gids.
12813                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12814                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12815                                    userId);
12816                            if (userIdToKill == UserHandle.USER_ALL
12817                                    || userIdToKill >= UserHandle.USER_OWNER) {
12818                                // If gids changed for this user, kill all affected packages.
12819                                mHandler.post(new Runnable() {
12820                                    @Override
12821                                    public void run() {
12822                                        // This has to happen with no lock held.
12823                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12824                                                KILL_APP_REASON_GIDS_CHANGED);
12825                                    }
12826                                });
12827                                break;
12828                            }
12829                        }
12830                    }
12831                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12832                }
12833                // make sure to preserve per-user disabled state if this removal was just
12834                // a downgrade of a system app to the factory package
12835                if (allUserHandles != null && perUserInstalled != null) {
12836                    if (DEBUG_REMOVE) {
12837                        Slog.d(TAG, "Propagating install state across downgrade");
12838                    }
12839                    for (int i = 0; i < allUserHandles.length; i++) {
12840                        if (DEBUG_REMOVE) {
12841                            Slog.d(TAG, "    user " + allUserHandles[i]
12842                                    + " => " + perUserInstalled[i]);
12843                        }
12844                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12845                    }
12846                }
12847            }
12848            // can downgrade to reader
12849            if (writeSettings) {
12850                // Save settings now
12851                mSettings.writeLPr();
12852            }
12853        }
12854        if (outInfo != null) {
12855            // A user ID was deleted here. Go through all users and remove it
12856            // from KeyStore.
12857            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12858        }
12859    }
12860
12861    static boolean locationIsPrivileged(File path) {
12862        try {
12863            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12864                    .getCanonicalPath();
12865            return path.getCanonicalPath().startsWith(privilegedAppDir);
12866        } catch (IOException e) {
12867            Slog.e(TAG, "Unable to access code path " + path);
12868        }
12869        return false;
12870    }
12871
12872    /*
12873     * Tries to delete system package.
12874     */
12875    private boolean deleteSystemPackageLI(PackageSetting newPs,
12876            int[] allUserHandles, boolean[] perUserInstalled,
12877            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12878        final boolean applyUserRestrictions
12879                = (allUserHandles != null) && (perUserInstalled != null);
12880        PackageSetting disabledPs = null;
12881        // Confirm if the system package has been updated
12882        // An updated system app can be deleted. This will also have to restore
12883        // the system pkg from system partition
12884        // reader
12885        synchronized (mPackages) {
12886            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12887        }
12888        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12889                + " disabledPs=" + disabledPs);
12890        if (disabledPs == null) {
12891            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12892            return false;
12893        } else if (DEBUG_REMOVE) {
12894            Slog.d(TAG, "Deleting system pkg from data partition");
12895        }
12896        if (DEBUG_REMOVE) {
12897            if (applyUserRestrictions) {
12898                Slog.d(TAG, "Remembering install states:");
12899                for (int i = 0; i < allUserHandles.length; i++) {
12900                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12901                }
12902            }
12903        }
12904        // Delete the updated package
12905        outInfo.isRemovedPackageSystemUpdate = true;
12906        if (disabledPs.versionCode < newPs.versionCode) {
12907            // Delete data for downgrades
12908            flags &= ~PackageManager.DELETE_KEEP_DATA;
12909        } else {
12910            // Preserve data by setting flag
12911            flags |= PackageManager.DELETE_KEEP_DATA;
12912        }
12913        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12914                allUserHandles, perUserInstalled, outInfo, writeSettings);
12915        if (!ret) {
12916            return false;
12917        }
12918        // writer
12919        synchronized (mPackages) {
12920            // Reinstate the old system package
12921            mSettings.enableSystemPackageLPw(newPs.name);
12922            // Remove any native libraries from the upgraded package.
12923            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12924        }
12925        // Install the system package
12926        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12927        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12928        if (locationIsPrivileged(disabledPs.codePath)) {
12929            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12930        }
12931
12932        final PackageParser.Package newPkg;
12933        try {
12934            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12935        } catch (PackageManagerException e) {
12936            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12937            return false;
12938        }
12939
12940        // writer
12941        synchronized (mPackages) {
12942            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12943
12944            updatePermissionsLPw(newPkg.packageName, newPkg,
12945                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12946
12947            if (applyUserRestrictions) {
12948                if (DEBUG_REMOVE) {
12949                    Slog.d(TAG, "Propagating install state across reinstall");
12950                }
12951                for (int i = 0; i < allUserHandles.length; i++) {
12952                    if (DEBUG_REMOVE) {
12953                        Slog.d(TAG, "    user " + allUserHandles[i]
12954                                + " => " + perUserInstalled[i]);
12955                    }
12956                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12957
12958                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12959                }
12960                // Regardless of writeSettings we need to ensure that this restriction
12961                // state propagation is persisted
12962                mSettings.writeAllUsersPackageRestrictionsLPr();
12963            }
12964            // can downgrade to reader here
12965            if (writeSettings) {
12966                mSettings.writeLPr();
12967            }
12968        }
12969        return true;
12970    }
12971
12972    private boolean deleteInstalledPackageLI(PackageSetting ps,
12973            boolean deleteCodeAndResources, int flags,
12974            int[] allUserHandles, boolean[] perUserInstalled,
12975            PackageRemovedInfo outInfo, boolean writeSettings) {
12976        if (outInfo != null) {
12977            outInfo.uid = ps.appId;
12978        }
12979
12980        // Delete package data from internal structures and also remove data if flag is set
12981        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12982
12983        // Delete application code and resources
12984        if (deleteCodeAndResources && (outInfo != null)) {
12985            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12986                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12987            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12988        }
12989        return true;
12990    }
12991
12992    @Override
12993    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12994            int userId) {
12995        mContext.enforceCallingOrSelfPermission(
12996                android.Manifest.permission.DELETE_PACKAGES, null);
12997        synchronized (mPackages) {
12998            PackageSetting ps = mSettings.mPackages.get(packageName);
12999            if (ps == null) {
13000                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13001                return false;
13002            }
13003            if (!ps.getInstalled(userId)) {
13004                // Can't block uninstall for an app that is not installed or enabled.
13005                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13006                return false;
13007            }
13008            ps.setBlockUninstall(blockUninstall, userId);
13009            mSettings.writePackageRestrictionsLPr(userId);
13010        }
13011        return true;
13012    }
13013
13014    @Override
13015    public boolean getBlockUninstallForUser(String packageName, int userId) {
13016        synchronized (mPackages) {
13017            PackageSetting ps = mSettings.mPackages.get(packageName);
13018            if (ps == null) {
13019                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13020                return false;
13021            }
13022            return ps.getBlockUninstall(userId);
13023        }
13024    }
13025
13026    /*
13027     * This method handles package deletion in general
13028     */
13029    private boolean deletePackageLI(String packageName, UserHandle user,
13030            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13031            int flags, PackageRemovedInfo outInfo,
13032            boolean writeSettings) {
13033        if (packageName == null) {
13034            Slog.w(TAG, "Attempt to delete null packageName.");
13035            return false;
13036        }
13037        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13038        PackageSetting ps;
13039        boolean dataOnly = false;
13040        int removeUser = -1;
13041        int appId = -1;
13042        synchronized (mPackages) {
13043            ps = mSettings.mPackages.get(packageName);
13044            if (ps == null) {
13045                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13046                return false;
13047            }
13048            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13049                    && user.getIdentifier() != UserHandle.USER_ALL) {
13050                // The caller is asking that the package only be deleted for a single
13051                // user.  To do this, we just mark its uninstalled state and delete
13052                // its data.  If this is a system app, we only allow this to happen if
13053                // they have set the special DELETE_SYSTEM_APP which requests different
13054                // semantics than normal for uninstalling system apps.
13055                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13056                ps.setUserState(user.getIdentifier(),
13057                        COMPONENT_ENABLED_STATE_DEFAULT,
13058                        false, //installed
13059                        true,  //stopped
13060                        true,  //notLaunched
13061                        false, //hidden
13062                        null, null, null,
13063                        false, // blockUninstall
13064                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13065                if (!isSystemApp(ps)) {
13066                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13067                        // Other user still have this package installed, so all
13068                        // we need to do is clear this user's data and save that
13069                        // it is uninstalled.
13070                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13071                        removeUser = user.getIdentifier();
13072                        appId = ps.appId;
13073                        scheduleWritePackageRestrictionsLocked(removeUser);
13074                    } else {
13075                        // We need to set it back to 'installed' so the uninstall
13076                        // broadcasts will be sent correctly.
13077                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13078                        ps.setInstalled(true, user.getIdentifier());
13079                    }
13080                } else {
13081                    // This is a system app, so we assume that the
13082                    // other users still have this package installed, so all
13083                    // we need to do is clear this user's data and save that
13084                    // it is uninstalled.
13085                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13086                    removeUser = user.getIdentifier();
13087                    appId = ps.appId;
13088                    scheduleWritePackageRestrictionsLocked(removeUser);
13089                }
13090            }
13091        }
13092
13093        if (removeUser >= 0) {
13094            // From above, we determined that we are deleting this only
13095            // for a single user.  Continue the work here.
13096            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13097            if (outInfo != null) {
13098                outInfo.removedPackage = packageName;
13099                outInfo.removedAppId = appId;
13100                outInfo.removedUsers = new int[] {removeUser};
13101            }
13102            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13103            removeKeystoreDataIfNeeded(removeUser, appId);
13104            schedulePackageCleaning(packageName, removeUser, false);
13105            synchronized (mPackages) {
13106                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13107                    scheduleWritePackageRestrictionsLocked(removeUser);
13108                }
13109                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13110            }
13111            return true;
13112        }
13113
13114        if (dataOnly) {
13115            // Delete application data first
13116            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13117            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13118            return true;
13119        }
13120
13121        boolean ret = false;
13122        if (isSystemApp(ps)) {
13123            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13124            // When an updated system application is deleted we delete the existing resources as well and
13125            // fall back to existing code in system partition
13126            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13127                    flags, outInfo, writeSettings);
13128        } else {
13129            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13130            // Kill application pre-emptively especially for apps on sd.
13131            killApplication(packageName, ps.appId, "uninstall pkg");
13132            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13133                    allUserHandles, perUserInstalled,
13134                    outInfo, writeSettings);
13135        }
13136
13137        return ret;
13138    }
13139
13140    private final class ClearStorageConnection implements ServiceConnection {
13141        IMediaContainerService mContainerService;
13142
13143        @Override
13144        public void onServiceConnected(ComponentName name, IBinder service) {
13145            synchronized (this) {
13146                mContainerService = IMediaContainerService.Stub.asInterface(service);
13147                notifyAll();
13148            }
13149        }
13150
13151        @Override
13152        public void onServiceDisconnected(ComponentName name) {
13153        }
13154    }
13155
13156    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13157        final boolean mounted;
13158        if (Environment.isExternalStorageEmulated()) {
13159            mounted = true;
13160        } else {
13161            final String status = Environment.getExternalStorageState();
13162
13163            mounted = status.equals(Environment.MEDIA_MOUNTED)
13164                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13165        }
13166
13167        if (!mounted) {
13168            return;
13169        }
13170
13171        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13172        int[] users;
13173        if (userId == UserHandle.USER_ALL) {
13174            users = sUserManager.getUserIds();
13175        } else {
13176            users = new int[] { userId };
13177        }
13178        final ClearStorageConnection conn = new ClearStorageConnection();
13179        if (mContext.bindServiceAsUser(
13180                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13181            try {
13182                for (int curUser : users) {
13183                    long timeout = SystemClock.uptimeMillis() + 5000;
13184                    synchronized (conn) {
13185                        long now = SystemClock.uptimeMillis();
13186                        while (conn.mContainerService == null && now < timeout) {
13187                            try {
13188                                conn.wait(timeout - now);
13189                            } catch (InterruptedException e) {
13190                            }
13191                        }
13192                    }
13193                    if (conn.mContainerService == null) {
13194                        return;
13195                    }
13196
13197                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13198                    clearDirectory(conn.mContainerService,
13199                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13200                    if (allData) {
13201                        clearDirectory(conn.mContainerService,
13202                                userEnv.buildExternalStorageAppDataDirs(packageName));
13203                        clearDirectory(conn.mContainerService,
13204                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13205                    }
13206                }
13207            } finally {
13208                mContext.unbindService(conn);
13209            }
13210        }
13211    }
13212
13213    @Override
13214    public void clearApplicationUserData(final String packageName,
13215            final IPackageDataObserver observer, final int userId) {
13216        mContext.enforceCallingOrSelfPermission(
13217                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13218        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13219        // Queue up an async operation since the package deletion may take a little while.
13220        mHandler.post(new Runnable() {
13221            public void run() {
13222                mHandler.removeCallbacks(this);
13223                final boolean succeeded;
13224                synchronized (mInstallLock) {
13225                    succeeded = clearApplicationUserDataLI(packageName, userId);
13226                }
13227                clearExternalStorageDataSync(packageName, userId, true);
13228                if (succeeded) {
13229                    // invoke DeviceStorageMonitor's update method to clear any notifications
13230                    DeviceStorageMonitorInternal
13231                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13232                    if (dsm != null) {
13233                        dsm.checkMemory();
13234                    }
13235                }
13236                if(observer != null) {
13237                    try {
13238                        observer.onRemoveCompleted(packageName, succeeded);
13239                    } catch (RemoteException e) {
13240                        Log.i(TAG, "Observer no longer exists.");
13241                    }
13242                } //end if observer
13243            } //end run
13244        });
13245    }
13246
13247    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13248        if (packageName == null) {
13249            Slog.w(TAG, "Attempt to delete null packageName.");
13250            return false;
13251        }
13252
13253        // Try finding details about the requested package
13254        PackageParser.Package pkg;
13255        synchronized (mPackages) {
13256            pkg = mPackages.get(packageName);
13257            if (pkg == null) {
13258                final PackageSetting ps = mSettings.mPackages.get(packageName);
13259                if (ps != null) {
13260                    pkg = ps.pkg;
13261                }
13262            }
13263
13264            if (pkg == null) {
13265                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13266                return false;
13267            }
13268
13269            PackageSetting ps = (PackageSetting) pkg.mExtras;
13270            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13271        }
13272
13273        // Always delete data directories for package, even if we found no other
13274        // record of app. This helps users recover from UID mismatches without
13275        // resorting to a full data wipe.
13276        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13277        if (retCode < 0) {
13278            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13279            return false;
13280        }
13281
13282        final int appId = pkg.applicationInfo.uid;
13283        removeKeystoreDataIfNeeded(userId, appId);
13284
13285        // Create a native library symlink only if we have native libraries
13286        // and if the native libraries are 32 bit libraries. We do not provide
13287        // this symlink for 64 bit libraries.
13288        if (pkg.applicationInfo.primaryCpuAbi != null &&
13289                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13290            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13291            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13292                    nativeLibPath, userId) < 0) {
13293                Slog.w(TAG, "Failed linking native library dir");
13294                return false;
13295            }
13296        }
13297
13298        return true;
13299    }
13300
13301    /**
13302     * Reverts user permission state changes (permissions and flags) in
13303     * all packages for a given user.
13304     *
13305     * @param userId The device user for which to do a reset.
13306     */
13307    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13308        final int packageCount = mPackages.size();
13309        for (int i = 0; i < packageCount; i++) {
13310            PackageParser.Package pkg = mPackages.valueAt(i);
13311            PackageSetting ps = (PackageSetting) pkg.mExtras;
13312            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13313        }
13314    }
13315
13316    /**
13317     * Reverts user permission state changes (permissions and flags).
13318     *
13319     * @param ps The package for which to reset.
13320     * @param userId The device user for which to do a reset.
13321     */
13322    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13323            final PackageSetting ps, final int userId) {
13324        if (ps.pkg == null) {
13325            return;
13326        }
13327
13328        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13329                | FLAG_PERMISSION_USER_FIXED
13330                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13331
13332        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13333                | FLAG_PERMISSION_POLICY_FIXED;
13334
13335        boolean writeInstallPermissions = false;
13336        boolean writeRuntimePermissions = false;
13337
13338        final int permissionCount = ps.pkg.requestedPermissions.size();
13339        for (int i = 0; i < permissionCount; i++) {
13340            String permission = ps.pkg.requestedPermissions.get(i);
13341
13342            BasePermission bp = mSettings.mPermissions.get(permission);
13343            if (bp == null) {
13344                continue;
13345            }
13346
13347            // If shared user we just reset the state to which only this app contributed.
13348            if (ps.sharedUser != null) {
13349                boolean used = false;
13350                final int packageCount = ps.sharedUser.packages.size();
13351                for (int j = 0; j < packageCount; j++) {
13352                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13353                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13354                            && pkg.pkg.requestedPermissions.contains(permission)) {
13355                        used = true;
13356                        break;
13357                    }
13358                }
13359                if (used) {
13360                    continue;
13361                }
13362            }
13363
13364            PermissionsState permissionsState = ps.getPermissionsState();
13365
13366            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13367
13368            // Always clear the user settable flags.
13369            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13370                    bp.name) != null;
13371            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13372                if (hasInstallState) {
13373                    writeInstallPermissions = true;
13374                } else {
13375                    writeRuntimePermissions = true;
13376                }
13377            }
13378
13379            // Below is only runtime permission handling.
13380            if (!bp.isRuntime()) {
13381                continue;
13382            }
13383
13384            // Never clobber system or policy.
13385            if ((oldFlags & policyOrSystemFlags) != 0) {
13386                continue;
13387            }
13388
13389            // If this permission was granted by default, make sure it is.
13390            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13391                if (permissionsState.grantRuntimePermission(bp, userId)
13392                        != PERMISSION_OPERATION_FAILURE) {
13393                    writeRuntimePermissions = true;
13394                }
13395            } else {
13396                // Otherwise, reset the permission.
13397                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13398                switch (revokeResult) {
13399                    case PERMISSION_OPERATION_SUCCESS: {
13400                        writeRuntimePermissions = true;
13401                    } break;
13402
13403                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13404                        writeRuntimePermissions = true;
13405                        // If gids changed for this user, kill all affected packages.
13406                        mHandler.post(new Runnable() {
13407                            @Override
13408                            public void run() {
13409                                // This has to happen with no lock held.
13410                                killSettingPackagesForUser(ps, userId,
13411                                        KILL_APP_REASON_GIDS_CHANGED);
13412                            }
13413                        });
13414                    } break;
13415                }
13416            }
13417        }
13418
13419        // Synchronously write as we are taking permissions away.
13420        if (writeRuntimePermissions) {
13421            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13422        }
13423
13424        // Synchronously write as we are taking permissions away.
13425        if (writeInstallPermissions) {
13426            mSettings.writeLPr();
13427        }
13428    }
13429
13430    /**
13431     * Remove entries from the keystore daemon. Will only remove it if the
13432     * {@code appId} is valid.
13433     */
13434    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13435        if (appId < 0) {
13436            return;
13437        }
13438
13439        final KeyStore keyStore = KeyStore.getInstance();
13440        if (keyStore != null) {
13441            if (userId == UserHandle.USER_ALL) {
13442                for (final int individual : sUserManager.getUserIds()) {
13443                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13444                }
13445            } else {
13446                keyStore.clearUid(UserHandle.getUid(userId, appId));
13447            }
13448        } else {
13449            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13450        }
13451    }
13452
13453    @Override
13454    public void deleteApplicationCacheFiles(final String packageName,
13455            final IPackageDataObserver observer) {
13456        mContext.enforceCallingOrSelfPermission(
13457                android.Manifest.permission.DELETE_CACHE_FILES, null);
13458        // Queue up an async operation since the package deletion may take a little while.
13459        final int userId = UserHandle.getCallingUserId();
13460        mHandler.post(new Runnable() {
13461            public void run() {
13462                mHandler.removeCallbacks(this);
13463                final boolean succeded;
13464                synchronized (mInstallLock) {
13465                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13466                }
13467                clearExternalStorageDataSync(packageName, userId, false);
13468                if (observer != null) {
13469                    try {
13470                        observer.onRemoveCompleted(packageName, succeded);
13471                    } catch (RemoteException e) {
13472                        Log.i(TAG, "Observer no longer exists.");
13473                    }
13474                } //end if observer
13475            } //end run
13476        });
13477    }
13478
13479    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13480        if (packageName == null) {
13481            Slog.w(TAG, "Attempt to delete null packageName.");
13482            return false;
13483        }
13484        PackageParser.Package p;
13485        synchronized (mPackages) {
13486            p = mPackages.get(packageName);
13487        }
13488        if (p == null) {
13489            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13490            return false;
13491        }
13492        final ApplicationInfo applicationInfo = p.applicationInfo;
13493        if (applicationInfo == null) {
13494            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13495            return false;
13496        }
13497        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13498        if (retCode < 0) {
13499            Slog.w(TAG, "Couldn't remove cache files for package: "
13500                       + packageName + " u" + userId);
13501            return false;
13502        }
13503        return true;
13504    }
13505
13506    @Override
13507    public void getPackageSizeInfo(final String packageName, int userHandle,
13508            final IPackageStatsObserver observer) {
13509        mContext.enforceCallingOrSelfPermission(
13510                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13511        if (packageName == null) {
13512            throw new IllegalArgumentException("Attempt to get size of null packageName");
13513        }
13514
13515        PackageStats stats = new PackageStats(packageName, userHandle);
13516
13517        /*
13518         * Queue up an async operation since the package measurement may take a
13519         * little while.
13520         */
13521        Message msg = mHandler.obtainMessage(INIT_COPY);
13522        msg.obj = new MeasureParams(stats, observer);
13523        mHandler.sendMessage(msg);
13524    }
13525
13526    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13527            PackageStats pStats) {
13528        if (packageName == null) {
13529            Slog.w(TAG, "Attempt to get size of null packageName.");
13530            return false;
13531        }
13532        PackageParser.Package p;
13533        boolean dataOnly = false;
13534        String libDirRoot = null;
13535        String asecPath = null;
13536        PackageSetting ps = null;
13537        synchronized (mPackages) {
13538            p = mPackages.get(packageName);
13539            ps = mSettings.mPackages.get(packageName);
13540            if(p == null) {
13541                dataOnly = true;
13542                if((ps == null) || (ps.pkg == null)) {
13543                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13544                    return false;
13545                }
13546                p = ps.pkg;
13547            }
13548            if (ps != null) {
13549                libDirRoot = ps.legacyNativeLibraryPathString;
13550            }
13551            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13552                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13553                if (secureContainerId != null) {
13554                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13555                }
13556            }
13557        }
13558        String publicSrcDir = null;
13559        if(!dataOnly) {
13560            final ApplicationInfo applicationInfo = p.applicationInfo;
13561            if (applicationInfo == null) {
13562                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13563                return false;
13564            }
13565            if (p.isForwardLocked()) {
13566                publicSrcDir = applicationInfo.getBaseResourcePath();
13567            }
13568        }
13569        // TODO: extend to measure size of split APKs
13570        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13571        // not just the first level.
13572        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13573        // just the primary.
13574        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13575        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13576                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13577        if (res < 0) {
13578            return false;
13579        }
13580
13581        // Fix-up for forward-locked applications in ASEC containers.
13582        if (!isExternal(p)) {
13583            pStats.codeSize += pStats.externalCodeSize;
13584            pStats.externalCodeSize = 0L;
13585        }
13586
13587        return true;
13588    }
13589
13590
13591    @Override
13592    public void addPackageToPreferred(String packageName) {
13593        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13594    }
13595
13596    @Override
13597    public void removePackageFromPreferred(String packageName) {
13598        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13599    }
13600
13601    @Override
13602    public List<PackageInfo> getPreferredPackages(int flags) {
13603        return new ArrayList<PackageInfo>();
13604    }
13605
13606    private int getUidTargetSdkVersionLockedLPr(int uid) {
13607        Object obj = mSettings.getUserIdLPr(uid);
13608        if (obj instanceof SharedUserSetting) {
13609            final SharedUserSetting sus = (SharedUserSetting) obj;
13610            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13611            final Iterator<PackageSetting> it = sus.packages.iterator();
13612            while (it.hasNext()) {
13613                final PackageSetting ps = it.next();
13614                if (ps.pkg != null) {
13615                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13616                    if (v < vers) vers = v;
13617                }
13618            }
13619            return vers;
13620        } else if (obj instanceof PackageSetting) {
13621            final PackageSetting ps = (PackageSetting) obj;
13622            if (ps.pkg != null) {
13623                return ps.pkg.applicationInfo.targetSdkVersion;
13624            }
13625        }
13626        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13627    }
13628
13629    @Override
13630    public void addPreferredActivity(IntentFilter filter, int match,
13631            ComponentName[] set, ComponentName activity, int userId) {
13632        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13633                "Adding preferred");
13634    }
13635
13636    private void addPreferredActivityInternal(IntentFilter filter, int match,
13637            ComponentName[] set, ComponentName activity, boolean always, int userId,
13638            String opname) {
13639        // writer
13640        int callingUid = Binder.getCallingUid();
13641        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13642        if (filter.countActions() == 0) {
13643            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13644            return;
13645        }
13646        synchronized (mPackages) {
13647            if (mContext.checkCallingOrSelfPermission(
13648                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13649                    != PackageManager.PERMISSION_GRANTED) {
13650                if (getUidTargetSdkVersionLockedLPr(callingUid)
13651                        < Build.VERSION_CODES.FROYO) {
13652                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13653                            + callingUid);
13654                    return;
13655                }
13656                mContext.enforceCallingOrSelfPermission(
13657                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13658            }
13659
13660            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13661            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13662                    + userId + ":");
13663            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13664            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13665            scheduleWritePackageRestrictionsLocked(userId);
13666        }
13667    }
13668
13669    @Override
13670    public void replacePreferredActivity(IntentFilter filter, int match,
13671            ComponentName[] set, ComponentName activity, int userId) {
13672        if (filter.countActions() != 1) {
13673            throw new IllegalArgumentException(
13674                    "replacePreferredActivity expects filter to have only 1 action.");
13675        }
13676        if (filter.countDataAuthorities() != 0
13677                || filter.countDataPaths() != 0
13678                || filter.countDataSchemes() > 1
13679                || filter.countDataTypes() != 0) {
13680            throw new IllegalArgumentException(
13681                    "replacePreferredActivity expects filter to have no data authorities, " +
13682                    "paths, or types; and at most one scheme.");
13683        }
13684
13685        final int callingUid = Binder.getCallingUid();
13686        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13687        synchronized (mPackages) {
13688            if (mContext.checkCallingOrSelfPermission(
13689                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13690                    != PackageManager.PERMISSION_GRANTED) {
13691                if (getUidTargetSdkVersionLockedLPr(callingUid)
13692                        < Build.VERSION_CODES.FROYO) {
13693                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13694                            + Binder.getCallingUid());
13695                    return;
13696                }
13697                mContext.enforceCallingOrSelfPermission(
13698                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13699            }
13700
13701            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13702            if (pir != null) {
13703                // Get all of the existing entries that exactly match this filter.
13704                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13705                if (existing != null && existing.size() == 1) {
13706                    PreferredActivity cur = existing.get(0);
13707                    if (DEBUG_PREFERRED) {
13708                        Slog.i(TAG, "Checking replace of preferred:");
13709                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13710                        if (!cur.mPref.mAlways) {
13711                            Slog.i(TAG, "  -- CUR; not mAlways!");
13712                        } else {
13713                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13714                            Slog.i(TAG, "  -- CUR: mSet="
13715                                    + Arrays.toString(cur.mPref.mSetComponents));
13716                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13717                            Slog.i(TAG, "  -- NEW: mMatch="
13718                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13719                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13720                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13721                        }
13722                    }
13723                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13724                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13725                            && cur.mPref.sameSet(set)) {
13726                        // Setting the preferred activity to what it happens to be already
13727                        if (DEBUG_PREFERRED) {
13728                            Slog.i(TAG, "Replacing with same preferred activity "
13729                                    + cur.mPref.mShortComponent + " for user "
13730                                    + userId + ":");
13731                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13732                        }
13733                        return;
13734                    }
13735                }
13736
13737                if (existing != null) {
13738                    if (DEBUG_PREFERRED) {
13739                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13740                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13741                    }
13742                    for (int i = 0; i < existing.size(); i++) {
13743                        PreferredActivity pa = existing.get(i);
13744                        if (DEBUG_PREFERRED) {
13745                            Slog.i(TAG, "Removing existing preferred activity "
13746                                    + pa.mPref.mComponent + ":");
13747                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13748                        }
13749                        pir.removeFilter(pa);
13750                    }
13751                }
13752            }
13753            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13754                    "Replacing preferred");
13755        }
13756    }
13757
13758    @Override
13759    public void clearPackagePreferredActivities(String packageName) {
13760        final int uid = Binder.getCallingUid();
13761        // writer
13762        synchronized (mPackages) {
13763            PackageParser.Package pkg = mPackages.get(packageName);
13764            if (pkg == null || pkg.applicationInfo.uid != uid) {
13765                if (mContext.checkCallingOrSelfPermission(
13766                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13767                        != PackageManager.PERMISSION_GRANTED) {
13768                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13769                            < Build.VERSION_CODES.FROYO) {
13770                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13771                                + Binder.getCallingUid());
13772                        return;
13773                    }
13774                    mContext.enforceCallingOrSelfPermission(
13775                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13776                }
13777            }
13778
13779            int user = UserHandle.getCallingUserId();
13780            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13781                scheduleWritePackageRestrictionsLocked(user);
13782            }
13783        }
13784    }
13785
13786    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13787    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13788        ArrayList<PreferredActivity> removed = null;
13789        boolean changed = false;
13790        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13791            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13792            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13793            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13794                continue;
13795            }
13796            Iterator<PreferredActivity> it = pir.filterIterator();
13797            while (it.hasNext()) {
13798                PreferredActivity pa = it.next();
13799                // Mark entry for removal only if it matches the package name
13800                // and the entry is of type "always".
13801                if (packageName == null ||
13802                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13803                                && pa.mPref.mAlways)) {
13804                    if (removed == null) {
13805                        removed = new ArrayList<PreferredActivity>();
13806                    }
13807                    removed.add(pa);
13808                }
13809            }
13810            if (removed != null) {
13811                for (int j=0; j<removed.size(); j++) {
13812                    PreferredActivity pa = removed.get(j);
13813                    pir.removeFilter(pa);
13814                }
13815                changed = true;
13816            }
13817        }
13818        return changed;
13819    }
13820
13821    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13822    private void clearIntentFilterVerificationsLPw(int userId) {
13823        final int packageCount = mPackages.size();
13824        for (int i = 0; i < packageCount; i++) {
13825            PackageParser.Package pkg = mPackages.valueAt(i);
13826            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13827        }
13828    }
13829
13830    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13831    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13832        if (userId == UserHandle.USER_ALL) {
13833            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13834                    sUserManager.getUserIds())) {
13835                for (int oneUserId : sUserManager.getUserIds()) {
13836                    scheduleWritePackageRestrictionsLocked(oneUserId);
13837                }
13838            }
13839        } else {
13840            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13841                scheduleWritePackageRestrictionsLocked(userId);
13842            }
13843        }
13844    }
13845
13846    void clearDefaultBrowserIfNeeded(String packageName) {
13847        for (int oneUserId : sUserManager.getUserIds()) {
13848            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13849            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13850            if (packageName.equals(defaultBrowserPackageName)) {
13851                setDefaultBrowserPackageName(null, oneUserId);
13852            }
13853        }
13854    }
13855
13856    @Override
13857    public void resetApplicationPreferences(int userId) {
13858        mContext.enforceCallingOrSelfPermission(
13859                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13860        // writer
13861        synchronized (mPackages) {
13862            final long identity = Binder.clearCallingIdentity();
13863            try {
13864                clearPackagePreferredActivitiesLPw(null, userId);
13865                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13866                // TODO: We have to reset the default SMS and Phone. This requires
13867                // significant refactoring to keep all default apps in the package
13868                // manager (cleaner but more work) or have the services provide
13869                // callbacks to the package manager to request a default app reset.
13870                applyFactoryDefaultBrowserLPw(userId);
13871                clearIntentFilterVerificationsLPw(userId);
13872                primeDomainVerificationsLPw(userId);
13873                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13874                scheduleWritePackageRestrictionsLocked(userId);
13875            } finally {
13876                Binder.restoreCallingIdentity(identity);
13877            }
13878        }
13879    }
13880
13881    @Override
13882    public int getPreferredActivities(List<IntentFilter> outFilters,
13883            List<ComponentName> outActivities, String packageName) {
13884
13885        int num = 0;
13886        final int userId = UserHandle.getCallingUserId();
13887        // reader
13888        synchronized (mPackages) {
13889            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13890            if (pir != null) {
13891                final Iterator<PreferredActivity> it = pir.filterIterator();
13892                while (it.hasNext()) {
13893                    final PreferredActivity pa = it.next();
13894                    if (packageName == null
13895                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13896                                    && pa.mPref.mAlways)) {
13897                        if (outFilters != null) {
13898                            outFilters.add(new IntentFilter(pa));
13899                        }
13900                        if (outActivities != null) {
13901                            outActivities.add(pa.mPref.mComponent);
13902                        }
13903                    }
13904                }
13905            }
13906        }
13907
13908        return num;
13909    }
13910
13911    @Override
13912    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13913            int userId) {
13914        int callingUid = Binder.getCallingUid();
13915        if (callingUid != Process.SYSTEM_UID) {
13916            throw new SecurityException(
13917                    "addPersistentPreferredActivity can only be run by the system");
13918        }
13919        if (filter.countActions() == 0) {
13920            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13921            return;
13922        }
13923        synchronized (mPackages) {
13924            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13925                    " :");
13926            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13927            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13928                    new PersistentPreferredActivity(filter, activity));
13929            scheduleWritePackageRestrictionsLocked(userId);
13930        }
13931    }
13932
13933    @Override
13934    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13935        int callingUid = Binder.getCallingUid();
13936        if (callingUid != Process.SYSTEM_UID) {
13937            throw new SecurityException(
13938                    "clearPackagePersistentPreferredActivities can only be run by the system");
13939        }
13940        ArrayList<PersistentPreferredActivity> removed = null;
13941        boolean changed = false;
13942        synchronized (mPackages) {
13943            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13944                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13945                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13946                        .valueAt(i);
13947                if (userId != thisUserId) {
13948                    continue;
13949                }
13950                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13951                while (it.hasNext()) {
13952                    PersistentPreferredActivity ppa = it.next();
13953                    // Mark entry for removal only if it matches the package name.
13954                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13955                        if (removed == null) {
13956                            removed = new ArrayList<PersistentPreferredActivity>();
13957                        }
13958                        removed.add(ppa);
13959                    }
13960                }
13961                if (removed != null) {
13962                    for (int j=0; j<removed.size(); j++) {
13963                        PersistentPreferredActivity ppa = removed.get(j);
13964                        ppir.removeFilter(ppa);
13965                    }
13966                    changed = true;
13967                }
13968            }
13969
13970            if (changed) {
13971                scheduleWritePackageRestrictionsLocked(userId);
13972            }
13973        }
13974    }
13975
13976    /**
13977     * Common machinery for picking apart a restored XML blob and passing
13978     * it to a caller-supplied functor to be applied to the running system.
13979     */
13980    private void restoreFromXml(XmlPullParser parser, int userId,
13981            String expectedStartTag, BlobXmlRestorer functor)
13982            throws IOException, XmlPullParserException {
13983        int type;
13984        while ((type = parser.next()) != XmlPullParser.START_TAG
13985                && type != XmlPullParser.END_DOCUMENT) {
13986        }
13987        if (type != XmlPullParser.START_TAG) {
13988            // oops didn't find a start tag?!
13989            if (DEBUG_BACKUP) {
13990                Slog.e(TAG, "Didn't find start tag during restore");
13991            }
13992            return;
13993        }
13994
13995        // this is supposed to be TAG_PREFERRED_BACKUP
13996        if (!expectedStartTag.equals(parser.getName())) {
13997            if (DEBUG_BACKUP) {
13998                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13999            }
14000            return;
14001        }
14002
14003        // skip interfering stuff, then we're aligned with the backing implementation
14004        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14005        functor.apply(parser, userId);
14006    }
14007
14008    private interface BlobXmlRestorer {
14009        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14010    }
14011
14012    /**
14013     * Non-Binder method, support for the backup/restore mechanism: write the
14014     * full set of preferred activities in its canonical XML format.  Returns the
14015     * XML output as a byte array, or null if there is none.
14016     */
14017    @Override
14018    public byte[] getPreferredActivityBackup(int userId) {
14019        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14020            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14021        }
14022
14023        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14024        try {
14025            final XmlSerializer serializer = new FastXmlSerializer();
14026            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14027            serializer.startDocument(null, true);
14028            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14029
14030            synchronized (mPackages) {
14031                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14032            }
14033
14034            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14035            serializer.endDocument();
14036            serializer.flush();
14037        } catch (Exception e) {
14038            if (DEBUG_BACKUP) {
14039                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14040            }
14041            return null;
14042        }
14043
14044        return dataStream.toByteArray();
14045    }
14046
14047    @Override
14048    public void restorePreferredActivities(byte[] backup, int userId) {
14049        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14050            throw new SecurityException("Only the system may call restorePreferredActivities()");
14051        }
14052
14053        try {
14054            final XmlPullParser parser = Xml.newPullParser();
14055            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14056            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14057                    new BlobXmlRestorer() {
14058                        @Override
14059                        public void apply(XmlPullParser parser, int userId)
14060                                throws XmlPullParserException, IOException {
14061                            synchronized (mPackages) {
14062                                mSettings.readPreferredActivitiesLPw(parser, userId);
14063                            }
14064                        }
14065                    } );
14066        } catch (Exception e) {
14067            if (DEBUG_BACKUP) {
14068                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14069            }
14070        }
14071    }
14072
14073    /**
14074     * Non-Binder method, support for the backup/restore mechanism: write the
14075     * default browser (etc) settings in its canonical XML format.  Returns the default
14076     * browser XML representation as a byte array, or null if there is none.
14077     */
14078    @Override
14079    public byte[] getDefaultAppsBackup(int userId) {
14080        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14081            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14082        }
14083
14084        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14085        try {
14086            final XmlSerializer serializer = new FastXmlSerializer();
14087            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14088            serializer.startDocument(null, true);
14089            serializer.startTag(null, TAG_DEFAULT_APPS);
14090
14091            synchronized (mPackages) {
14092                mSettings.writeDefaultAppsLPr(serializer, userId);
14093            }
14094
14095            serializer.endTag(null, TAG_DEFAULT_APPS);
14096            serializer.endDocument();
14097            serializer.flush();
14098        } catch (Exception e) {
14099            if (DEBUG_BACKUP) {
14100                Slog.e(TAG, "Unable to write default apps for backup", e);
14101            }
14102            return null;
14103        }
14104
14105        return dataStream.toByteArray();
14106    }
14107
14108    @Override
14109    public void restoreDefaultApps(byte[] backup, int userId) {
14110        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14111            throw new SecurityException("Only the system may call restoreDefaultApps()");
14112        }
14113
14114        try {
14115            final XmlPullParser parser = Xml.newPullParser();
14116            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14117            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14118                    new BlobXmlRestorer() {
14119                        @Override
14120                        public void apply(XmlPullParser parser, int userId)
14121                                throws XmlPullParserException, IOException {
14122                            synchronized (mPackages) {
14123                                mSettings.readDefaultAppsLPw(parser, userId);
14124                            }
14125                        }
14126                    } );
14127        } catch (Exception e) {
14128            if (DEBUG_BACKUP) {
14129                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14130            }
14131        }
14132    }
14133
14134    @Override
14135    public byte[] getIntentFilterVerificationBackup(int userId) {
14136        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14137            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14138        }
14139
14140        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14141        try {
14142            final XmlSerializer serializer = new FastXmlSerializer();
14143            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14144            serializer.startDocument(null, true);
14145            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14146
14147            synchronized (mPackages) {
14148                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14149            }
14150
14151            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14152            serializer.endDocument();
14153            serializer.flush();
14154        } catch (Exception e) {
14155            if (DEBUG_BACKUP) {
14156                Slog.e(TAG, "Unable to write default apps for backup", e);
14157            }
14158            return null;
14159        }
14160
14161        return dataStream.toByteArray();
14162    }
14163
14164    @Override
14165    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14166        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14167            throw new SecurityException("Only the system may call restorePreferredActivities()");
14168        }
14169
14170        try {
14171            final XmlPullParser parser = Xml.newPullParser();
14172            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14173            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14174                    new BlobXmlRestorer() {
14175                        @Override
14176                        public void apply(XmlPullParser parser, int userId)
14177                                throws XmlPullParserException, IOException {
14178                            synchronized (mPackages) {
14179                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14180                                mSettings.writeLPr();
14181                            }
14182                        }
14183                    } );
14184        } catch (Exception e) {
14185            if (DEBUG_BACKUP) {
14186                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14187            }
14188        }
14189    }
14190
14191    @Override
14192    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14193            int sourceUserId, int targetUserId, int flags) {
14194        mContext.enforceCallingOrSelfPermission(
14195                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14196        int callingUid = Binder.getCallingUid();
14197        enforceOwnerRights(ownerPackage, callingUid);
14198        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14199        if (intentFilter.countActions() == 0) {
14200            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14201            return;
14202        }
14203        synchronized (mPackages) {
14204            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14205                    ownerPackage, targetUserId, flags);
14206            CrossProfileIntentResolver resolver =
14207                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14208            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14209            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14210            if (existing != null) {
14211                int size = existing.size();
14212                for (int i = 0; i < size; i++) {
14213                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14214                        return;
14215                    }
14216                }
14217            }
14218            resolver.addFilter(newFilter);
14219            scheduleWritePackageRestrictionsLocked(sourceUserId);
14220        }
14221    }
14222
14223    @Override
14224    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14225        mContext.enforceCallingOrSelfPermission(
14226                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14227        int callingUid = Binder.getCallingUid();
14228        enforceOwnerRights(ownerPackage, callingUid);
14229        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14230        synchronized (mPackages) {
14231            CrossProfileIntentResolver resolver =
14232                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14233            ArraySet<CrossProfileIntentFilter> set =
14234                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14235            for (CrossProfileIntentFilter filter : set) {
14236                if (filter.getOwnerPackage().equals(ownerPackage)) {
14237                    resolver.removeFilter(filter);
14238                }
14239            }
14240            scheduleWritePackageRestrictionsLocked(sourceUserId);
14241        }
14242    }
14243
14244    // Enforcing that callingUid is owning pkg on userId
14245    private void enforceOwnerRights(String pkg, int callingUid) {
14246        // The system owns everything.
14247        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14248            return;
14249        }
14250        int callingUserId = UserHandle.getUserId(callingUid);
14251        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14252        if (pi == null) {
14253            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14254                    + callingUserId);
14255        }
14256        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14257            throw new SecurityException("Calling uid " + callingUid
14258                    + " does not own package " + pkg);
14259        }
14260    }
14261
14262    @Override
14263    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14264        Intent intent = new Intent(Intent.ACTION_MAIN);
14265        intent.addCategory(Intent.CATEGORY_HOME);
14266
14267        final int callingUserId = UserHandle.getCallingUserId();
14268        List<ResolveInfo> list = queryIntentActivities(intent, null,
14269                PackageManager.GET_META_DATA, callingUserId);
14270        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14271                true, false, false, callingUserId);
14272
14273        allHomeCandidates.clear();
14274        if (list != null) {
14275            for (ResolveInfo ri : list) {
14276                allHomeCandidates.add(ri);
14277            }
14278        }
14279        return (preferred == null || preferred.activityInfo == null)
14280                ? null
14281                : new ComponentName(preferred.activityInfo.packageName,
14282                        preferred.activityInfo.name);
14283    }
14284
14285    @Override
14286    public void setApplicationEnabledSetting(String appPackageName,
14287            int newState, int flags, int userId, String callingPackage) {
14288        if (!sUserManager.exists(userId)) return;
14289        if (callingPackage == null) {
14290            callingPackage = Integer.toString(Binder.getCallingUid());
14291        }
14292        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14293    }
14294
14295    @Override
14296    public void setComponentEnabledSetting(ComponentName componentName,
14297            int newState, int flags, int userId) {
14298        if (!sUserManager.exists(userId)) return;
14299        setEnabledSetting(componentName.getPackageName(),
14300                componentName.getClassName(), newState, flags, userId, null);
14301    }
14302
14303    private void setEnabledSetting(final String packageName, String className, int newState,
14304            final int flags, int userId, String callingPackage) {
14305        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14306              || newState == COMPONENT_ENABLED_STATE_ENABLED
14307              || newState == COMPONENT_ENABLED_STATE_DISABLED
14308              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14309              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14310            throw new IllegalArgumentException("Invalid new component state: "
14311                    + newState);
14312        }
14313        PackageSetting pkgSetting;
14314        final int uid = Binder.getCallingUid();
14315        final int permission = mContext.checkCallingOrSelfPermission(
14316                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14317        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14318        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14319        boolean sendNow = false;
14320        boolean isApp = (className == null);
14321        String componentName = isApp ? packageName : className;
14322        int packageUid = -1;
14323        ArrayList<String> components;
14324
14325        // writer
14326        synchronized (mPackages) {
14327            pkgSetting = mSettings.mPackages.get(packageName);
14328            if (pkgSetting == null) {
14329                if (className == null) {
14330                    throw new IllegalArgumentException(
14331                            "Unknown package: " + packageName);
14332                }
14333                throw new IllegalArgumentException(
14334                        "Unknown component: " + packageName
14335                        + "/" + className);
14336            }
14337            // Allow root and verify that userId is not being specified by a different user
14338            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14339                throw new SecurityException(
14340                        "Permission Denial: attempt to change component state from pid="
14341                        + Binder.getCallingPid()
14342                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14343            }
14344            if (className == null) {
14345                // We're dealing with an application/package level state change
14346                if (pkgSetting.getEnabled(userId) == newState) {
14347                    // Nothing to do
14348                    return;
14349                }
14350                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14351                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14352                    // Don't care about who enables an app.
14353                    callingPackage = null;
14354                }
14355                pkgSetting.setEnabled(newState, userId, callingPackage);
14356                // pkgSetting.pkg.mSetEnabled = newState;
14357            } else {
14358                // We're dealing with a component level state change
14359                // First, verify that this is a valid class name.
14360                PackageParser.Package pkg = pkgSetting.pkg;
14361                if (pkg == null || !pkg.hasComponentClassName(className)) {
14362                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14363                        throw new IllegalArgumentException("Component class " + className
14364                                + " does not exist in " + packageName);
14365                    } else {
14366                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14367                                + className + " does not exist in " + packageName);
14368                    }
14369                }
14370                switch (newState) {
14371                case COMPONENT_ENABLED_STATE_ENABLED:
14372                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14373                        return;
14374                    }
14375                    break;
14376                case COMPONENT_ENABLED_STATE_DISABLED:
14377                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14378                        return;
14379                    }
14380                    break;
14381                case COMPONENT_ENABLED_STATE_DEFAULT:
14382                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14383                        return;
14384                    }
14385                    break;
14386                default:
14387                    Slog.e(TAG, "Invalid new component state: " + newState);
14388                    return;
14389                }
14390            }
14391            scheduleWritePackageRestrictionsLocked(userId);
14392            components = mPendingBroadcasts.get(userId, packageName);
14393            final boolean newPackage = components == null;
14394            if (newPackage) {
14395                components = new ArrayList<String>();
14396            }
14397            if (!components.contains(componentName)) {
14398                components.add(componentName);
14399            }
14400            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14401                sendNow = true;
14402                // Purge entry from pending broadcast list if another one exists already
14403                // since we are sending one right away.
14404                mPendingBroadcasts.remove(userId, packageName);
14405            } else {
14406                if (newPackage) {
14407                    mPendingBroadcasts.put(userId, packageName, components);
14408                }
14409                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14410                    // Schedule a message
14411                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14412                }
14413            }
14414        }
14415
14416        long callingId = Binder.clearCallingIdentity();
14417        try {
14418            if (sendNow) {
14419                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14420                sendPackageChangedBroadcast(packageName,
14421                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14422            }
14423        } finally {
14424            Binder.restoreCallingIdentity(callingId);
14425        }
14426    }
14427
14428    private void sendPackageChangedBroadcast(String packageName,
14429            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14430        if (DEBUG_INSTALL)
14431            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14432                    + componentNames);
14433        Bundle extras = new Bundle(4);
14434        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14435        String nameList[] = new String[componentNames.size()];
14436        componentNames.toArray(nameList);
14437        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14438        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14439        extras.putInt(Intent.EXTRA_UID, packageUid);
14440        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14441                new int[] {UserHandle.getUserId(packageUid)});
14442    }
14443
14444    @Override
14445    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14446        if (!sUserManager.exists(userId)) return;
14447        final int uid = Binder.getCallingUid();
14448        final int permission = mContext.checkCallingOrSelfPermission(
14449                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14450        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14451        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14452        // writer
14453        synchronized (mPackages) {
14454            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14455                    allowedByPermission, uid, userId)) {
14456                scheduleWritePackageRestrictionsLocked(userId);
14457            }
14458        }
14459    }
14460
14461    @Override
14462    public String getInstallerPackageName(String packageName) {
14463        // reader
14464        synchronized (mPackages) {
14465            return mSettings.getInstallerPackageNameLPr(packageName);
14466        }
14467    }
14468
14469    @Override
14470    public int getApplicationEnabledSetting(String packageName, int userId) {
14471        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14472        int uid = Binder.getCallingUid();
14473        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14474        // reader
14475        synchronized (mPackages) {
14476            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14477        }
14478    }
14479
14480    @Override
14481    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14482        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14483        int uid = Binder.getCallingUid();
14484        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14485        // reader
14486        synchronized (mPackages) {
14487            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14488        }
14489    }
14490
14491    @Override
14492    public void enterSafeMode() {
14493        enforceSystemOrRoot("Only the system can request entering safe mode");
14494
14495        if (!mSystemReady) {
14496            mSafeMode = true;
14497        }
14498    }
14499
14500    @Override
14501    public void systemReady() {
14502        mSystemReady = true;
14503
14504        // Read the compatibilty setting when the system is ready.
14505        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14506                mContext.getContentResolver(),
14507                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14508        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14509        if (DEBUG_SETTINGS) {
14510            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14511        }
14512
14513        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14514
14515        synchronized (mPackages) {
14516            // Verify that all of the preferred activity components actually
14517            // exist.  It is possible for applications to be updated and at
14518            // that point remove a previously declared activity component that
14519            // had been set as a preferred activity.  We try to clean this up
14520            // the next time we encounter that preferred activity, but it is
14521            // possible for the user flow to never be able to return to that
14522            // situation so here we do a sanity check to make sure we haven't
14523            // left any junk around.
14524            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14525            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14526                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14527                removed.clear();
14528                for (PreferredActivity pa : pir.filterSet()) {
14529                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14530                        removed.add(pa);
14531                    }
14532                }
14533                if (removed.size() > 0) {
14534                    for (int r=0; r<removed.size(); r++) {
14535                        PreferredActivity pa = removed.get(r);
14536                        Slog.w(TAG, "Removing dangling preferred activity: "
14537                                + pa.mPref.mComponent);
14538                        pir.removeFilter(pa);
14539                    }
14540                    mSettings.writePackageRestrictionsLPr(
14541                            mSettings.mPreferredActivities.keyAt(i));
14542                }
14543            }
14544
14545            for (int userId : UserManagerService.getInstance().getUserIds()) {
14546                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14547                    grantPermissionsUserIds = ArrayUtils.appendInt(
14548                            grantPermissionsUserIds, userId);
14549                }
14550            }
14551        }
14552        sUserManager.systemReady();
14553
14554        // If we upgraded grant all default permissions before kicking off.
14555        for (int userId : grantPermissionsUserIds) {
14556            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14557        }
14558
14559        // Kick off any messages waiting for system ready
14560        if (mPostSystemReadyMessages != null) {
14561            for (Message msg : mPostSystemReadyMessages) {
14562                msg.sendToTarget();
14563            }
14564            mPostSystemReadyMessages = null;
14565        }
14566
14567        // Watch for external volumes that come and go over time
14568        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14569        storage.registerListener(mStorageListener);
14570
14571        mInstallerService.systemReady();
14572        mPackageDexOptimizer.systemReady();
14573
14574        MountServiceInternal mountServiceInternal = LocalServices.getService(
14575                MountServiceInternal.class);
14576        mountServiceInternal.addExternalStoragePolicy(
14577                new MountServiceInternal.ExternalStorageMountPolicy() {
14578            @Override
14579            public int getMountMode(int uid, String packageName) {
14580                if (Process.isIsolated(uid)) {
14581                    return Zygote.MOUNT_EXTERNAL_NONE;
14582                }
14583                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14584                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14585                }
14586                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14587                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14588                }
14589                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14590                    return Zygote.MOUNT_EXTERNAL_READ;
14591                }
14592                return Zygote.MOUNT_EXTERNAL_WRITE;
14593            }
14594
14595            @Override
14596            public boolean hasExternalStorage(int uid, String packageName) {
14597                return true;
14598            }
14599        });
14600    }
14601
14602    @Override
14603    public boolean isSafeMode() {
14604        return mSafeMode;
14605    }
14606
14607    @Override
14608    public boolean hasSystemUidErrors() {
14609        return mHasSystemUidErrors;
14610    }
14611
14612    static String arrayToString(int[] array) {
14613        StringBuffer buf = new StringBuffer(128);
14614        buf.append('[');
14615        if (array != null) {
14616            for (int i=0; i<array.length; i++) {
14617                if (i > 0) buf.append(", ");
14618                buf.append(array[i]);
14619            }
14620        }
14621        buf.append(']');
14622        return buf.toString();
14623    }
14624
14625    static class DumpState {
14626        public static final int DUMP_LIBS = 1 << 0;
14627        public static final int DUMP_FEATURES = 1 << 1;
14628        public static final int DUMP_RESOLVERS = 1 << 2;
14629        public static final int DUMP_PERMISSIONS = 1 << 3;
14630        public static final int DUMP_PACKAGES = 1 << 4;
14631        public static final int DUMP_SHARED_USERS = 1 << 5;
14632        public static final int DUMP_MESSAGES = 1 << 6;
14633        public static final int DUMP_PROVIDERS = 1 << 7;
14634        public static final int DUMP_VERIFIERS = 1 << 8;
14635        public static final int DUMP_PREFERRED = 1 << 9;
14636        public static final int DUMP_PREFERRED_XML = 1 << 10;
14637        public static final int DUMP_KEYSETS = 1 << 11;
14638        public static final int DUMP_VERSION = 1 << 12;
14639        public static final int DUMP_INSTALLS = 1 << 13;
14640        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14641        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14642
14643        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14644
14645        private int mTypes;
14646
14647        private int mOptions;
14648
14649        private boolean mTitlePrinted;
14650
14651        private SharedUserSetting mSharedUser;
14652
14653        public boolean isDumping(int type) {
14654            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14655                return true;
14656            }
14657
14658            return (mTypes & type) != 0;
14659        }
14660
14661        public void setDump(int type) {
14662            mTypes |= type;
14663        }
14664
14665        public boolean isOptionEnabled(int option) {
14666            return (mOptions & option) != 0;
14667        }
14668
14669        public void setOptionEnabled(int option) {
14670            mOptions |= option;
14671        }
14672
14673        public boolean onTitlePrinted() {
14674            final boolean printed = mTitlePrinted;
14675            mTitlePrinted = true;
14676            return printed;
14677        }
14678
14679        public boolean getTitlePrinted() {
14680            return mTitlePrinted;
14681        }
14682
14683        public void setTitlePrinted(boolean enabled) {
14684            mTitlePrinted = enabled;
14685        }
14686
14687        public SharedUserSetting getSharedUser() {
14688            return mSharedUser;
14689        }
14690
14691        public void setSharedUser(SharedUserSetting user) {
14692            mSharedUser = user;
14693        }
14694    }
14695
14696    @Override
14697    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14698        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14699                != PackageManager.PERMISSION_GRANTED) {
14700            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14701                    + Binder.getCallingPid()
14702                    + ", uid=" + Binder.getCallingUid()
14703                    + " without permission "
14704                    + android.Manifest.permission.DUMP);
14705            return;
14706        }
14707
14708        DumpState dumpState = new DumpState();
14709        boolean fullPreferred = false;
14710        boolean checkin = false;
14711
14712        String packageName = null;
14713        ArraySet<String> permissionNames = null;
14714
14715        int opti = 0;
14716        while (opti < args.length) {
14717            String opt = args[opti];
14718            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14719                break;
14720            }
14721            opti++;
14722
14723            if ("-a".equals(opt)) {
14724                // Right now we only know how to print all.
14725            } else if ("-h".equals(opt)) {
14726                pw.println("Package manager dump options:");
14727                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14728                pw.println("    --checkin: dump for a checkin");
14729                pw.println("    -f: print details of intent filters");
14730                pw.println("    -h: print this help");
14731                pw.println("  cmd may be one of:");
14732                pw.println("    l[ibraries]: list known shared libraries");
14733                pw.println("    f[ibraries]: list device features");
14734                pw.println("    k[eysets]: print known keysets");
14735                pw.println("    r[esolvers]: dump intent resolvers");
14736                pw.println("    perm[issions]: dump permissions");
14737                pw.println("    permission [name ...]: dump declaration and use of given permission");
14738                pw.println("    pref[erred]: print preferred package settings");
14739                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14740                pw.println("    prov[iders]: dump content providers");
14741                pw.println("    p[ackages]: dump installed packages");
14742                pw.println("    s[hared-users]: dump shared user IDs");
14743                pw.println("    m[essages]: print collected runtime messages");
14744                pw.println("    v[erifiers]: print package verifier info");
14745                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14746                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14747                pw.println("    version: print database version info");
14748                pw.println("    write: write current settings now");
14749                pw.println("    installs: details about install sessions");
14750                pw.println("    <package.name>: info about given package");
14751                return;
14752            } else if ("--checkin".equals(opt)) {
14753                checkin = true;
14754            } else if ("-f".equals(opt)) {
14755                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14756            } else {
14757                pw.println("Unknown argument: " + opt + "; use -h for help");
14758            }
14759        }
14760
14761        // Is the caller requesting to dump a particular piece of data?
14762        if (opti < args.length) {
14763            String cmd = args[opti];
14764            opti++;
14765            // Is this a package name?
14766            if ("android".equals(cmd) || cmd.contains(".")) {
14767                packageName = cmd;
14768                // When dumping a single package, we always dump all of its
14769                // filter information since the amount of data will be reasonable.
14770                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14771            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14772                dumpState.setDump(DumpState.DUMP_LIBS);
14773            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14774                dumpState.setDump(DumpState.DUMP_FEATURES);
14775            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14776                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14777            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14778                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14779            } else if ("permission".equals(cmd)) {
14780                if (opti >= args.length) {
14781                    pw.println("Error: permission requires permission name");
14782                    return;
14783                }
14784                permissionNames = new ArraySet<>();
14785                while (opti < args.length) {
14786                    permissionNames.add(args[opti]);
14787                    opti++;
14788                }
14789                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14790                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14791            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14792                dumpState.setDump(DumpState.DUMP_PREFERRED);
14793            } else if ("preferred-xml".equals(cmd)) {
14794                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14795                if (opti < args.length && "--full".equals(args[opti])) {
14796                    fullPreferred = true;
14797                    opti++;
14798                }
14799            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14800                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14801            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14802                dumpState.setDump(DumpState.DUMP_PACKAGES);
14803            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14804                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14805            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14806                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14807            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14808                dumpState.setDump(DumpState.DUMP_MESSAGES);
14809            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14810                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14811            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14812                    || "intent-filter-verifiers".equals(cmd)) {
14813                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14814            } else if ("version".equals(cmd)) {
14815                dumpState.setDump(DumpState.DUMP_VERSION);
14816            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14817                dumpState.setDump(DumpState.DUMP_KEYSETS);
14818            } else if ("installs".equals(cmd)) {
14819                dumpState.setDump(DumpState.DUMP_INSTALLS);
14820            } else if ("write".equals(cmd)) {
14821                synchronized (mPackages) {
14822                    mSettings.writeLPr();
14823                    pw.println("Settings written.");
14824                    return;
14825                }
14826            }
14827        }
14828
14829        if (checkin) {
14830            pw.println("vers,1");
14831        }
14832
14833        // reader
14834        synchronized (mPackages) {
14835            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14836                if (!checkin) {
14837                    if (dumpState.onTitlePrinted())
14838                        pw.println();
14839                    pw.println("Database versions:");
14840                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14841                }
14842            }
14843
14844            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14845                if (!checkin) {
14846                    if (dumpState.onTitlePrinted())
14847                        pw.println();
14848                    pw.println("Verifiers:");
14849                    pw.print("  Required: ");
14850                    pw.print(mRequiredVerifierPackage);
14851                    pw.print(" (uid=");
14852                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14853                    pw.println(")");
14854                } else if (mRequiredVerifierPackage != null) {
14855                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14856                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14857                }
14858            }
14859
14860            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14861                    packageName == null) {
14862                if (mIntentFilterVerifierComponent != null) {
14863                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14864                    if (!checkin) {
14865                        if (dumpState.onTitlePrinted())
14866                            pw.println();
14867                        pw.println("Intent Filter Verifier:");
14868                        pw.print("  Using: ");
14869                        pw.print(verifierPackageName);
14870                        pw.print(" (uid=");
14871                        pw.print(getPackageUid(verifierPackageName, 0));
14872                        pw.println(")");
14873                    } else if (verifierPackageName != null) {
14874                        pw.print("ifv,"); pw.print(verifierPackageName);
14875                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14876                    }
14877                } else {
14878                    pw.println();
14879                    pw.println("No Intent Filter Verifier available!");
14880                }
14881            }
14882
14883            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14884                boolean printedHeader = false;
14885                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14886                while (it.hasNext()) {
14887                    String name = it.next();
14888                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14889                    if (!checkin) {
14890                        if (!printedHeader) {
14891                            if (dumpState.onTitlePrinted())
14892                                pw.println();
14893                            pw.println("Libraries:");
14894                            printedHeader = true;
14895                        }
14896                        pw.print("  ");
14897                    } else {
14898                        pw.print("lib,");
14899                    }
14900                    pw.print(name);
14901                    if (!checkin) {
14902                        pw.print(" -> ");
14903                    }
14904                    if (ent.path != null) {
14905                        if (!checkin) {
14906                            pw.print("(jar) ");
14907                            pw.print(ent.path);
14908                        } else {
14909                            pw.print(",jar,");
14910                            pw.print(ent.path);
14911                        }
14912                    } else {
14913                        if (!checkin) {
14914                            pw.print("(apk) ");
14915                            pw.print(ent.apk);
14916                        } else {
14917                            pw.print(",apk,");
14918                            pw.print(ent.apk);
14919                        }
14920                    }
14921                    pw.println();
14922                }
14923            }
14924
14925            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14926                if (dumpState.onTitlePrinted())
14927                    pw.println();
14928                if (!checkin) {
14929                    pw.println("Features:");
14930                }
14931                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14932                while (it.hasNext()) {
14933                    String name = it.next();
14934                    if (!checkin) {
14935                        pw.print("  ");
14936                    } else {
14937                        pw.print("feat,");
14938                    }
14939                    pw.println(name);
14940                }
14941            }
14942
14943            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14944                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14945                        : "Activity Resolver Table:", "  ", packageName,
14946                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14947                    dumpState.setTitlePrinted(true);
14948                }
14949                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14950                        : "Receiver Resolver Table:", "  ", packageName,
14951                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14952                    dumpState.setTitlePrinted(true);
14953                }
14954                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14955                        : "Service Resolver Table:", "  ", packageName,
14956                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14957                    dumpState.setTitlePrinted(true);
14958                }
14959                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14960                        : "Provider Resolver Table:", "  ", packageName,
14961                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14962                    dumpState.setTitlePrinted(true);
14963                }
14964            }
14965
14966            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14967                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14968                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14969                    int user = mSettings.mPreferredActivities.keyAt(i);
14970                    if (pir.dump(pw,
14971                            dumpState.getTitlePrinted()
14972                                ? "\nPreferred Activities User " + user + ":"
14973                                : "Preferred Activities User " + user + ":", "  ",
14974                            packageName, true, false)) {
14975                        dumpState.setTitlePrinted(true);
14976                    }
14977                }
14978            }
14979
14980            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14981                pw.flush();
14982                FileOutputStream fout = new FileOutputStream(fd);
14983                BufferedOutputStream str = new BufferedOutputStream(fout);
14984                XmlSerializer serializer = new FastXmlSerializer();
14985                try {
14986                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14987                    serializer.startDocument(null, true);
14988                    serializer.setFeature(
14989                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14990                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14991                    serializer.endDocument();
14992                    serializer.flush();
14993                } catch (IllegalArgumentException e) {
14994                    pw.println("Failed writing: " + e);
14995                } catch (IllegalStateException e) {
14996                    pw.println("Failed writing: " + e);
14997                } catch (IOException e) {
14998                    pw.println("Failed writing: " + e);
14999                }
15000            }
15001
15002            if (!checkin
15003                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15004                    && packageName == null) {
15005                pw.println();
15006                int count = mSettings.mPackages.size();
15007                if (count == 0) {
15008                    pw.println("No applications!");
15009                    pw.println();
15010                } else {
15011                    final String prefix = "  ";
15012                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15013                    if (allPackageSettings.size() == 0) {
15014                        pw.println("No domain preferred apps!");
15015                        pw.println();
15016                    } else {
15017                        pw.println("App verification status:");
15018                        pw.println();
15019                        count = 0;
15020                        for (PackageSetting ps : allPackageSettings) {
15021                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15022                            if (ivi == null || ivi.getPackageName() == null) continue;
15023                            pw.println(prefix + "Package: " + ivi.getPackageName());
15024                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15025                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15026                            pw.println();
15027                            count++;
15028                        }
15029                        if (count == 0) {
15030                            pw.println(prefix + "No app verification established.");
15031                            pw.println();
15032                        }
15033                        for (int userId : sUserManager.getUserIds()) {
15034                            pw.println("App linkages for user " + userId + ":");
15035                            pw.println();
15036                            count = 0;
15037                            for (PackageSetting ps : allPackageSettings) {
15038                                final long status = ps.getDomainVerificationStatusForUser(userId);
15039                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15040                                    continue;
15041                                }
15042                                pw.println(prefix + "Package: " + ps.name);
15043                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15044                                String statusStr = IntentFilterVerificationInfo.
15045                                        getStatusStringFromValue(status);
15046                                pw.println(prefix + "Status:  " + statusStr);
15047                                pw.println();
15048                                count++;
15049                            }
15050                            if (count == 0) {
15051                                pw.println(prefix + "No configured app linkages.");
15052                                pw.println();
15053                            }
15054                        }
15055                    }
15056                }
15057            }
15058
15059            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15060                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15061                if (packageName == null && permissionNames == null) {
15062                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15063                        if (iperm == 0) {
15064                            if (dumpState.onTitlePrinted())
15065                                pw.println();
15066                            pw.println("AppOp Permissions:");
15067                        }
15068                        pw.print("  AppOp Permission ");
15069                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15070                        pw.println(":");
15071                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15072                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15073                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15074                        }
15075                    }
15076                }
15077            }
15078
15079            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15080                boolean printedSomething = false;
15081                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15082                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15083                        continue;
15084                    }
15085                    if (!printedSomething) {
15086                        if (dumpState.onTitlePrinted())
15087                            pw.println();
15088                        pw.println("Registered ContentProviders:");
15089                        printedSomething = true;
15090                    }
15091                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15092                    pw.print("    "); pw.println(p.toString());
15093                }
15094                printedSomething = false;
15095                for (Map.Entry<String, PackageParser.Provider> entry :
15096                        mProvidersByAuthority.entrySet()) {
15097                    PackageParser.Provider p = entry.getValue();
15098                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15099                        continue;
15100                    }
15101                    if (!printedSomething) {
15102                        if (dumpState.onTitlePrinted())
15103                            pw.println();
15104                        pw.println("ContentProvider Authorities:");
15105                        printedSomething = true;
15106                    }
15107                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15108                    pw.print("    "); pw.println(p.toString());
15109                    if (p.info != null && p.info.applicationInfo != null) {
15110                        final String appInfo = p.info.applicationInfo.toString();
15111                        pw.print("      applicationInfo="); pw.println(appInfo);
15112                    }
15113                }
15114            }
15115
15116            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15117                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15118            }
15119
15120            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15121                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15122            }
15123
15124            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15125                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15126            }
15127
15128            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15129                // XXX should handle packageName != null by dumping only install data that
15130                // the given package is involved with.
15131                if (dumpState.onTitlePrinted()) pw.println();
15132                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15133            }
15134
15135            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15136                if (dumpState.onTitlePrinted()) pw.println();
15137                mSettings.dumpReadMessagesLPr(pw, dumpState);
15138
15139                pw.println();
15140                pw.println("Package warning messages:");
15141                BufferedReader in = null;
15142                String line = null;
15143                try {
15144                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15145                    while ((line = in.readLine()) != null) {
15146                        if (line.contains("ignored: updated version")) continue;
15147                        pw.println(line);
15148                    }
15149                } catch (IOException ignored) {
15150                } finally {
15151                    IoUtils.closeQuietly(in);
15152                }
15153            }
15154
15155            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15156                BufferedReader in = null;
15157                String line = null;
15158                try {
15159                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15160                    while ((line = in.readLine()) != null) {
15161                        if (line.contains("ignored: updated version")) continue;
15162                        pw.print("msg,");
15163                        pw.println(line);
15164                    }
15165                } catch (IOException ignored) {
15166                } finally {
15167                    IoUtils.closeQuietly(in);
15168                }
15169            }
15170        }
15171    }
15172
15173    private String dumpDomainString(String packageName) {
15174        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15175        List<IntentFilter> filters = getAllIntentFilters(packageName);
15176
15177        ArraySet<String> result = new ArraySet<>();
15178        if (iviList.size() > 0) {
15179            for (IntentFilterVerificationInfo ivi : iviList) {
15180                for (String host : ivi.getDomains()) {
15181                    result.add(host);
15182                }
15183            }
15184        }
15185        if (filters != null && filters.size() > 0) {
15186            for (IntentFilter filter : filters) {
15187                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15188                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15189                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15190                    result.addAll(filter.getHostsList());
15191                }
15192            }
15193        }
15194
15195        StringBuilder sb = new StringBuilder(result.size() * 16);
15196        for (String domain : result) {
15197            if (sb.length() > 0) sb.append(" ");
15198            sb.append(domain);
15199        }
15200        return sb.toString();
15201    }
15202
15203    // ------- apps on sdcard specific code -------
15204    static final boolean DEBUG_SD_INSTALL = false;
15205
15206    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15207
15208    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15209
15210    private boolean mMediaMounted = false;
15211
15212    static String getEncryptKey() {
15213        try {
15214            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15215                    SD_ENCRYPTION_KEYSTORE_NAME);
15216            if (sdEncKey == null) {
15217                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15218                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15219                if (sdEncKey == null) {
15220                    Slog.e(TAG, "Failed to create encryption keys");
15221                    return null;
15222                }
15223            }
15224            return sdEncKey;
15225        } catch (NoSuchAlgorithmException nsae) {
15226            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15227            return null;
15228        } catch (IOException ioe) {
15229            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15230            return null;
15231        }
15232    }
15233
15234    /*
15235     * Update media status on PackageManager.
15236     */
15237    @Override
15238    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15239        int callingUid = Binder.getCallingUid();
15240        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15241            throw new SecurityException("Media status can only be updated by the system");
15242        }
15243        // reader; this apparently protects mMediaMounted, but should probably
15244        // be a different lock in that case.
15245        synchronized (mPackages) {
15246            Log.i(TAG, "Updating external media status from "
15247                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15248                    + (mediaStatus ? "mounted" : "unmounted"));
15249            if (DEBUG_SD_INSTALL)
15250                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15251                        + ", mMediaMounted=" + mMediaMounted);
15252            if (mediaStatus == mMediaMounted) {
15253                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15254                        : 0, -1);
15255                mHandler.sendMessage(msg);
15256                return;
15257            }
15258            mMediaMounted = mediaStatus;
15259        }
15260        // Queue up an async operation since the package installation may take a
15261        // little while.
15262        mHandler.post(new Runnable() {
15263            public void run() {
15264                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15265            }
15266        });
15267    }
15268
15269    /**
15270     * Called by MountService when the initial ASECs to scan are available.
15271     * Should block until all the ASEC containers are finished being scanned.
15272     */
15273    public void scanAvailableAsecs() {
15274        updateExternalMediaStatusInner(true, false, false);
15275        if (mShouldRestoreconData) {
15276            SELinuxMMAC.setRestoreconDone();
15277            mShouldRestoreconData = false;
15278        }
15279    }
15280
15281    /*
15282     * Collect information of applications on external media, map them against
15283     * existing containers and update information based on current mount status.
15284     * Please note that we always have to report status if reportStatus has been
15285     * set to true especially when unloading packages.
15286     */
15287    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15288            boolean externalStorage) {
15289        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15290        int[] uidArr = EmptyArray.INT;
15291
15292        final String[] list = PackageHelper.getSecureContainerList();
15293        if (ArrayUtils.isEmpty(list)) {
15294            Log.i(TAG, "No secure containers found");
15295        } else {
15296            // Process list of secure containers and categorize them
15297            // as active or stale based on their package internal state.
15298
15299            // reader
15300            synchronized (mPackages) {
15301                for (String cid : list) {
15302                    // Leave stages untouched for now; installer service owns them
15303                    if (PackageInstallerService.isStageName(cid)) continue;
15304
15305                    if (DEBUG_SD_INSTALL)
15306                        Log.i(TAG, "Processing container " + cid);
15307                    String pkgName = getAsecPackageName(cid);
15308                    if (pkgName == null) {
15309                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15310                        continue;
15311                    }
15312                    if (DEBUG_SD_INSTALL)
15313                        Log.i(TAG, "Looking for pkg : " + pkgName);
15314
15315                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15316                    if (ps == null) {
15317                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15318                        continue;
15319                    }
15320
15321                    /*
15322                     * Skip packages that are not external if we're unmounting
15323                     * external storage.
15324                     */
15325                    if (externalStorage && !isMounted && !isExternal(ps)) {
15326                        continue;
15327                    }
15328
15329                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15330                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15331                    // The package status is changed only if the code path
15332                    // matches between settings and the container id.
15333                    if (ps.codePathString != null
15334                            && ps.codePathString.startsWith(args.getCodePath())) {
15335                        if (DEBUG_SD_INSTALL) {
15336                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15337                                    + " at code path: " + ps.codePathString);
15338                        }
15339
15340                        // We do have a valid package installed on sdcard
15341                        processCids.put(args, ps.codePathString);
15342                        final int uid = ps.appId;
15343                        if (uid != -1) {
15344                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15345                        }
15346                    } else {
15347                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15348                                + ps.codePathString);
15349                    }
15350                }
15351            }
15352
15353            Arrays.sort(uidArr);
15354        }
15355
15356        // Process packages with valid entries.
15357        if (isMounted) {
15358            if (DEBUG_SD_INSTALL)
15359                Log.i(TAG, "Loading packages");
15360            loadMediaPackages(processCids, uidArr);
15361            startCleaningPackages();
15362            mInstallerService.onSecureContainersAvailable();
15363        } else {
15364            if (DEBUG_SD_INSTALL)
15365                Log.i(TAG, "Unloading packages");
15366            unloadMediaPackages(processCids, uidArr, reportStatus);
15367        }
15368    }
15369
15370    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15371            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15372        final int size = infos.size();
15373        final String[] packageNames = new String[size];
15374        final int[] packageUids = new int[size];
15375        for (int i = 0; i < size; i++) {
15376            final ApplicationInfo info = infos.get(i);
15377            packageNames[i] = info.packageName;
15378            packageUids[i] = info.uid;
15379        }
15380        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15381                finishedReceiver);
15382    }
15383
15384    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15385            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15386        sendResourcesChangedBroadcast(mediaStatus, replacing,
15387                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15388    }
15389
15390    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15391            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15392        int size = pkgList.length;
15393        if (size > 0) {
15394            // Send broadcasts here
15395            Bundle extras = new Bundle();
15396            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15397            if (uidArr != null) {
15398                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15399            }
15400            if (replacing) {
15401                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15402            }
15403            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15404                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15405            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15406        }
15407    }
15408
15409   /*
15410     * Look at potentially valid container ids from processCids If package
15411     * information doesn't match the one on record or package scanning fails,
15412     * the cid is added to list of removeCids. We currently don't delete stale
15413     * containers.
15414     */
15415    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15416        ArrayList<String> pkgList = new ArrayList<String>();
15417        Set<AsecInstallArgs> keys = processCids.keySet();
15418
15419        for (AsecInstallArgs args : keys) {
15420            String codePath = processCids.get(args);
15421            if (DEBUG_SD_INSTALL)
15422                Log.i(TAG, "Loading container : " + args.cid);
15423            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15424            try {
15425                // Make sure there are no container errors first.
15426                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15427                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15428                            + " when installing from sdcard");
15429                    continue;
15430                }
15431                // Check code path here.
15432                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15433                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15434                            + " does not match one in settings " + codePath);
15435                    continue;
15436                }
15437                // Parse package
15438                int parseFlags = mDefParseFlags;
15439                if (args.isExternalAsec()) {
15440                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15441                }
15442                if (args.isFwdLocked()) {
15443                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15444                }
15445
15446                synchronized (mInstallLock) {
15447                    PackageParser.Package pkg = null;
15448                    try {
15449                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15450                    } catch (PackageManagerException e) {
15451                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15452                    }
15453                    // Scan the package
15454                    if (pkg != null) {
15455                        /*
15456                         * TODO why is the lock being held? doPostInstall is
15457                         * called in other places without the lock. This needs
15458                         * to be straightened out.
15459                         */
15460                        // writer
15461                        synchronized (mPackages) {
15462                            retCode = PackageManager.INSTALL_SUCCEEDED;
15463                            pkgList.add(pkg.packageName);
15464                            // Post process args
15465                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15466                                    pkg.applicationInfo.uid);
15467                        }
15468                    } else {
15469                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15470                    }
15471                }
15472
15473            } finally {
15474                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15475                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15476                }
15477            }
15478        }
15479        // writer
15480        synchronized (mPackages) {
15481            // If the platform SDK has changed since the last time we booted,
15482            // we need to re-grant app permission to catch any new ones that
15483            // appear. This is really a hack, and means that apps can in some
15484            // cases get permissions that the user didn't initially explicitly
15485            // allow... it would be nice to have some better way to handle
15486            // this situation.
15487            final VersionInfo ver = mSettings.getExternalVersion();
15488
15489            int updateFlags = UPDATE_PERMISSIONS_ALL;
15490            if (ver.sdkVersion != mSdkVersion) {
15491                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15492                        + mSdkVersion + "; regranting permissions for external");
15493                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15494            }
15495            updatePermissionsLPw(null, null, updateFlags);
15496
15497            // Yay, everything is now upgraded
15498            ver.forceCurrent();
15499
15500            // can downgrade to reader
15501            // Persist settings
15502            mSettings.writeLPr();
15503        }
15504        // Send a broadcast to let everyone know we are done processing
15505        if (pkgList.size() > 0) {
15506            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15507        }
15508    }
15509
15510   /*
15511     * Utility method to unload a list of specified containers
15512     */
15513    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15514        // Just unmount all valid containers.
15515        for (AsecInstallArgs arg : cidArgs) {
15516            synchronized (mInstallLock) {
15517                arg.doPostDeleteLI(false);
15518           }
15519       }
15520   }
15521
15522    /*
15523     * Unload packages mounted on external media. This involves deleting package
15524     * data from internal structures, sending broadcasts about diabled packages,
15525     * gc'ing to free up references, unmounting all secure containers
15526     * corresponding to packages on external media, and posting a
15527     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15528     * that we always have to post this message if status has been requested no
15529     * matter what.
15530     */
15531    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15532            final boolean reportStatus) {
15533        if (DEBUG_SD_INSTALL)
15534            Log.i(TAG, "unloading media packages");
15535        ArrayList<String> pkgList = new ArrayList<String>();
15536        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15537        final Set<AsecInstallArgs> keys = processCids.keySet();
15538        for (AsecInstallArgs args : keys) {
15539            String pkgName = args.getPackageName();
15540            if (DEBUG_SD_INSTALL)
15541                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15542            // Delete package internally
15543            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15544            synchronized (mInstallLock) {
15545                boolean res = deletePackageLI(pkgName, null, false, null, null,
15546                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15547                if (res) {
15548                    pkgList.add(pkgName);
15549                } else {
15550                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15551                    failedList.add(args);
15552                }
15553            }
15554        }
15555
15556        // reader
15557        synchronized (mPackages) {
15558            // We didn't update the settings after removing each package;
15559            // write them now for all packages.
15560            mSettings.writeLPr();
15561        }
15562
15563        // We have to absolutely send UPDATED_MEDIA_STATUS only
15564        // after confirming that all the receivers processed the ordered
15565        // broadcast when packages get disabled, force a gc to clean things up.
15566        // and unload all the containers.
15567        if (pkgList.size() > 0) {
15568            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15569                    new IIntentReceiver.Stub() {
15570                public void performReceive(Intent intent, int resultCode, String data,
15571                        Bundle extras, boolean ordered, boolean sticky,
15572                        int sendingUser) throws RemoteException {
15573                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15574                            reportStatus ? 1 : 0, 1, keys);
15575                    mHandler.sendMessage(msg);
15576                }
15577            });
15578        } else {
15579            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15580                    keys);
15581            mHandler.sendMessage(msg);
15582        }
15583    }
15584
15585    private void loadPrivatePackages(VolumeInfo vol) {
15586        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15587        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15588        synchronized (mInstallLock) {
15589        synchronized (mPackages) {
15590            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15591            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15592            for (PackageSetting ps : packages) {
15593                final PackageParser.Package pkg;
15594                try {
15595                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15596                    loaded.add(pkg.applicationInfo);
15597                } catch (PackageManagerException e) {
15598                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15599                }
15600
15601                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15602                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15603                }
15604            }
15605
15606            int updateFlags = UPDATE_PERMISSIONS_ALL;
15607            if (ver.sdkVersion != mSdkVersion) {
15608                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15609                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15610                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15611            }
15612            updatePermissionsLPw(null, null, updateFlags);
15613
15614            // Yay, everything is now upgraded
15615            ver.forceCurrent();
15616
15617            mSettings.writeLPr();
15618        }
15619        }
15620
15621        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15622        sendResourcesChangedBroadcast(true, false, loaded, null);
15623    }
15624
15625    private void unloadPrivatePackages(VolumeInfo vol) {
15626        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15627        synchronized (mInstallLock) {
15628        synchronized (mPackages) {
15629            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15630            for (PackageSetting ps : packages) {
15631                if (ps.pkg == null) continue;
15632
15633                final ApplicationInfo info = ps.pkg.applicationInfo;
15634                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15635                if (deletePackageLI(ps.name, null, false, null, null,
15636                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15637                    unloaded.add(info);
15638                } else {
15639                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15640                }
15641            }
15642
15643            mSettings.writeLPr();
15644        }
15645        }
15646
15647        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15648        sendResourcesChangedBroadcast(false, false, unloaded, null);
15649    }
15650
15651    /**
15652     * Examine all users present on given mounted volume, and destroy data
15653     * belonging to users that are no longer valid, or whose user ID has been
15654     * recycled.
15655     */
15656    private void reconcileUsers(String volumeUuid) {
15657        final File[] files = FileUtils
15658                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15659        for (File file : files) {
15660            if (!file.isDirectory()) continue;
15661
15662            final int userId;
15663            final UserInfo info;
15664            try {
15665                userId = Integer.parseInt(file.getName());
15666                info = sUserManager.getUserInfo(userId);
15667            } catch (NumberFormatException e) {
15668                Slog.w(TAG, "Invalid user directory " + file);
15669                continue;
15670            }
15671
15672            boolean destroyUser = false;
15673            if (info == null) {
15674                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15675                        + " because no matching user was found");
15676                destroyUser = true;
15677            } else {
15678                try {
15679                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15680                } catch (IOException e) {
15681                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15682                            + " because we failed to enforce serial number: " + e);
15683                    destroyUser = true;
15684                }
15685            }
15686
15687            if (destroyUser) {
15688                synchronized (mInstallLock) {
15689                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15690                }
15691            }
15692        }
15693
15694        final UserManager um = mContext.getSystemService(UserManager.class);
15695        for (UserInfo user : um.getUsers()) {
15696            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15697            if (userDir.exists()) continue;
15698
15699            try {
15700                UserManagerService.prepareUserDirectory(userDir);
15701                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15702            } catch (IOException e) {
15703                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15704            }
15705        }
15706    }
15707
15708    /**
15709     * Examine all apps present on given mounted volume, and destroy apps that
15710     * aren't expected, either due to uninstallation or reinstallation on
15711     * another volume.
15712     */
15713    private void reconcileApps(String volumeUuid) {
15714        final File[] files = FileUtils
15715                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15716        for (File file : files) {
15717            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15718                    && !PackageInstallerService.isStageName(file.getName());
15719            if (!isPackage) {
15720                // Ignore entries which are not packages
15721                continue;
15722            }
15723
15724            boolean destroyApp = false;
15725            String packageName = null;
15726            try {
15727                final PackageLite pkg = PackageParser.parsePackageLite(file,
15728                        PackageParser.PARSE_MUST_BE_APK);
15729                packageName = pkg.packageName;
15730
15731                synchronized (mPackages) {
15732                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15733                    if (ps == null) {
15734                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15735                                + volumeUuid + " because we found no install record");
15736                        destroyApp = true;
15737                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15738                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15739                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15740                        destroyApp = true;
15741                    }
15742                }
15743
15744            } catch (PackageParserException e) {
15745                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15746                destroyApp = true;
15747            }
15748
15749            if (destroyApp) {
15750                synchronized (mInstallLock) {
15751                    if (packageName != null) {
15752                        removeDataDirsLI(volumeUuid, packageName);
15753                    }
15754                    if (file.isDirectory()) {
15755                        mInstaller.rmPackageDir(file.getAbsolutePath());
15756                    } else {
15757                        file.delete();
15758                    }
15759                }
15760            }
15761        }
15762    }
15763
15764    private void unfreezePackage(String packageName) {
15765        synchronized (mPackages) {
15766            final PackageSetting ps = mSettings.mPackages.get(packageName);
15767            if (ps != null) {
15768                ps.frozen = false;
15769            }
15770        }
15771    }
15772
15773    @Override
15774    public int movePackage(final String packageName, final String volumeUuid) {
15775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15776
15777        final int moveId = mNextMoveId.getAndIncrement();
15778        try {
15779            movePackageInternal(packageName, volumeUuid, moveId);
15780        } catch (PackageManagerException e) {
15781            Slog.w(TAG, "Failed to move " + packageName, e);
15782            mMoveCallbacks.notifyStatusChanged(moveId,
15783                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15784        }
15785        return moveId;
15786    }
15787
15788    private void movePackageInternal(final String packageName, final String volumeUuid,
15789            final int moveId) throws PackageManagerException {
15790        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15791        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15792        final PackageManager pm = mContext.getPackageManager();
15793
15794        final boolean currentAsec;
15795        final String currentVolumeUuid;
15796        final File codeFile;
15797        final String installerPackageName;
15798        final String packageAbiOverride;
15799        final int appId;
15800        final String seinfo;
15801        final String label;
15802
15803        // reader
15804        synchronized (mPackages) {
15805            final PackageParser.Package pkg = mPackages.get(packageName);
15806            final PackageSetting ps = mSettings.mPackages.get(packageName);
15807            if (pkg == null || ps == null) {
15808                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15809            }
15810
15811            if (pkg.applicationInfo.isSystemApp()) {
15812                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15813                        "Cannot move system application");
15814            }
15815
15816            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15817                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15818                        "Package already moved to " + volumeUuid);
15819            }
15820
15821            final File probe = new File(pkg.codePath);
15822            final File probeOat = new File(probe, "oat");
15823            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15824                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15825                        "Move only supported for modern cluster style installs");
15826            }
15827
15828            if (ps.frozen) {
15829                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15830                        "Failed to move already frozen package");
15831            }
15832            ps.frozen = true;
15833
15834            currentAsec = pkg.applicationInfo.isForwardLocked()
15835                    || pkg.applicationInfo.isExternalAsec();
15836            currentVolumeUuid = ps.volumeUuid;
15837            codeFile = new File(pkg.codePath);
15838            installerPackageName = ps.installerPackageName;
15839            packageAbiOverride = ps.cpuAbiOverrideString;
15840            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15841            seinfo = pkg.applicationInfo.seinfo;
15842            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15843        }
15844
15845        // Now that we're guarded by frozen state, kill app during move
15846        final long token = Binder.clearCallingIdentity();
15847        try {
15848            killApplication(packageName, appId, "move pkg");
15849        } finally {
15850            Binder.restoreCallingIdentity(token);
15851        }
15852
15853        final Bundle extras = new Bundle();
15854        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15855        extras.putString(Intent.EXTRA_TITLE, label);
15856        mMoveCallbacks.notifyCreated(moveId, extras);
15857
15858        int installFlags;
15859        final boolean moveCompleteApp;
15860        final File measurePath;
15861
15862        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15863            installFlags = INSTALL_INTERNAL;
15864            moveCompleteApp = !currentAsec;
15865            measurePath = Environment.getDataAppDirectory(volumeUuid);
15866        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15867            installFlags = INSTALL_EXTERNAL;
15868            moveCompleteApp = false;
15869            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15870        } else {
15871            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15872            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15873                    || !volume.isMountedWritable()) {
15874                unfreezePackage(packageName);
15875                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15876                        "Move location not mounted private volume");
15877            }
15878
15879            Preconditions.checkState(!currentAsec);
15880
15881            installFlags = INSTALL_INTERNAL;
15882            moveCompleteApp = true;
15883            measurePath = Environment.getDataAppDirectory(volumeUuid);
15884        }
15885
15886        final PackageStats stats = new PackageStats(null, -1);
15887        synchronized (mInstaller) {
15888            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15889                unfreezePackage(packageName);
15890                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15891                        "Failed to measure package size");
15892            }
15893        }
15894
15895        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15896                + stats.dataSize);
15897
15898        final long startFreeBytes = measurePath.getFreeSpace();
15899        final long sizeBytes;
15900        if (moveCompleteApp) {
15901            sizeBytes = stats.codeSize + stats.dataSize;
15902        } else {
15903            sizeBytes = stats.codeSize;
15904        }
15905
15906        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15907            unfreezePackage(packageName);
15908            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15909                    "Not enough free space to move");
15910        }
15911
15912        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15913
15914        final CountDownLatch installedLatch = new CountDownLatch(1);
15915        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15916            @Override
15917            public void onUserActionRequired(Intent intent) throws RemoteException {
15918                throw new IllegalStateException();
15919            }
15920
15921            @Override
15922            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15923                    Bundle extras) throws RemoteException {
15924                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15925                        + PackageManager.installStatusToString(returnCode, msg));
15926
15927                installedLatch.countDown();
15928
15929                // Regardless of success or failure of the move operation,
15930                // always unfreeze the package
15931                unfreezePackage(packageName);
15932
15933                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15934                switch (status) {
15935                    case PackageInstaller.STATUS_SUCCESS:
15936                        mMoveCallbacks.notifyStatusChanged(moveId,
15937                                PackageManager.MOVE_SUCCEEDED);
15938                        break;
15939                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15940                        mMoveCallbacks.notifyStatusChanged(moveId,
15941                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15942                        break;
15943                    default:
15944                        mMoveCallbacks.notifyStatusChanged(moveId,
15945                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15946                        break;
15947                }
15948            }
15949        };
15950
15951        final MoveInfo move;
15952        if (moveCompleteApp) {
15953            // Kick off a thread to report progress estimates
15954            new Thread() {
15955                @Override
15956                public void run() {
15957                    while (true) {
15958                        try {
15959                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15960                                break;
15961                            }
15962                        } catch (InterruptedException ignored) {
15963                        }
15964
15965                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15966                        final int progress = 10 + (int) MathUtils.constrain(
15967                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15968                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15969                    }
15970                }
15971            }.start();
15972
15973            final String dataAppName = codeFile.getName();
15974            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15975                    dataAppName, appId, seinfo);
15976        } else {
15977            move = null;
15978        }
15979
15980        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15981
15982        final Message msg = mHandler.obtainMessage(INIT_COPY);
15983        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15984        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15985                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15986        mHandler.sendMessage(msg);
15987    }
15988
15989    @Override
15990    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15991        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15992
15993        final int realMoveId = mNextMoveId.getAndIncrement();
15994        final Bundle extras = new Bundle();
15995        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15996        mMoveCallbacks.notifyCreated(realMoveId, extras);
15997
15998        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15999            @Override
16000            public void onCreated(int moveId, Bundle extras) {
16001                // Ignored
16002            }
16003
16004            @Override
16005            public void onStatusChanged(int moveId, int status, long estMillis) {
16006                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16007            }
16008        };
16009
16010        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16011        storage.setPrimaryStorageUuid(volumeUuid, callback);
16012        return realMoveId;
16013    }
16014
16015    @Override
16016    public int getMoveStatus(int moveId) {
16017        mContext.enforceCallingOrSelfPermission(
16018                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16019        return mMoveCallbacks.mLastStatus.get(moveId);
16020    }
16021
16022    @Override
16023    public void registerMoveCallback(IPackageMoveObserver callback) {
16024        mContext.enforceCallingOrSelfPermission(
16025                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16026        mMoveCallbacks.register(callback);
16027    }
16028
16029    @Override
16030    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16031        mContext.enforceCallingOrSelfPermission(
16032                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16033        mMoveCallbacks.unregister(callback);
16034    }
16035
16036    @Override
16037    public boolean setInstallLocation(int loc) {
16038        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16039                null);
16040        if (getInstallLocation() == loc) {
16041            return true;
16042        }
16043        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16044                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16045            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16046                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16047            return true;
16048        }
16049        return false;
16050   }
16051
16052    @Override
16053    public int getInstallLocation() {
16054        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16055                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16056                PackageHelper.APP_INSTALL_AUTO);
16057    }
16058
16059    /** Called by UserManagerService */
16060    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16061        mDirtyUsers.remove(userHandle);
16062        mSettings.removeUserLPw(userHandle);
16063        mPendingBroadcasts.remove(userHandle);
16064        if (mInstaller != null) {
16065            // Technically, we shouldn't be doing this with the package lock
16066            // held.  However, this is very rare, and there is already so much
16067            // other disk I/O going on, that we'll let it slide for now.
16068            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16069            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16070                final String volumeUuid = vol.getFsUuid();
16071                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16072                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16073            }
16074        }
16075        mUserNeedsBadging.delete(userHandle);
16076        removeUnusedPackagesLILPw(userManager, userHandle);
16077    }
16078
16079    /**
16080     * We're removing userHandle and would like to remove any downloaded packages
16081     * that are no longer in use by any other user.
16082     * @param userHandle the user being removed
16083     */
16084    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16085        final boolean DEBUG_CLEAN_APKS = false;
16086        int [] users = userManager.getUserIdsLPr();
16087        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16088        while (psit.hasNext()) {
16089            PackageSetting ps = psit.next();
16090            if (ps.pkg == null) {
16091                continue;
16092            }
16093            final String packageName = ps.pkg.packageName;
16094            // Skip over if system app
16095            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16096                continue;
16097            }
16098            if (DEBUG_CLEAN_APKS) {
16099                Slog.i(TAG, "Checking package " + packageName);
16100            }
16101            boolean keep = false;
16102            for (int i = 0; i < users.length; i++) {
16103                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16104                    keep = true;
16105                    if (DEBUG_CLEAN_APKS) {
16106                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16107                                + users[i]);
16108                    }
16109                    break;
16110                }
16111            }
16112            if (!keep) {
16113                if (DEBUG_CLEAN_APKS) {
16114                    Slog.i(TAG, "  Removing package " + packageName);
16115                }
16116                mHandler.post(new Runnable() {
16117                    public void run() {
16118                        deletePackageX(packageName, userHandle, 0);
16119                    } //end run
16120                });
16121            }
16122        }
16123    }
16124
16125    /** Called by UserManagerService */
16126    void createNewUserLILPw(int userHandle) {
16127        if (mInstaller != null) {
16128            mInstaller.createUserConfig(userHandle);
16129            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16130            applyFactoryDefaultBrowserLPw(userHandle);
16131            primeDomainVerificationsLPw(userHandle);
16132        }
16133    }
16134
16135    void newUserCreated(final int userHandle) {
16136        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16137    }
16138
16139    @Override
16140    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16141        mContext.enforceCallingOrSelfPermission(
16142                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16143                "Only package verification agents can read the verifier device identity");
16144
16145        synchronized (mPackages) {
16146            return mSettings.getVerifierDeviceIdentityLPw();
16147        }
16148    }
16149
16150    @Override
16151    public void setPermissionEnforced(String permission, boolean enforced) {
16152        // TODO: Now that we no longer change GID for storage, this should to away.
16153        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16154                "setPermissionEnforced");
16155        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16156            synchronized (mPackages) {
16157                if (mSettings.mReadExternalStorageEnforced == null
16158                        || mSettings.mReadExternalStorageEnforced != enforced) {
16159                    mSettings.mReadExternalStorageEnforced = enforced;
16160                    mSettings.writeLPr();
16161                }
16162            }
16163            // kill any non-foreground processes so we restart them and
16164            // grant/revoke the GID.
16165            final IActivityManager am = ActivityManagerNative.getDefault();
16166            if (am != null) {
16167                final long token = Binder.clearCallingIdentity();
16168                try {
16169                    am.killProcessesBelowForeground("setPermissionEnforcement");
16170                } catch (RemoteException e) {
16171                } finally {
16172                    Binder.restoreCallingIdentity(token);
16173                }
16174            }
16175        } else {
16176            throw new IllegalArgumentException("No selective enforcement for " + permission);
16177        }
16178    }
16179
16180    @Override
16181    @Deprecated
16182    public boolean isPermissionEnforced(String permission) {
16183        return true;
16184    }
16185
16186    @Override
16187    public boolean isStorageLow() {
16188        final long token = Binder.clearCallingIdentity();
16189        try {
16190            final DeviceStorageMonitorInternal
16191                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16192            if (dsm != null) {
16193                return dsm.isMemoryLow();
16194            } else {
16195                return false;
16196            }
16197        } finally {
16198            Binder.restoreCallingIdentity(token);
16199        }
16200    }
16201
16202    @Override
16203    public IPackageInstaller getPackageInstaller() {
16204        return mInstallerService;
16205    }
16206
16207    private boolean userNeedsBadging(int userId) {
16208        int index = mUserNeedsBadging.indexOfKey(userId);
16209        if (index < 0) {
16210            final UserInfo userInfo;
16211            final long token = Binder.clearCallingIdentity();
16212            try {
16213                userInfo = sUserManager.getUserInfo(userId);
16214            } finally {
16215                Binder.restoreCallingIdentity(token);
16216            }
16217            final boolean b;
16218            if (userInfo != null && userInfo.isManagedProfile()) {
16219                b = true;
16220            } else {
16221                b = false;
16222            }
16223            mUserNeedsBadging.put(userId, b);
16224            return b;
16225        }
16226        return mUserNeedsBadging.valueAt(index);
16227    }
16228
16229    @Override
16230    public KeySet getKeySetByAlias(String packageName, String alias) {
16231        if (packageName == null || alias == null) {
16232            return null;
16233        }
16234        synchronized(mPackages) {
16235            final PackageParser.Package pkg = mPackages.get(packageName);
16236            if (pkg == null) {
16237                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16238                throw new IllegalArgumentException("Unknown package: " + packageName);
16239            }
16240            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16241            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16242        }
16243    }
16244
16245    @Override
16246    public KeySet getSigningKeySet(String packageName) {
16247        if (packageName == null) {
16248            return null;
16249        }
16250        synchronized(mPackages) {
16251            final PackageParser.Package pkg = mPackages.get(packageName);
16252            if (pkg == null) {
16253                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16254                throw new IllegalArgumentException("Unknown package: " + packageName);
16255            }
16256            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16257                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16258                throw new SecurityException("May not access signing KeySet of other apps.");
16259            }
16260            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16261            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16262        }
16263    }
16264
16265    @Override
16266    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16267        if (packageName == null || ks == null) {
16268            return false;
16269        }
16270        synchronized(mPackages) {
16271            final PackageParser.Package pkg = mPackages.get(packageName);
16272            if (pkg == null) {
16273                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16274                throw new IllegalArgumentException("Unknown package: " + packageName);
16275            }
16276            IBinder ksh = ks.getToken();
16277            if (ksh instanceof KeySetHandle) {
16278                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16279                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16280            }
16281            return false;
16282        }
16283    }
16284
16285    @Override
16286    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16287        if (packageName == null || ks == null) {
16288            return false;
16289        }
16290        synchronized(mPackages) {
16291            final PackageParser.Package pkg = mPackages.get(packageName);
16292            if (pkg == null) {
16293                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16294                throw new IllegalArgumentException("Unknown package: " + packageName);
16295            }
16296            IBinder ksh = ks.getToken();
16297            if (ksh instanceof KeySetHandle) {
16298                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16299                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16300            }
16301            return false;
16302        }
16303    }
16304
16305    public void getUsageStatsIfNoPackageUsageInfo() {
16306        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16307            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16308            if (usm == null) {
16309                throw new IllegalStateException("UsageStatsManager must be initialized");
16310            }
16311            long now = System.currentTimeMillis();
16312            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16313            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16314                String packageName = entry.getKey();
16315                PackageParser.Package pkg = mPackages.get(packageName);
16316                if (pkg == null) {
16317                    continue;
16318                }
16319                UsageStats usage = entry.getValue();
16320                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16321                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16322            }
16323        }
16324    }
16325
16326    /**
16327     * Check and throw if the given before/after packages would be considered a
16328     * downgrade.
16329     */
16330    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16331            throws PackageManagerException {
16332        if (after.versionCode < before.mVersionCode) {
16333            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16334                    "Update version code " + after.versionCode + " is older than current "
16335                    + before.mVersionCode);
16336        } else if (after.versionCode == before.mVersionCode) {
16337            if (after.baseRevisionCode < before.baseRevisionCode) {
16338                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16339                        "Update base revision code " + after.baseRevisionCode
16340                        + " is older than current " + before.baseRevisionCode);
16341            }
16342
16343            if (!ArrayUtils.isEmpty(after.splitNames)) {
16344                for (int i = 0; i < after.splitNames.length; i++) {
16345                    final String splitName = after.splitNames[i];
16346                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16347                    if (j != -1) {
16348                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16349                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16350                                    "Update split " + splitName + " revision code "
16351                                    + after.splitRevisionCodes[i] + " is older than current "
16352                                    + before.splitRevisionCodes[j]);
16353                        }
16354                    }
16355                }
16356            }
16357        }
16358    }
16359
16360    private static class MoveCallbacks extends Handler {
16361        private static final int MSG_CREATED = 1;
16362        private static final int MSG_STATUS_CHANGED = 2;
16363
16364        private final RemoteCallbackList<IPackageMoveObserver>
16365                mCallbacks = new RemoteCallbackList<>();
16366
16367        private final SparseIntArray mLastStatus = new SparseIntArray();
16368
16369        public MoveCallbacks(Looper looper) {
16370            super(looper);
16371        }
16372
16373        public void register(IPackageMoveObserver callback) {
16374            mCallbacks.register(callback);
16375        }
16376
16377        public void unregister(IPackageMoveObserver callback) {
16378            mCallbacks.unregister(callback);
16379        }
16380
16381        @Override
16382        public void handleMessage(Message msg) {
16383            final SomeArgs args = (SomeArgs) msg.obj;
16384            final int n = mCallbacks.beginBroadcast();
16385            for (int i = 0; i < n; i++) {
16386                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16387                try {
16388                    invokeCallback(callback, msg.what, args);
16389                } catch (RemoteException ignored) {
16390                }
16391            }
16392            mCallbacks.finishBroadcast();
16393            args.recycle();
16394        }
16395
16396        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16397                throws RemoteException {
16398            switch (what) {
16399                case MSG_CREATED: {
16400                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16401                    break;
16402                }
16403                case MSG_STATUS_CHANGED: {
16404                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16405                    break;
16406                }
16407            }
16408        }
16409
16410        private void notifyCreated(int moveId, Bundle extras) {
16411            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16412
16413            final SomeArgs args = SomeArgs.obtain();
16414            args.argi1 = moveId;
16415            args.arg2 = extras;
16416            obtainMessage(MSG_CREATED, args).sendToTarget();
16417        }
16418
16419        private void notifyStatusChanged(int moveId, int status) {
16420            notifyStatusChanged(moveId, status, -1);
16421        }
16422
16423        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16424            Slog.v(TAG, "Move " + moveId + " status " + status);
16425
16426            final SomeArgs args = SomeArgs.obtain();
16427            args.argi1 = moveId;
16428            args.argi2 = status;
16429            args.arg3 = estMillis;
16430            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16431
16432            synchronized (mLastStatus) {
16433                mLastStatus.put(moveId, status);
16434            }
16435        }
16436    }
16437
16438    private final class OnPermissionChangeListeners extends Handler {
16439        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16440
16441        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16442                new RemoteCallbackList<>();
16443
16444        public OnPermissionChangeListeners(Looper looper) {
16445            super(looper);
16446        }
16447
16448        @Override
16449        public void handleMessage(Message msg) {
16450            switch (msg.what) {
16451                case MSG_ON_PERMISSIONS_CHANGED: {
16452                    final int uid = msg.arg1;
16453                    handleOnPermissionsChanged(uid);
16454                } break;
16455            }
16456        }
16457
16458        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16459            mPermissionListeners.register(listener);
16460
16461        }
16462
16463        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16464            mPermissionListeners.unregister(listener);
16465        }
16466
16467        public void onPermissionsChanged(int uid) {
16468            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16469                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16470            }
16471        }
16472
16473        private void handleOnPermissionsChanged(int uid) {
16474            final int count = mPermissionListeners.beginBroadcast();
16475            try {
16476                for (int i = 0; i < count; i++) {
16477                    IOnPermissionsChangeListener callback = mPermissionListeners
16478                            .getBroadcastItem(i);
16479                    try {
16480                        callback.onPermissionsChanged(uid);
16481                    } catch (RemoteException e) {
16482                        Log.e(TAG, "Permission listener is dead", e);
16483                    }
16484                }
16485            } finally {
16486                mPermissionListeners.finishBroadcast();
16487            }
16488        }
16489    }
16490
16491    private class PackageManagerInternalImpl extends PackageManagerInternal {
16492        @Override
16493        public void setLocationPackagesProvider(PackagesProvider provider) {
16494            synchronized (mPackages) {
16495                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16496            }
16497        }
16498
16499        @Override
16500        public void setImePackagesProvider(PackagesProvider provider) {
16501            synchronized (mPackages) {
16502                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16503            }
16504        }
16505
16506        @Override
16507        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16508            synchronized (mPackages) {
16509                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16510            }
16511        }
16512
16513        @Override
16514        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16515            synchronized (mPackages) {
16516                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16517            }
16518        }
16519
16520        @Override
16521        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16522            synchronized (mPackages) {
16523                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16524            }
16525        }
16526
16527        @Override
16528        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16529            synchronized (mPackages) {
16530                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16531            }
16532        }
16533
16534        @Override
16535        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16536            synchronized (mPackages) {
16537                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16538            }
16539        }
16540
16541        @Override
16542        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16543            synchronized (mPackages) {
16544                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16545                        packageName, userId);
16546            }
16547        }
16548
16549        @Override
16550        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16551            synchronized (mPackages) {
16552                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16553                        packageName, userId);
16554            }
16555        }
16556        @Override
16557        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16558            synchronized (mPackages) {
16559                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16560                        packageName, userId);
16561            }
16562        }
16563    }
16564
16565    @Override
16566    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16567        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16568        synchronized (mPackages) {
16569            final long identity = Binder.clearCallingIdentity();
16570            try {
16571                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16572                        packageNames, userId);
16573            } finally {
16574                Binder.restoreCallingIdentity(identity);
16575            }
16576        }
16577    }
16578
16579    private static void enforceSystemOrPhoneCaller(String tag) {
16580        int callingUid = Binder.getCallingUid();
16581        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16582            throw new SecurityException(
16583                    "Cannot call " + tag + " from UID " + callingUid);
16584        }
16585    }
16586}
16587