PackageManagerService.java revision ad3b2975574f916c14382628d50c710a78064746
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.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
29import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
30import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
37import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
38import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
39import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
40import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
47import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
48import static android.content.pm.PackageManager.INSTALL_INTERNAL;
49import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
53import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
54import static android.content.pm.PackageManager.MATCH_ALL;
55import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
56import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
57import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
58import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
59import static android.content.pm.PackageManager.PERMISSION_GRANTED;
60import static android.content.pm.PackageParser.isApkFile;
61import static android.os.Process.PACKAGE_INFO_GID;
62import static android.os.Process.SYSTEM_UID;
63import static android.system.OsConstants.O_CREAT;
64import static android.system.OsConstants.O_RDWR;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
66import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
67import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
68import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
69import static com.android.internal.util.ArrayUtils.appendInt;
70import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
72import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
73import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
74import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
75
76import android.Manifest;
77import android.app.ActivityManager;
78import android.app.ActivityManagerNative;
79import android.app.AppGlobals;
80import android.app.IActivityManager;
81import android.app.admin.IDevicePolicyManager;
82import android.app.backup.IBackupManager;
83import android.app.usage.UsageStats;
84import android.app.usage.UsageStatsManager;
85import android.content.BroadcastReceiver;
86import android.content.ComponentName;
87import android.content.Context;
88import android.content.IIntentReceiver;
89import android.content.Intent;
90import android.content.IntentFilter;
91import android.content.IntentSender;
92import android.content.IntentSender.SendIntentException;
93import android.content.ServiceConnection;
94import android.content.pm.ActivityInfo;
95import android.content.pm.ApplicationInfo;
96import android.content.pm.FeatureInfo;
97import android.content.pm.IOnPermissionsChangeListener;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.IntentFilterVerificationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageManagerInternal;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Debug;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteCallbackList;
152import android.os.RemoteException;
153import android.os.SELinux;
154import android.os.ServiceManager;
155import android.os.SystemClock;
156import android.os.SystemProperties;
157import android.os.UserHandle;
158import android.os.UserManager;
159import android.os.storage.IMountService;
160import android.os.storage.StorageEventListener;
161import android.os.storage.StorageManager;
162import android.os.storage.VolumeInfo;
163import android.os.storage.VolumeRecord;
164import android.security.KeyStore;
165import android.security.SystemKeyStore;
166import android.system.ErrnoException;
167import android.system.Os;
168import android.system.StructStat;
169import android.text.TextUtils;
170import android.text.format.DateUtils;
171import android.util.ArrayMap;
172import android.util.ArraySet;
173import android.util.AtomicFile;
174import android.util.DisplayMetrics;
175import android.util.EventLog;
176import android.util.ExceptionUtils;
177import android.util.Log;
178import android.util.LogPrinter;
179import android.util.MathUtils;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.util.SparseIntArray;
185import android.util.Xml;
186import android.view.Display;
187
188import dalvik.system.DexFile;
189import dalvik.system.VMRuntime;
190
191import libcore.io.IoUtils;
192import libcore.util.EmptyArray;
193
194import com.android.internal.R;
195import com.android.internal.annotations.GuardedBy;
196import com.android.internal.app.IMediaContainerService;
197import com.android.internal.app.ResolverActivity;
198import com.android.internal.content.NativeLibraryHelper;
199import com.android.internal.content.PackageHelper;
200import com.android.internal.os.IParcelFileDescriptorFactory;
201import com.android.internal.os.SomeArgs;
202import com.android.internal.os.Zygote;
203import com.android.internal.util.ArrayUtils;
204import com.android.internal.util.FastPrintWriter;
205import com.android.internal.util.FastXmlSerializer;
206import com.android.internal.util.IndentingPrintWriter;
207import com.android.internal.util.Preconditions;
208import com.android.server.EventLogTags;
209import com.android.server.FgThread;
210import com.android.server.IntentResolver;
211import com.android.server.LocalServices;
212import com.android.server.ServiceThread;
213import com.android.server.SystemConfig;
214import com.android.server.Watchdog;
215import com.android.server.pm.PermissionsState.PermissionState;
216import com.android.server.pm.Settings.DatabaseVersion;
217import com.android.server.storage.DeviceStorageMonitorInternal;
218
219import org.xmlpull.v1.XmlPullParser;
220import org.xmlpull.v1.XmlPullParserException;
221import org.xmlpull.v1.XmlSerializer;
222
223import java.io.BufferedInputStream;
224import java.io.BufferedOutputStream;
225import java.io.BufferedReader;
226import java.io.ByteArrayInputStream;
227import java.io.ByteArrayOutputStream;
228import java.io.File;
229import java.io.FileDescriptor;
230import java.io.FileNotFoundException;
231import java.io.FileOutputStream;
232import java.io.FileReader;
233import java.io.FilenameFilter;
234import java.io.IOException;
235import java.io.InputStream;
236import java.io.PrintWriter;
237import java.nio.charset.StandardCharsets;
238import java.security.NoSuchAlgorithmException;
239import java.security.PublicKey;
240import java.security.cert.CertificateEncodingException;
241import java.security.cert.CertificateException;
242import java.text.SimpleDateFormat;
243import java.util.ArrayList;
244import java.util.Arrays;
245import java.util.Collection;
246import java.util.Collections;
247import java.util.Comparator;
248import java.util.Date;
249import java.util.Iterator;
250import java.util.List;
251import java.util.Map;
252import java.util.Objects;
253import java.util.Set;
254import java.util.concurrent.CountDownLatch;
255import java.util.concurrent.TimeUnit;
256import java.util.concurrent.atomic.AtomicBoolean;
257import java.util.concurrent.atomic.AtomicInteger;
258import java.util.concurrent.atomic.AtomicLong;
259
260/**
261 * Keep track of all those .apks everywhere.
262 *
263 * This is very central to the platform's security; please run the unit
264 * tests whenever making modifications here:
265 *
266mmm frameworks/base/tests/AndroidTests
267adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
268adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
269 *
270 * {@hide}
271 */
272public class PackageManagerService extends IPackageManager.Stub {
273    static final String TAG = "PackageManager";
274    static final boolean DEBUG_SETTINGS = false;
275    static final boolean DEBUG_PREFERRED = false;
276    static final boolean DEBUG_UPGRADE = false;
277    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
278    private static final boolean DEBUG_BACKUP = true;
279    private static final boolean DEBUG_INSTALL = false;
280    private static final boolean DEBUG_REMOVE = false;
281    private static final boolean DEBUG_BROADCASTS = false;
282    private static final boolean DEBUG_SHOW_INFO = false;
283    private static final boolean DEBUG_PACKAGE_INFO = false;
284    private static final boolean DEBUG_INTENT_MATCHING = false;
285    private static final boolean DEBUG_PACKAGE_SCANNING = false;
286    private static final boolean DEBUG_VERIFY = false;
287    private static final boolean DEBUG_DEXOPT = false;
288    private static final boolean DEBUG_ABI_SELECTION = false;
289
290    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
291
292    private static final int RADIO_UID = Process.PHONE_UID;
293    private static final int LOG_UID = Process.LOG_UID;
294    private static final int NFC_UID = Process.NFC_UID;
295    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
296    private static final int SHELL_UID = Process.SHELL_UID;
297
298    // Cap the size of permission trees that 3rd party apps can define
299    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
300
301    // Suffix used during package installation when copying/moving
302    // package apks to install directory.
303    private static final String INSTALL_PACKAGE_SUFFIX = "-";
304
305    static final int SCAN_NO_DEX = 1<<1;
306    static final int SCAN_FORCE_DEX = 1<<2;
307    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
308    static final int SCAN_NEW_INSTALL = 1<<4;
309    static final int SCAN_NO_PATHS = 1<<5;
310    static final int SCAN_UPDATE_TIME = 1<<6;
311    static final int SCAN_DEFER_DEX = 1<<7;
312    static final int SCAN_BOOTING = 1<<8;
313    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
314    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
315    static final int SCAN_REQUIRE_KNOWN = 1<<12;
316    static final int SCAN_MOVE = 1<<13;
317    static final int SCAN_INITIAL = 1<<14;
318
319    static final int REMOVE_CHATTY = 1<<16;
320
321    private static final int[] EMPTY_INT_ARRAY = new int[0];
322
323    /**
324     * Timeout (in milliseconds) after which the watchdog should declare that
325     * our handler thread is wedged.  The usual default for such things is one
326     * minute but we sometimes do very lengthy I/O operations on this thread,
327     * such as installing multi-gigabyte applications, so ours needs to be longer.
328     */
329    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
330
331    /**
332     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
333     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
334     * settings entry if available, otherwise we use the hardcoded default.  If it's been
335     * more than this long since the last fstrim, we force one during the boot sequence.
336     *
337     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
338     * one gets run at the next available charging+idle time.  This final mandatory
339     * no-fstrim check kicks in only of the other scheduling criteria is never met.
340     */
341    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
342
343    /**
344     * Whether verification is enabled by default.
345     */
346    private static final boolean DEFAULT_VERIFY_ENABLE = true;
347
348    /**
349     * The default maximum time to wait for the verification agent to return in
350     * milliseconds.
351     */
352    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
353
354    /**
355     * The default response for package verification timeout.
356     *
357     * This can be either PackageManager.VERIFICATION_ALLOW or
358     * PackageManager.VERIFICATION_REJECT.
359     */
360    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
361
362    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
363
364    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
365            DEFAULT_CONTAINER_PACKAGE,
366            "com.android.defcontainer.DefaultContainerService");
367
368    private static final String KILL_APP_REASON_GIDS_CHANGED =
369            "permission grant or revoke changed gids";
370
371    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
372            "permissions revoked";
373
374    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
375
376    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
377
378    /** Permission grant: not grant the permission. */
379    private static final int GRANT_DENIED = 1;
380
381    /** Permission grant: grant the permission as an install permission. */
382    private static final int GRANT_INSTALL = 2;
383
384    /** Permission grant: grant the permission as an install permission for a legacy app. */
385    private static final int GRANT_INSTALL_LEGACY = 3;
386
387    /** Permission grant: grant the permission as a runtime one. */
388    private static final int GRANT_RUNTIME = 4;
389
390    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
391    private static final int GRANT_UPGRADE = 5;
392
393    /** Canonical intent used to identify what counts as a "web browser" app */
394    private static final Intent sBrowserIntent;
395    static {
396        sBrowserIntent = new Intent();
397        sBrowserIntent.setAction(Intent.ACTION_VIEW);
398        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
399        sBrowserIntent.setData(Uri.parse("http:"));
400    }
401
402    final ServiceThread mHandlerThread;
403
404    final PackageHandler mHandler;
405
406    /**
407     * Messages for {@link #mHandler} that need to wait for system ready before
408     * being dispatched.
409     */
410    private ArrayList<Message> mPostSystemReadyMessages;
411
412    final int mSdkVersion = Build.VERSION.SDK_INT;
413
414    final Context mContext;
415    final boolean mFactoryTest;
416    final boolean mOnlyCore;
417    final boolean mLazyDexOpt;
418    final long mDexOptLRUThresholdInMills;
419    final DisplayMetrics mMetrics;
420    final int mDefParseFlags;
421    final String[] mSeparateProcesses;
422    final boolean mIsUpgrade;
423
424    // This is where all application persistent data goes.
425    final File mAppDataDir;
426
427    // This is where all application persistent data goes for secondary users.
428    final File mUserAppDataDir;
429
430    /** The location for ASEC container files on internal storage. */
431    final String mAsecInternalPath;
432
433    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
434    // LOCK HELD.  Can be called with mInstallLock held.
435    @GuardedBy("mInstallLock")
436    final Installer mInstaller;
437
438    /** Directory where installed third-party apps stored */
439    final File mAppInstallDir;
440
441    /**
442     * Directory to which applications installed internally have their
443     * 32 bit native libraries copied.
444     */
445    private File mAppLib32InstallDir;
446
447    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
448    // apps.
449    final File mDrmAppPrivateInstallDir;
450
451    // ----------------------------------------------------------------
452
453    // Lock for state used when installing and doing other long running
454    // operations.  Methods that must be called with this lock held have
455    // the suffix "LI".
456    final Object mInstallLock = new Object();
457
458    // ----------------------------------------------------------------
459
460    // Keys are String (package name), values are Package.  This also serves
461    // as the lock for the global state.  Methods that must be called with
462    // this lock held have the prefix "LP".
463    @GuardedBy("mPackages")
464    final ArrayMap<String, PackageParser.Package> mPackages =
465            new ArrayMap<String, PackageParser.Package>();
466
467    // Tracks available target package names -> overlay package paths.
468    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
469        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
470
471    final Settings mSettings;
472    boolean mRestoredSettings;
473
474    // System configuration read by SystemConfig.
475    final int[] mGlobalGids;
476    final SparseArray<ArraySet<String>> mSystemPermissions;
477    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
478
479    // If mac_permissions.xml was found for seinfo labeling.
480    boolean mFoundPolicyFile;
481
482    // If a recursive restorecon of /data/data/<pkg> is needed.
483    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
484
485    public static final class SharedLibraryEntry {
486        public final String path;
487        public final String apk;
488
489        SharedLibraryEntry(String _path, String _apk) {
490            path = _path;
491            apk = _apk;
492        }
493    }
494
495    // Currently known shared libraries.
496    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
497            new ArrayMap<String, SharedLibraryEntry>();
498
499    // All available activities, for your resolving pleasure.
500    final ActivityIntentResolver mActivities =
501            new ActivityIntentResolver();
502
503    // All available receivers, for your resolving pleasure.
504    final ActivityIntentResolver mReceivers =
505            new ActivityIntentResolver();
506
507    // All available services, for your resolving pleasure.
508    final ServiceIntentResolver mServices = new ServiceIntentResolver();
509
510    // All available providers, for your resolving pleasure.
511    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
512
513    // Mapping from provider base names (first directory in content URI codePath)
514    // to the provider information.
515    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
516            new ArrayMap<String, PackageParser.Provider>();
517
518    // Mapping from instrumentation class names to info about them.
519    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
520            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
521
522    // Mapping from permission names to info about them.
523    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
524            new ArrayMap<String, PackageParser.PermissionGroup>();
525
526    // Packages whose data we have transfered into another package, thus
527    // should no longer exist.
528    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
529
530    // Broadcast actions that are only available to the system.
531    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
532
533    /** List of packages waiting for verification. */
534    final SparseArray<PackageVerificationState> mPendingVerification
535            = new SparseArray<PackageVerificationState>();
536
537    /** Set of packages associated with each app op permission. */
538    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
539
540    final PackageInstallerService mInstallerService;
541
542    private final PackageDexOptimizer mPackageDexOptimizer;
543
544    private AtomicInteger mNextMoveId = new AtomicInteger();
545    private final MoveCallbacks mMoveCallbacks;
546
547    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
548
549    // Cache of users who need badging.
550    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
551
552    /** Token for keys in mPendingVerification. */
553    private int mPendingVerificationToken = 0;
554
555    volatile boolean mSystemReady;
556    volatile boolean mSafeMode;
557    volatile boolean mHasSystemUidErrors;
558
559    ApplicationInfo mAndroidApplication;
560    final ActivityInfo mResolveActivity = new ActivityInfo();
561    final ResolveInfo mResolveInfo = new ResolveInfo();
562    ComponentName mResolveComponentName;
563    PackageParser.Package mPlatformPackage;
564    ComponentName mCustomResolverComponentName;
565
566    boolean mResolverReplaced = false;
567
568    private final ComponentName mIntentFilterVerifierComponent;
569    private int mIntentFilterVerificationToken = 0;
570
571    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
572            = new SparseArray<IntentFilterVerificationState>();
573
574    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
575            new DefaultPermissionGrantPolicy(this);
576
577    private static class IFVerificationParams {
578        PackageParser.Package pkg;
579        boolean replacing;
580        int userId;
581        int verifierUid;
582
583        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
584                int _userId, int _verifierUid) {
585            pkg = _pkg;
586            replacing = _replacing;
587            userId = _userId;
588            replacing = _replacing;
589            verifierUid = _verifierUid;
590        }
591    }
592
593    private interface IntentFilterVerifier<T extends IntentFilter> {
594        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
595                                               T filter, String packageName);
596        void startVerifications(int userId);
597        void receiveVerificationResponse(int verificationId);
598    }
599
600    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
601        private Context mContext;
602        private ComponentName mIntentFilterVerifierComponent;
603        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
604
605        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
606            mContext = context;
607            mIntentFilterVerifierComponent = verifierComponent;
608        }
609
610        private String getDefaultScheme() {
611            return IntentFilter.SCHEME_HTTPS;
612        }
613
614        @Override
615        public void startVerifications(int userId) {
616            // Launch verifications requests
617            int count = mCurrentIntentFilterVerifications.size();
618            for (int n=0; n<count; n++) {
619                int verificationId = mCurrentIntentFilterVerifications.get(n);
620                final IntentFilterVerificationState ivs =
621                        mIntentFilterVerificationStates.get(verificationId);
622
623                String packageName = ivs.getPackageName();
624
625                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
626                final int filterCount = filters.size();
627                ArraySet<String> domainsSet = new ArraySet<>();
628                for (int m=0; m<filterCount; m++) {
629                    PackageParser.ActivityIntentInfo filter = filters.get(m);
630                    domainsSet.addAll(filter.getHostsList());
631                }
632                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
633                synchronized (mPackages) {
634                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
635                            packageName, domainsList) != null) {
636                        scheduleWriteSettingsLocked();
637                    }
638                }
639                sendVerificationRequest(userId, verificationId, ivs);
640            }
641            mCurrentIntentFilterVerifications.clear();
642        }
643
644        private void sendVerificationRequest(int userId, int verificationId,
645                IntentFilterVerificationState ivs) {
646
647            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
648            verificationIntent.putExtra(
649                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
650                    verificationId);
651            verificationIntent.putExtra(
652                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
653                    getDefaultScheme());
654            verificationIntent.putExtra(
655                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
656                    ivs.getHostsString());
657            verificationIntent.putExtra(
658                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
659                    ivs.getPackageName());
660            verificationIntent.setComponent(mIntentFilterVerifierComponent);
661            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
662
663            UserHandle user = new UserHandle(userId);
664            mContext.sendBroadcastAsUser(verificationIntent, user);
665            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
666                    "Sending IntentFilter verification broadcast");
667        }
668
669        public void receiveVerificationResponse(int verificationId) {
670            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
671
672            final boolean verified = ivs.isVerified();
673
674            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
675            final int count = filters.size();
676            if (DEBUG_DOMAIN_VERIFICATION) {
677                Slog.i(TAG, "Received verification response " + verificationId
678                        + " for " + count + " filters, verified=" + verified);
679            }
680            for (int n=0; n<count; n++) {
681                PackageParser.ActivityIntentInfo filter = filters.get(n);
682                filter.setVerified(verified);
683
684                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
685                        + " verified with result:" + verified + " and hosts:"
686                        + ivs.getHostsString());
687            }
688
689            mIntentFilterVerificationStates.remove(verificationId);
690
691            final String packageName = ivs.getPackageName();
692            IntentFilterVerificationInfo ivi = null;
693
694            synchronized (mPackages) {
695                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
696            }
697            if (ivi == null) {
698                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
699                        + verificationId + " packageName:" + packageName);
700                return;
701            }
702            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
703                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
704
705            synchronized (mPackages) {
706                if (verified) {
707                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
708                } else {
709                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
710                }
711                scheduleWriteSettingsLocked();
712
713                final int userId = ivs.getUserId();
714                if (userId != UserHandle.USER_ALL) {
715                    final int userStatus =
716                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
717
718                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
719                    boolean needUpdate = false;
720
721                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
722                    // already been set by the User thru the Disambiguation dialog
723                    switch (userStatus) {
724                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
725                            if (verified) {
726                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
727                            } else {
728                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
729                            }
730                            needUpdate = true;
731                            break;
732
733                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
734                            if (verified) {
735                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
736                                needUpdate = true;
737                            }
738                            break;
739
740                        default:
741                            // Nothing to do
742                    }
743
744                    if (needUpdate) {
745                        mSettings.updateIntentFilterVerificationStatusLPw(
746                                packageName, updatedStatus, userId);
747                        scheduleWritePackageRestrictionsLocked(userId);
748                    }
749                }
750            }
751        }
752
753        @Override
754        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
755                    ActivityIntentInfo filter, String packageName) {
756            if (!hasValidDomains(filter)) {
757                return false;
758            }
759            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
760            if (ivs == null) {
761                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
762                        packageName);
763            }
764            if (DEBUG_DOMAIN_VERIFICATION) {
765                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
766            }
767            ivs.addFilter(filter);
768            return true;
769        }
770
771        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
772                int userId, int verificationId, String packageName) {
773            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
774                    verifierUid, userId, packageName);
775            ivs.setPendingState();
776            synchronized (mPackages) {
777                mIntentFilterVerificationStates.append(verificationId, ivs);
778                mCurrentIntentFilterVerifications.add(verificationId);
779            }
780            return ivs;
781        }
782    }
783
784    private static boolean hasValidDomains(ActivityIntentInfo filter) {
785        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
786                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
787        if (!hasHTTPorHTTPS) {
788            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
789                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
790            return false;
791        }
792        return true;
793    }
794
795    private IntentFilterVerifier mIntentFilterVerifier;
796
797    // Set of pending broadcasts for aggregating enable/disable of components.
798    static class PendingPackageBroadcasts {
799        // for each user id, a map of <package name -> components within that package>
800        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
801
802        public PendingPackageBroadcasts() {
803            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
804        }
805
806        public ArrayList<String> get(int userId, String packageName) {
807            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
808            return packages.get(packageName);
809        }
810
811        public void put(int userId, String packageName, ArrayList<String> components) {
812            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
813            packages.put(packageName, components);
814        }
815
816        public void remove(int userId, String packageName) {
817            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
818            if (packages != null) {
819                packages.remove(packageName);
820            }
821        }
822
823        public void remove(int userId) {
824            mUidMap.remove(userId);
825        }
826
827        public int userIdCount() {
828            return mUidMap.size();
829        }
830
831        public int userIdAt(int n) {
832            return mUidMap.keyAt(n);
833        }
834
835        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
836            return mUidMap.get(userId);
837        }
838
839        public int size() {
840            // total number of pending broadcast entries across all userIds
841            int num = 0;
842            for (int i = 0; i< mUidMap.size(); i++) {
843                num += mUidMap.valueAt(i).size();
844            }
845            return num;
846        }
847
848        public void clear() {
849            mUidMap.clear();
850        }
851
852        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
853            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
854            if (map == null) {
855                map = new ArrayMap<String, ArrayList<String>>();
856                mUidMap.put(userId, map);
857            }
858            return map;
859        }
860    }
861    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
862
863    // Service Connection to remote media container service to copy
864    // package uri's from external media onto secure containers
865    // or internal storage.
866    private IMediaContainerService mContainerService = null;
867
868    static final int SEND_PENDING_BROADCAST = 1;
869    static final int MCS_BOUND = 3;
870    static final int END_COPY = 4;
871    static final int INIT_COPY = 5;
872    static final int MCS_UNBIND = 6;
873    static final int START_CLEANING_PACKAGE = 7;
874    static final int FIND_INSTALL_LOC = 8;
875    static final int POST_INSTALL = 9;
876    static final int MCS_RECONNECT = 10;
877    static final int MCS_GIVE_UP = 11;
878    static final int UPDATED_MEDIA_STATUS = 12;
879    static final int WRITE_SETTINGS = 13;
880    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
881    static final int PACKAGE_VERIFIED = 15;
882    static final int CHECK_PENDING_VERIFICATION = 16;
883    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
884    static final int INTENT_FILTER_VERIFIED = 18;
885
886    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
887
888    // Delay time in millisecs
889    static final int BROADCAST_DELAY = 10 * 1000;
890
891    static UserManagerService sUserManager;
892
893    // Stores a list of users whose package restrictions file needs to be updated
894    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
895
896    final private DefaultContainerConnection mDefContainerConn =
897            new DefaultContainerConnection();
898    class DefaultContainerConnection implements ServiceConnection {
899        public void onServiceConnected(ComponentName name, IBinder service) {
900            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
901            IMediaContainerService imcs =
902                IMediaContainerService.Stub.asInterface(service);
903            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
904        }
905
906        public void onServiceDisconnected(ComponentName name) {
907            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
908        }
909    }
910
911    // Recordkeeping of restore-after-install operations that are currently in flight
912    // between the Package Manager and the Backup Manager
913    class PostInstallData {
914        public InstallArgs args;
915        public PackageInstalledInfo res;
916
917        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
918            args = _a;
919            res = _r;
920        }
921    }
922
923    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
924    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
925
926    // XML tags for backup/restore of various bits of state
927    private static final String TAG_PREFERRED_BACKUP = "pa";
928    private static final String TAG_DEFAULT_APPS = "da";
929    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
930
931    final String mRequiredVerifierPackage;
932    final String mRequiredInstallerPackage;
933
934    private final PackageUsage mPackageUsage = new PackageUsage();
935
936    private class PackageUsage {
937        private static final int WRITE_INTERVAL
938            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
939
940        private final Object mFileLock = new Object();
941        private final AtomicLong mLastWritten = new AtomicLong(0);
942        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
943
944        private boolean mIsHistoricalPackageUsageAvailable = true;
945
946        boolean isHistoricalPackageUsageAvailable() {
947            return mIsHistoricalPackageUsageAvailable;
948        }
949
950        void write(boolean force) {
951            if (force) {
952                writeInternal();
953                return;
954            }
955            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
956                && !DEBUG_DEXOPT) {
957                return;
958            }
959            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
960                new Thread("PackageUsage_DiskWriter") {
961                    @Override
962                    public void run() {
963                        try {
964                            writeInternal();
965                        } finally {
966                            mBackgroundWriteRunning.set(false);
967                        }
968                    }
969                }.start();
970            }
971        }
972
973        private void writeInternal() {
974            synchronized (mPackages) {
975                synchronized (mFileLock) {
976                    AtomicFile file = getFile();
977                    FileOutputStream f = null;
978                    try {
979                        f = file.startWrite();
980                        BufferedOutputStream out = new BufferedOutputStream(f);
981                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
982                        StringBuilder sb = new StringBuilder();
983                        for (PackageParser.Package pkg : mPackages.values()) {
984                            if (pkg.mLastPackageUsageTimeInMills == 0) {
985                                continue;
986                            }
987                            sb.setLength(0);
988                            sb.append(pkg.packageName);
989                            sb.append(' ');
990                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
991                            sb.append('\n');
992                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
993                        }
994                        out.flush();
995                        file.finishWrite(f);
996                    } catch (IOException e) {
997                        if (f != null) {
998                            file.failWrite(f);
999                        }
1000                        Log.e(TAG, "Failed to write package usage times", e);
1001                    }
1002                }
1003            }
1004            mLastWritten.set(SystemClock.elapsedRealtime());
1005        }
1006
1007        void readLP() {
1008            synchronized (mFileLock) {
1009                AtomicFile file = getFile();
1010                BufferedInputStream in = null;
1011                try {
1012                    in = new BufferedInputStream(file.openRead());
1013                    StringBuffer sb = new StringBuffer();
1014                    while (true) {
1015                        String packageName = readToken(in, sb, ' ');
1016                        if (packageName == null) {
1017                            break;
1018                        }
1019                        String timeInMillisString = readToken(in, sb, '\n');
1020                        if (timeInMillisString == null) {
1021                            throw new IOException("Failed to find last usage time for package "
1022                                                  + packageName);
1023                        }
1024                        PackageParser.Package pkg = mPackages.get(packageName);
1025                        if (pkg == null) {
1026                            continue;
1027                        }
1028                        long timeInMillis;
1029                        try {
1030                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1031                        } catch (NumberFormatException e) {
1032                            throw new IOException("Failed to parse " + timeInMillisString
1033                                                  + " as a long.", e);
1034                        }
1035                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1036                    }
1037                } catch (FileNotFoundException expected) {
1038                    mIsHistoricalPackageUsageAvailable = false;
1039                } catch (IOException e) {
1040                    Log.w(TAG, "Failed to read package usage times", e);
1041                } finally {
1042                    IoUtils.closeQuietly(in);
1043                }
1044            }
1045            mLastWritten.set(SystemClock.elapsedRealtime());
1046        }
1047
1048        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1049                throws IOException {
1050            sb.setLength(0);
1051            while (true) {
1052                int ch = in.read();
1053                if (ch == -1) {
1054                    if (sb.length() == 0) {
1055                        return null;
1056                    }
1057                    throw new IOException("Unexpected EOF");
1058                }
1059                if (ch == endOfToken) {
1060                    return sb.toString();
1061                }
1062                sb.append((char)ch);
1063            }
1064        }
1065
1066        private AtomicFile getFile() {
1067            File dataDir = Environment.getDataDirectory();
1068            File systemDir = new File(dataDir, "system");
1069            File fname = new File(systemDir, "package-usage.list");
1070            return new AtomicFile(fname);
1071        }
1072    }
1073
1074    class PackageHandler extends Handler {
1075        private boolean mBound = false;
1076        final ArrayList<HandlerParams> mPendingInstalls =
1077            new ArrayList<HandlerParams>();
1078
1079        private boolean connectToService() {
1080            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1081                    " DefaultContainerService");
1082            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1083            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1084            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1085                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1086                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1087                mBound = true;
1088                return true;
1089            }
1090            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1091            return false;
1092        }
1093
1094        private void disconnectService() {
1095            mContainerService = null;
1096            mBound = false;
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098            mContext.unbindService(mDefContainerConn);
1099            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1100        }
1101
1102        PackageHandler(Looper looper) {
1103            super(looper);
1104        }
1105
1106        public void handleMessage(Message msg) {
1107            try {
1108                doHandleMessage(msg);
1109            } finally {
1110                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1111            }
1112        }
1113
1114        void doHandleMessage(Message msg) {
1115            switch (msg.what) {
1116                case INIT_COPY: {
1117                    HandlerParams params = (HandlerParams) msg.obj;
1118                    int idx = mPendingInstalls.size();
1119                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1120                    // If a bind was already initiated we dont really
1121                    // need to do anything. The pending install
1122                    // will be processed later on.
1123                    if (!mBound) {
1124                        // If this is the only one pending we might
1125                        // have to bind to the service again.
1126                        if (!connectToService()) {
1127                            Slog.e(TAG, "Failed to bind to media container service");
1128                            params.serviceError();
1129                            return;
1130                        } else {
1131                            // Once we bind to the service, the first
1132                            // pending request will be processed.
1133                            mPendingInstalls.add(idx, params);
1134                        }
1135                    } else {
1136                        mPendingInstalls.add(idx, params);
1137                        // Already bound to the service. Just make
1138                        // sure we trigger off processing the first request.
1139                        if (idx == 0) {
1140                            mHandler.sendEmptyMessage(MCS_BOUND);
1141                        }
1142                    }
1143                    break;
1144                }
1145                case MCS_BOUND: {
1146                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1147                    if (msg.obj != null) {
1148                        mContainerService = (IMediaContainerService) msg.obj;
1149                    }
1150                    if (mContainerService == null) {
1151                        if (!mBound) {
1152                            // Something seriously wrong since we are not bound and we are not
1153                            // waiting for connection. Bail out.
1154                            Slog.e(TAG, "Cannot bind to media container service");
1155                            for (HandlerParams params : mPendingInstalls) {
1156                                // Indicate service bind error
1157                                params.serviceError();
1158                            }
1159                            mPendingInstalls.clear();
1160                        } else {
1161                            Slog.w(TAG, "Waiting to connect to media container service");
1162                        }
1163                    } else if (mPendingInstalls.size() > 0) {
1164                        HandlerParams params = mPendingInstalls.get(0);
1165                        if (params != null) {
1166                            if (params.startCopy()) {
1167                                // We are done...  look for more work or to
1168                                // go idle.
1169                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1170                                        "Checking for more work or unbind...");
1171                                // Delete pending install
1172                                if (mPendingInstalls.size() > 0) {
1173                                    mPendingInstalls.remove(0);
1174                                }
1175                                if (mPendingInstalls.size() == 0) {
1176                                    if (mBound) {
1177                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1178                                                "Posting delayed MCS_UNBIND");
1179                                        removeMessages(MCS_UNBIND);
1180                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1181                                        // Unbind after a little delay, to avoid
1182                                        // continual thrashing.
1183                                        sendMessageDelayed(ubmsg, 10000);
1184                                    }
1185                                } else {
1186                                    // There are more pending requests in queue.
1187                                    // Just post MCS_BOUND message to trigger processing
1188                                    // of next pending install.
1189                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1190                                            "Posting MCS_BOUND for next work");
1191                                    mHandler.sendEmptyMessage(MCS_BOUND);
1192                                }
1193                            }
1194                        }
1195                    } else {
1196                        // Should never happen ideally.
1197                        Slog.w(TAG, "Empty queue");
1198                    }
1199                    break;
1200                }
1201                case MCS_RECONNECT: {
1202                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1203                    if (mPendingInstalls.size() > 0) {
1204                        if (mBound) {
1205                            disconnectService();
1206                        }
1207                        if (!connectToService()) {
1208                            Slog.e(TAG, "Failed to bind to media container service");
1209                            for (HandlerParams params : mPendingInstalls) {
1210                                // Indicate service bind error
1211                                params.serviceError();
1212                            }
1213                            mPendingInstalls.clear();
1214                        }
1215                    }
1216                    break;
1217                }
1218                case MCS_UNBIND: {
1219                    // If there is no actual work left, then time to unbind.
1220                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1221
1222                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1223                        if (mBound) {
1224                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1225
1226                            disconnectService();
1227                        }
1228                    } else if (mPendingInstalls.size() > 0) {
1229                        // There are more pending requests in queue.
1230                        // Just post MCS_BOUND message to trigger processing
1231                        // of next pending install.
1232                        mHandler.sendEmptyMessage(MCS_BOUND);
1233                    }
1234
1235                    break;
1236                }
1237                case MCS_GIVE_UP: {
1238                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1239                    mPendingInstalls.remove(0);
1240                    break;
1241                }
1242                case SEND_PENDING_BROADCAST: {
1243                    String packages[];
1244                    ArrayList<String> components[];
1245                    int size = 0;
1246                    int uids[];
1247                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1248                    synchronized (mPackages) {
1249                        if (mPendingBroadcasts == null) {
1250                            return;
1251                        }
1252                        size = mPendingBroadcasts.size();
1253                        if (size <= 0) {
1254                            // Nothing to be done. Just return
1255                            return;
1256                        }
1257                        packages = new String[size];
1258                        components = new ArrayList[size];
1259                        uids = new int[size];
1260                        int i = 0;  // filling out the above arrays
1261
1262                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1263                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1264                            Iterator<Map.Entry<String, ArrayList<String>>> it
1265                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1266                                            .entrySet().iterator();
1267                            while (it.hasNext() && i < size) {
1268                                Map.Entry<String, ArrayList<String>> ent = it.next();
1269                                packages[i] = ent.getKey();
1270                                components[i] = ent.getValue();
1271                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1272                                uids[i] = (ps != null)
1273                                        ? UserHandle.getUid(packageUserId, ps.appId)
1274                                        : -1;
1275                                i++;
1276                            }
1277                        }
1278                        size = i;
1279                        mPendingBroadcasts.clear();
1280                    }
1281                    // Send broadcasts
1282                    for (int i = 0; i < size; i++) {
1283                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1284                    }
1285                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1286                    break;
1287                }
1288                case START_CLEANING_PACKAGE: {
1289                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1290                    final String packageName = (String)msg.obj;
1291                    final int userId = msg.arg1;
1292                    final boolean andCode = msg.arg2 != 0;
1293                    synchronized (mPackages) {
1294                        if (userId == UserHandle.USER_ALL) {
1295                            int[] users = sUserManager.getUserIds();
1296                            for (int user : users) {
1297                                mSettings.addPackageToCleanLPw(
1298                                        new PackageCleanItem(user, packageName, andCode));
1299                            }
1300                        } else {
1301                            mSettings.addPackageToCleanLPw(
1302                                    new PackageCleanItem(userId, packageName, andCode));
1303                        }
1304                    }
1305                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1306                    startCleaningPackages();
1307                } break;
1308                case POST_INSTALL: {
1309                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1310                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1311                    mRunningInstalls.delete(msg.arg1);
1312                    boolean deleteOld = false;
1313
1314                    if (data != null) {
1315                        InstallArgs args = data.args;
1316                        PackageInstalledInfo res = data.res;
1317
1318                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1319                            final String packageName = res.pkg.applicationInfo.packageName;
1320                            res.removedInfo.sendBroadcast(false, true, false);
1321                            Bundle extras = new Bundle(1);
1322                            extras.putInt(Intent.EXTRA_UID, res.uid);
1323
1324                            // Now that we successfully installed the package, grant runtime
1325                            // permissions if requested before broadcasting the install.
1326                            if ((args.installFlags
1327                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1328                                grantRequestedRuntimePermissions(res.pkg,
1329                                        args.user.getIdentifier());
1330                            }
1331
1332                            // Determine the set of users who are adding this
1333                            // package for the first time vs. those who are seeing
1334                            // an update.
1335                            int[] firstUsers;
1336                            int[] updateUsers = new int[0];
1337                            if (res.origUsers == null || res.origUsers.length == 0) {
1338                                firstUsers = res.newUsers;
1339                            } else {
1340                                firstUsers = new int[0];
1341                                for (int i=0; i<res.newUsers.length; i++) {
1342                                    int user = res.newUsers[i];
1343                                    boolean isNew = true;
1344                                    for (int j=0; j<res.origUsers.length; j++) {
1345                                        if (res.origUsers[j] == user) {
1346                                            isNew = false;
1347                                            break;
1348                                        }
1349                                    }
1350                                    if (isNew) {
1351                                        int[] newFirst = new int[firstUsers.length+1];
1352                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1353                                                firstUsers.length);
1354                                        newFirst[firstUsers.length] = user;
1355                                        firstUsers = newFirst;
1356                                    } else {
1357                                        int[] newUpdate = new int[updateUsers.length+1];
1358                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1359                                                updateUsers.length);
1360                                        newUpdate[updateUsers.length] = user;
1361                                        updateUsers = newUpdate;
1362                                    }
1363                                }
1364                            }
1365                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1366                                    packageName, extras, null, null, firstUsers);
1367                            final boolean update = res.removedInfo.removedPackage != null;
1368                            if (update) {
1369                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1370                            }
1371                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1372                                    packageName, extras, null, null, updateUsers);
1373                            if (update) {
1374                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1375                                        packageName, extras, null, null, updateUsers);
1376                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1377                                        null, null, packageName, null, updateUsers);
1378
1379                                // treat asec-hosted packages like removable media on upgrade
1380                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1381                                    if (DEBUG_INSTALL) {
1382                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1383                                                + " is ASEC-hosted -> AVAILABLE");
1384                                    }
1385                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1386                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1387                                    pkgList.add(packageName);
1388                                    sendResourcesChangedBroadcast(true, true,
1389                                            pkgList,uidArray, null);
1390                                }
1391                            }
1392                            if (res.removedInfo.args != null) {
1393                                // Remove the replaced package's older resources safely now
1394                                deleteOld = true;
1395                            }
1396
1397                            // If this app is a browser and it's newly-installed for some
1398                            // users, clear any default-browser state in those users
1399                            if (firstUsers.length > 0) {
1400                                // the app's nature doesn't depend on the user, so we can just
1401                                // check its browser nature in any user and generalize.
1402                                if (packageIsBrowser(packageName, firstUsers[0])) {
1403                                    synchronized (mPackages) {
1404                                        for (int userId : firstUsers) {
1405                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1406                                        }
1407                                    }
1408                                }
1409                            }
1410                            // Log current value of "unknown sources" setting
1411                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1412                                getUnknownSourcesSettings());
1413                        }
1414                        // Force a gc to clear up things
1415                        Runtime.getRuntime().gc();
1416                        // We delete after a gc for applications  on sdcard.
1417                        if (deleteOld) {
1418                            synchronized (mInstallLock) {
1419                                res.removedInfo.args.doPostDeleteLI(true);
1420                            }
1421                        }
1422                        if (args.observer != null) {
1423                            try {
1424                                Bundle extras = extrasForInstallResult(res);
1425                                args.observer.onPackageInstalled(res.name, res.returnCode,
1426                                        res.returnMsg, extras);
1427                            } catch (RemoteException e) {
1428                                Slog.i(TAG, "Observer no longer exists.");
1429                            }
1430                        }
1431                    } else {
1432                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1433                    }
1434                } break;
1435                case UPDATED_MEDIA_STATUS: {
1436                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1437                    boolean reportStatus = msg.arg1 == 1;
1438                    boolean doGc = msg.arg2 == 1;
1439                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1440                    if (doGc) {
1441                        // Force a gc to clear up stale containers.
1442                        Runtime.getRuntime().gc();
1443                    }
1444                    if (msg.obj != null) {
1445                        @SuppressWarnings("unchecked")
1446                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1447                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1448                        // Unload containers
1449                        unloadAllContainers(args);
1450                    }
1451                    if (reportStatus) {
1452                        try {
1453                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1454                            PackageHelper.getMountService().finishMediaUpdate();
1455                        } catch (RemoteException e) {
1456                            Log.e(TAG, "MountService not running?");
1457                        }
1458                    }
1459                } break;
1460                case WRITE_SETTINGS: {
1461                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1462                    synchronized (mPackages) {
1463                        removeMessages(WRITE_SETTINGS);
1464                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1465                        mSettings.writeLPr();
1466                        mDirtyUsers.clear();
1467                    }
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1469                } break;
1470                case WRITE_PACKAGE_RESTRICTIONS: {
1471                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1472                    synchronized (mPackages) {
1473                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1474                        for (int userId : mDirtyUsers) {
1475                            mSettings.writePackageRestrictionsLPr(userId);
1476                        }
1477                        mDirtyUsers.clear();
1478                    }
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1480                } break;
1481                case CHECK_PENDING_VERIFICATION: {
1482                    final int verificationId = msg.arg1;
1483                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1484
1485                    if ((state != null) && !state.timeoutExtended()) {
1486                        final InstallArgs args = state.getInstallArgs();
1487                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1488
1489                        Slog.i(TAG, "Verification timed out for " + originUri);
1490                        mPendingVerification.remove(verificationId);
1491
1492                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1493
1494                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1495                            Slog.i(TAG, "Continuing with installation of " + originUri);
1496                            state.setVerifierResponse(Binder.getCallingUid(),
1497                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1498                            broadcastPackageVerified(verificationId, originUri,
1499                                    PackageManager.VERIFICATION_ALLOW,
1500                                    state.getInstallArgs().getUser());
1501                            try {
1502                                ret = args.copyApk(mContainerService, true);
1503                            } catch (RemoteException e) {
1504                                Slog.e(TAG, "Could not contact the ContainerService");
1505                            }
1506                        } else {
1507                            broadcastPackageVerified(verificationId, originUri,
1508                                    PackageManager.VERIFICATION_REJECT,
1509                                    state.getInstallArgs().getUser());
1510                        }
1511
1512                        processPendingInstall(args, ret);
1513                        mHandler.sendEmptyMessage(MCS_UNBIND);
1514                    }
1515                    break;
1516                }
1517                case PACKAGE_VERIFIED: {
1518                    final int verificationId = msg.arg1;
1519
1520                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1521                    if (state == null) {
1522                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1523                        break;
1524                    }
1525
1526                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1527
1528                    state.setVerifierResponse(response.callerUid, response.code);
1529
1530                    if (state.isVerificationComplete()) {
1531                        mPendingVerification.remove(verificationId);
1532
1533                        final InstallArgs args = state.getInstallArgs();
1534                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1535
1536                        int ret;
1537                        if (state.isInstallAllowed()) {
1538                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1539                            broadcastPackageVerified(verificationId, originUri,
1540                                    response.code, state.getInstallArgs().getUser());
1541                            try {
1542                                ret = args.copyApk(mContainerService, true);
1543                            } catch (RemoteException e) {
1544                                Slog.e(TAG, "Could not contact the ContainerService");
1545                            }
1546                        } else {
1547                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1548                        }
1549
1550                        processPendingInstall(args, ret);
1551
1552                        mHandler.sendEmptyMessage(MCS_UNBIND);
1553                    }
1554
1555                    break;
1556                }
1557                case START_INTENT_FILTER_VERIFICATIONS: {
1558                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1559                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1560                            params.replacing, params.pkg);
1561                    break;
1562                }
1563                case INTENT_FILTER_VERIFIED: {
1564                    final int verificationId = msg.arg1;
1565
1566                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1567                            verificationId);
1568                    if (state == null) {
1569                        Slog.w(TAG, "Invalid IntentFilter verification token "
1570                                + verificationId + " received");
1571                        break;
1572                    }
1573
1574                    final int userId = state.getUserId();
1575
1576                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1577                            "Processing IntentFilter verification with token:"
1578                            + verificationId + " and userId:" + userId);
1579
1580                    final IntentFilterVerificationResponse response =
1581                            (IntentFilterVerificationResponse) msg.obj;
1582
1583                    state.setVerifierResponse(response.callerUid, response.code);
1584
1585                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1586                            "IntentFilter verification with token:" + verificationId
1587                            + " and userId:" + userId
1588                            + " is settings verifier response with response code:"
1589                            + response.code);
1590
1591                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1592                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1593                                + response.getFailedDomainsString());
1594                    }
1595
1596                    if (state.isVerificationComplete()) {
1597                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1598                    } else {
1599                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                                "IntentFilter verification with token:" + verificationId
1601                                + " was not said to be complete");
1602                    }
1603
1604                    break;
1605                }
1606            }
1607        }
1608    }
1609
1610    private StorageEventListener mStorageListener = new StorageEventListener() {
1611        @Override
1612        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1613            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1614                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1615                    final String volumeUuid = vol.getFsUuid();
1616
1617                    // Clean up any users or apps that were removed or recreated
1618                    // while this volume was missing
1619                    reconcileUsers(volumeUuid);
1620                    reconcileApps(volumeUuid);
1621
1622                    // Clean up any install sessions that expired or were
1623                    // cancelled while this volume was missing
1624                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1625
1626                    loadPrivatePackages(vol);
1627
1628                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1629                    unloadPrivatePackages(vol);
1630                }
1631            }
1632
1633            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1634                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1635                    updateExternalMediaStatus(true, false);
1636                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1637                    updateExternalMediaStatus(false, false);
1638                }
1639            }
1640        }
1641
1642        @Override
1643        public void onVolumeForgotten(String fsUuid) {
1644            // Remove any apps installed on the forgotten volume
1645            synchronized (mPackages) {
1646                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1647                for (PackageSetting ps : packages) {
1648                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1649                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1650                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1651                }
1652
1653                mSettings.writeLPr();
1654            }
1655        }
1656    };
1657
1658    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1659        if (userId >= UserHandle.USER_OWNER) {
1660            grantRequestedRuntimePermissionsForUser(pkg, userId);
1661        } else if (userId == UserHandle.USER_ALL) {
1662            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1663                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1664            }
1665        }
1666
1667        // We could have touched GID membership, so flush out packages.list
1668        synchronized (mPackages) {
1669            mSettings.writePackageListLPr();
1670        }
1671    }
1672
1673    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1674        SettingBase sb = (SettingBase) pkg.mExtras;
1675        if (sb == null) {
1676            return;
1677        }
1678
1679        PermissionsState permissionsState = sb.getPermissionsState();
1680
1681        for (String permission : pkg.requestedPermissions) {
1682            BasePermission bp = mSettings.mPermissions.get(permission);
1683            if (bp != null && bp.isRuntime()) {
1684                permissionsState.grantRuntimePermission(bp, userId);
1685            }
1686        }
1687    }
1688
1689    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1690        Bundle extras = null;
1691        switch (res.returnCode) {
1692            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1693                extras = new Bundle();
1694                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1695                        res.origPermission);
1696                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1697                        res.origPackage);
1698                break;
1699            }
1700            case PackageManager.INSTALL_SUCCEEDED: {
1701                extras = new Bundle();
1702                extras.putBoolean(Intent.EXTRA_REPLACING,
1703                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1704                break;
1705            }
1706        }
1707        return extras;
1708    }
1709
1710    void scheduleWriteSettingsLocked() {
1711        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1712            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1713        }
1714    }
1715
1716    void scheduleWritePackageRestrictionsLocked(int userId) {
1717        if (!sUserManager.exists(userId)) return;
1718        mDirtyUsers.add(userId);
1719        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1720            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1721        }
1722    }
1723
1724    public static PackageManagerService main(Context context, Installer installer,
1725            boolean factoryTest, boolean onlyCore) {
1726        PackageManagerService m = new PackageManagerService(context, installer,
1727                factoryTest, onlyCore);
1728        ServiceManager.addService("package", m);
1729        return m;
1730    }
1731
1732    static String[] splitString(String str, char sep) {
1733        int count = 1;
1734        int i = 0;
1735        while ((i=str.indexOf(sep, i)) >= 0) {
1736            count++;
1737            i++;
1738        }
1739
1740        String[] res = new String[count];
1741        i=0;
1742        count = 0;
1743        int lastI=0;
1744        while ((i=str.indexOf(sep, i)) >= 0) {
1745            res[count] = str.substring(lastI, i);
1746            count++;
1747            i++;
1748            lastI = i;
1749        }
1750        res[count] = str.substring(lastI, str.length());
1751        return res;
1752    }
1753
1754    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1755        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1756                Context.DISPLAY_SERVICE);
1757        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1758    }
1759
1760    public PackageManagerService(Context context, Installer installer,
1761            boolean factoryTest, boolean onlyCore) {
1762        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1763                SystemClock.uptimeMillis());
1764
1765        if (mSdkVersion <= 0) {
1766            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1767        }
1768
1769        mContext = context;
1770        mFactoryTest = factoryTest;
1771        mOnlyCore = onlyCore;
1772        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1773        mMetrics = new DisplayMetrics();
1774        mSettings = new Settings(mPackages);
1775        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1776                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1777        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1778                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1779        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1780                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1781        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1782                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1783        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1784                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1785        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1786                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1787
1788        // TODO: add a property to control this?
1789        long dexOptLRUThresholdInMinutes;
1790        if (mLazyDexOpt) {
1791            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1792        } else {
1793            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1794        }
1795        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1796
1797        String separateProcesses = SystemProperties.get("debug.separate_processes");
1798        if (separateProcesses != null && separateProcesses.length() > 0) {
1799            if ("*".equals(separateProcesses)) {
1800                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1801                mSeparateProcesses = null;
1802                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1803            } else {
1804                mDefParseFlags = 0;
1805                mSeparateProcesses = separateProcesses.split(",");
1806                Slog.w(TAG, "Running with debug.separate_processes: "
1807                        + separateProcesses);
1808            }
1809        } else {
1810            mDefParseFlags = 0;
1811            mSeparateProcesses = null;
1812        }
1813
1814        mInstaller = installer;
1815        mPackageDexOptimizer = new PackageDexOptimizer(this);
1816        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1817
1818        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1819                FgThread.get().getLooper());
1820
1821        getDefaultDisplayMetrics(context, mMetrics);
1822
1823        SystemConfig systemConfig = SystemConfig.getInstance();
1824        mGlobalGids = systemConfig.getGlobalGids();
1825        mSystemPermissions = systemConfig.getSystemPermissions();
1826        mAvailableFeatures = systemConfig.getAvailableFeatures();
1827
1828        synchronized (mInstallLock) {
1829        // writer
1830        synchronized (mPackages) {
1831            mHandlerThread = new ServiceThread(TAG,
1832                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1833            mHandlerThread.start();
1834            mHandler = new PackageHandler(mHandlerThread.getLooper());
1835            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1836
1837            File dataDir = Environment.getDataDirectory();
1838            mAppDataDir = new File(dataDir, "data");
1839            mAppInstallDir = new File(dataDir, "app");
1840            mAppLib32InstallDir = new File(dataDir, "app-lib");
1841            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1842            mUserAppDataDir = new File(dataDir, "user");
1843            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1844
1845            sUserManager = new UserManagerService(context, this,
1846                    mInstallLock, mPackages);
1847
1848            // Propagate permission configuration in to package manager.
1849            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1850                    = systemConfig.getPermissions();
1851            for (int i=0; i<permConfig.size(); i++) {
1852                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1853                BasePermission bp = mSettings.mPermissions.get(perm.name);
1854                if (bp == null) {
1855                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1856                    mSettings.mPermissions.put(perm.name, bp);
1857                }
1858                if (perm.gids != null) {
1859                    bp.setGids(perm.gids, perm.perUser);
1860                }
1861            }
1862
1863            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1864            for (int i=0; i<libConfig.size(); i++) {
1865                mSharedLibraries.put(libConfig.keyAt(i),
1866                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1867            }
1868
1869            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1870
1871            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1872                    mSdkVersion, mOnlyCore);
1873
1874            String customResolverActivity = Resources.getSystem().getString(
1875                    R.string.config_customResolverActivity);
1876            if (TextUtils.isEmpty(customResolverActivity)) {
1877                customResolverActivity = null;
1878            } else {
1879                mCustomResolverComponentName = ComponentName.unflattenFromString(
1880                        customResolverActivity);
1881            }
1882
1883            long startTime = SystemClock.uptimeMillis();
1884
1885            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1886                    startTime);
1887
1888            // Set flag to monitor and not change apk file paths when
1889            // scanning install directories.
1890            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1891
1892            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1893
1894            /**
1895             * Add everything in the in the boot class path to the
1896             * list of process files because dexopt will have been run
1897             * if necessary during zygote startup.
1898             */
1899            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1900            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1901
1902            if (bootClassPath != null) {
1903                String[] bootClassPathElements = splitString(bootClassPath, ':');
1904                for (String element : bootClassPathElements) {
1905                    alreadyDexOpted.add(element);
1906                }
1907            } else {
1908                Slog.w(TAG, "No BOOTCLASSPATH found!");
1909            }
1910
1911            if (systemServerClassPath != null) {
1912                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1913                for (String element : systemServerClassPathElements) {
1914                    alreadyDexOpted.add(element);
1915                }
1916            } else {
1917                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1918            }
1919
1920            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1921            final String[] dexCodeInstructionSets =
1922                    getDexCodeInstructionSets(
1923                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1924
1925            /**
1926             * Ensure all external libraries have had dexopt run on them.
1927             */
1928            if (mSharedLibraries.size() > 0) {
1929                // NOTE: For now, we're compiling these system "shared libraries"
1930                // (and framework jars) into all available architectures. It's possible
1931                // to compile them only when we come across an app that uses them (there's
1932                // already logic for that in scanPackageLI) but that adds some complexity.
1933                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1934                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1935                        final String lib = libEntry.path;
1936                        if (lib == null) {
1937                            continue;
1938                        }
1939
1940                        try {
1941                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1942                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1943                                alreadyDexOpted.add(lib);
1944                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1945                            }
1946                        } catch (FileNotFoundException e) {
1947                            Slog.w(TAG, "Library not found: " + lib);
1948                        } catch (IOException e) {
1949                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1950                                    + e.getMessage());
1951                        }
1952                    }
1953                }
1954            }
1955
1956            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1957
1958            // Gross hack for now: we know this file doesn't contain any
1959            // code, so don't dexopt it to avoid the resulting log spew.
1960            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1961
1962            // Gross hack for now: we know this file is only part of
1963            // the boot class path for art, so don't dexopt it to
1964            // avoid the resulting log spew.
1965            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1966
1967            /**
1968             * There are a number of commands implemented in Java, which
1969             * we currently need to do the dexopt on so that they can be
1970             * run from a non-root shell.
1971             */
1972            String[] frameworkFiles = frameworkDir.list();
1973            if (frameworkFiles != null) {
1974                // TODO: We could compile these only for the most preferred ABI. We should
1975                // first double check that the dex files for these commands are not referenced
1976                // by other system apps.
1977                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1978                    for (int i=0; i<frameworkFiles.length; i++) {
1979                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1980                        String path = libPath.getPath();
1981                        // Skip the file if we already did it.
1982                        if (alreadyDexOpted.contains(path)) {
1983                            continue;
1984                        }
1985                        // Skip the file if it is not a type we want to dexopt.
1986                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1987                            continue;
1988                        }
1989                        try {
1990                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1991                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1992                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1993                            }
1994                        } catch (FileNotFoundException e) {
1995                            Slog.w(TAG, "Jar not found: " + path);
1996                        } catch (IOException e) {
1997                            Slog.w(TAG, "Exception reading jar: " + path, e);
1998                        }
1999                    }
2000                }
2001            }
2002
2003            // Collect vendor overlay packages.
2004            // (Do this before scanning any apps.)
2005            // For security and version matching reason, only consider
2006            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2007            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2008            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2009                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2010
2011            // Find base frameworks (resource packages without code).
2012            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2013                    | PackageParser.PARSE_IS_SYSTEM_DIR
2014                    | PackageParser.PARSE_IS_PRIVILEGED,
2015                    scanFlags | SCAN_NO_DEX, 0);
2016
2017            // Collected privileged system packages.
2018            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2019            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2020                    | PackageParser.PARSE_IS_SYSTEM_DIR
2021                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2022
2023            // Collect ordinary system packages.
2024            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2025            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2026                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2027
2028            // Collect all vendor packages.
2029            File vendorAppDir = new File("/vendor/app");
2030            try {
2031                vendorAppDir = vendorAppDir.getCanonicalFile();
2032            } catch (IOException e) {
2033                // failed to look up canonical path, continue with original one
2034            }
2035            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2036                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2037
2038            // Collect all OEM packages.
2039            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2040            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2041                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2042
2043            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2044            mInstaller.moveFiles();
2045
2046            // Prune any system packages that no longer exist.
2047            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2048            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2049            if (!mOnlyCore) {
2050                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2051                while (psit.hasNext()) {
2052                    PackageSetting ps = psit.next();
2053
2054                    /*
2055                     * If this is not a system app, it can't be a
2056                     * disable system app.
2057                     */
2058                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2059                        continue;
2060                    }
2061
2062                    /*
2063                     * If the package is scanned, it's not erased.
2064                     */
2065                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2066                    if (scannedPkg != null) {
2067                        /*
2068                         * If the system app is both scanned and in the
2069                         * disabled packages list, then it must have been
2070                         * added via OTA. Remove it from the currently
2071                         * scanned package so the previously user-installed
2072                         * application can be scanned.
2073                         */
2074                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2075                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2076                                    + ps.name + "; removing system app.  Last known codePath="
2077                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2078                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2079                                    + scannedPkg.mVersionCode);
2080                            removePackageLI(ps, true);
2081                            expectingBetter.put(ps.name, ps.codePath);
2082                        }
2083
2084                        continue;
2085                    }
2086
2087                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2088                        psit.remove();
2089                        logCriticalInfo(Log.WARN, "System package " + ps.name
2090                                + " no longer exists; wiping its data");
2091                        removeDataDirsLI(null, ps.name);
2092                    } else {
2093                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2094                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2095                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2096                        }
2097                    }
2098                }
2099            }
2100
2101            //look for any incomplete package installations
2102            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2103            //clean up list
2104            for(int i = 0; i < deletePkgsList.size(); i++) {
2105                //clean up here
2106                cleanupInstallFailedPackage(deletePkgsList.get(i));
2107            }
2108            //delete tmp files
2109            deleteTempPackageFiles();
2110
2111            // Remove any shared userIDs that have no associated packages
2112            mSettings.pruneSharedUsersLPw();
2113
2114            if (!mOnlyCore) {
2115                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2116                        SystemClock.uptimeMillis());
2117                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2118
2119                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2120                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2121
2122                /**
2123                 * Remove disable package settings for any updated system
2124                 * apps that were removed via an OTA. If they're not a
2125                 * previously-updated app, remove them completely.
2126                 * Otherwise, just revoke their system-level permissions.
2127                 */
2128                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2129                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2130                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2131
2132                    String msg;
2133                    if (deletedPkg == null) {
2134                        msg = "Updated system package " + deletedAppName
2135                                + " no longer exists; wiping its data";
2136                        removeDataDirsLI(null, deletedAppName);
2137                    } else {
2138                        msg = "Updated system app + " + deletedAppName
2139                                + " no longer present; removing system privileges for "
2140                                + deletedAppName;
2141
2142                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2143
2144                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2145                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2146                    }
2147                    logCriticalInfo(Log.WARN, msg);
2148                }
2149
2150                /**
2151                 * Make sure all system apps that we expected to appear on
2152                 * the userdata partition actually showed up. If they never
2153                 * appeared, crawl back and revive the system version.
2154                 */
2155                for (int i = 0; i < expectingBetter.size(); i++) {
2156                    final String packageName = expectingBetter.keyAt(i);
2157                    if (!mPackages.containsKey(packageName)) {
2158                        final File scanFile = expectingBetter.valueAt(i);
2159
2160                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2161                                + " but never showed up; reverting to system");
2162
2163                        final int reparseFlags;
2164                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2165                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2166                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2167                                    | PackageParser.PARSE_IS_PRIVILEGED;
2168                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2169                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2170                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2171                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2172                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2173                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2174                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2175                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2176                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2177                        } else {
2178                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2179                            continue;
2180                        }
2181
2182                        mSettings.enableSystemPackageLPw(packageName);
2183
2184                        try {
2185                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2186                        } catch (PackageManagerException e) {
2187                            Slog.e(TAG, "Failed to parse original system package: "
2188                                    + e.getMessage());
2189                        }
2190                    }
2191                }
2192            }
2193
2194            // Now that we know all of the shared libraries, update all clients to have
2195            // the correct library paths.
2196            updateAllSharedLibrariesLPw();
2197
2198            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2199                // NOTE: We ignore potential failures here during a system scan (like
2200                // the rest of the commands above) because there's precious little we
2201                // can do about it. A settings error is reported, though.
2202                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2203                        false /* force dexopt */, false /* defer dexopt */);
2204            }
2205
2206            // Now that we know all the packages we are keeping,
2207            // read and update their last usage times.
2208            mPackageUsage.readLP();
2209
2210            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2211                    SystemClock.uptimeMillis());
2212            Slog.i(TAG, "Time to scan packages: "
2213                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2214                    + " seconds");
2215
2216            // If the platform SDK has changed since the last time we booted,
2217            // we need to re-grant app permission to catch any new ones that
2218            // appear.  This is really a hack, and means that apps can in some
2219            // cases get permissions that the user didn't initially explicitly
2220            // allow...  it would be nice to have some better way to handle
2221            // this situation.
2222            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2223                    != mSdkVersion;
2224            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2225                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2226                    + "; regranting permissions for internal storage");
2227            mSettings.mInternalSdkPlatform = mSdkVersion;
2228
2229            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2230                    | (regrantPermissions
2231                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2232                            : 0));
2233
2234            // If this is the first boot, and it is a normal boot, then
2235            // we need to initialize the default preferred apps.
2236            if (!mRestoredSettings && !onlyCore) {
2237                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2238                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2239            }
2240
2241            // If this is first boot after an OTA, and a normal boot, then
2242            // we need to clear code cache directories.
2243            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2244            if (mIsUpgrade && !onlyCore) {
2245                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2246                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2247                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2248                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2249                }
2250                mSettings.mFingerprint = Build.FINGERPRINT;
2251            }
2252
2253            primeDomainVerificationsLPw();
2254            checkDefaultBrowser();
2255
2256            // All the changes are done during package scanning.
2257            mSettings.updateInternalDatabaseVersion();
2258
2259            // can downgrade to reader
2260            mSettings.writeLPr();
2261
2262            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2263                    SystemClock.uptimeMillis());
2264
2265            mRequiredVerifierPackage = getRequiredVerifierLPr();
2266            mRequiredInstallerPackage = getRequiredInstallerLPr();
2267
2268            mInstallerService = new PackageInstallerService(context, this);
2269
2270            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2271            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2272                    mIntentFilterVerifierComponent);
2273
2274        } // synchronized (mPackages)
2275        } // synchronized (mInstallLock)
2276
2277        // Now after opening every single application zip, make sure they
2278        // are all flushed.  Not really needed, but keeps things nice and
2279        // tidy.
2280        Runtime.getRuntime().gc();
2281
2282        // Expose private service for system components to use.
2283        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2284    }
2285
2286    @Override
2287    public boolean isFirstBoot() {
2288        return !mRestoredSettings;
2289    }
2290
2291    @Override
2292    public boolean isOnlyCoreApps() {
2293        return mOnlyCore;
2294    }
2295
2296    @Override
2297    public boolean isUpgrade() {
2298        return mIsUpgrade;
2299    }
2300
2301    private String getRequiredVerifierLPr() {
2302        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2303        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2304                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2305
2306        String requiredVerifier = null;
2307
2308        final int N = receivers.size();
2309        for (int i = 0; i < N; i++) {
2310            final ResolveInfo info = receivers.get(i);
2311
2312            if (info.activityInfo == null) {
2313                continue;
2314            }
2315
2316            final String packageName = info.activityInfo.packageName;
2317
2318            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2319                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2320                continue;
2321            }
2322
2323            if (requiredVerifier != null) {
2324                throw new RuntimeException("There can be only one required verifier");
2325            }
2326
2327            requiredVerifier = packageName;
2328        }
2329
2330        return requiredVerifier;
2331    }
2332
2333    private String getRequiredInstallerLPr() {
2334        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2335        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2336        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2337
2338        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2339                PACKAGE_MIME_TYPE, 0, 0);
2340
2341        String requiredInstaller = null;
2342
2343        final int N = installers.size();
2344        for (int i = 0; i < N; i++) {
2345            final ResolveInfo info = installers.get(i);
2346            final String packageName = info.activityInfo.packageName;
2347
2348            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2349                continue;
2350            }
2351
2352            if (requiredInstaller != null) {
2353                throw new RuntimeException("There must be one required installer");
2354            }
2355
2356            requiredInstaller = packageName;
2357        }
2358
2359        if (requiredInstaller == null) {
2360            throw new RuntimeException("There must be one required installer");
2361        }
2362
2363        return requiredInstaller;
2364    }
2365
2366    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2367        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2368        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2369                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2370
2371        ComponentName verifierComponentName = null;
2372
2373        int priority = -1000;
2374        final int N = receivers.size();
2375        for (int i = 0; i < N; i++) {
2376            final ResolveInfo info = receivers.get(i);
2377
2378            if (info.activityInfo == null) {
2379                continue;
2380            }
2381
2382            final String packageName = info.activityInfo.packageName;
2383
2384            final PackageSetting ps = mSettings.mPackages.get(packageName);
2385            if (ps == null) {
2386                continue;
2387            }
2388
2389            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2390                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2391                continue;
2392            }
2393
2394            // Select the IntentFilterVerifier with the highest priority
2395            if (priority < info.priority) {
2396                priority = info.priority;
2397                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2398                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2399                        + verifierComponentName + " with priority: " + info.priority);
2400            }
2401        }
2402
2403        return verifierComponentName;
2404    }
2405
2406    private void primeDomainVerificationsLPw() {
2407        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2408        boolean updated = false;
2409        ArraySet<String> allHostsSet = new ArraySet<>();
2410        for (PackageParser.Package pkg : mPackages.values()) {
2411            final String packageName = pkg.packageName;
2412            if (!hasDomainURLs(pkg)) {
2413                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2414                            "package with no domain URLs: " + packageName);
2415                continue;
2416            }
2417            if (!pkg.isSystemApp()) {
2418                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2419                        "No priming domain verifications for a non system package : " +
2420                                packageName);
2421                continue;
2422            }
2423            for (PackageParser.Activity a : pkg.activities) {
2424                for (ActivityIntentInfo filter : a.intents) {
2425                    if (hasValidDomains(filter)) {
2426                        allHostsSet.addAll(filter.getHostsList());
2427                    }
2428                }
2429            }
2430            if (allHostsSet.size() == 0) {
2431                allHostsSet.add("*");
2432            }
2433            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2434            IntentFilterVerificationInfo ivi =
2435                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2436            if (ivi != null) {
2437                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2438                        "Priming domain verifications for package: " + packageName +
2439                        " with hosts:" + ivi.getDomainsString());
2440                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2441                updated = true;
2442            }
2443            else {
2444                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2445                        "No priming domain verifications for package: " + packageName);
2446            }
2447            allHostsSet.clear();
2448        }
2449        if (updated) {
2450            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2451                    "Will need to write primed domain verifications");
2452        }
2453        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2454    }
2455
2456    private void applyFactoryDefaultBrowserLPw(int userId) {
2457        // The default browser app's package name is stored in a string resource,
2458        // with a product-specific overlay used for vendor customization.
2459        String browserPkg = mContext.getResources().getString(
2460                com.android.internal.R.string.default_browser);
2461        if (browserPkg != null) {
2462            // non-empty string => required to be a known package
2463            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2464            if (ps == null) {
2465                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2466                browserPkg = null;
2467            } else {
2468                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2469            }
2470        }
2471
2472        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2473        // default.  If there's more than one, just leave everything alone.
2474        if (browserPkg == null) {
2475            calculateDefaultBrowserLPw(userId);
2476        }
2477    }
2478
2479    private void calculateDefaultBrowserLPw(int userId) {
2480        List<String> allBrowsers = resolveAllBrowserApps(userId);
2481        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2482        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2483    }
2484
2485    private List<String> resolveAllBrowserApps(int userId) {
2486        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2487        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2488                PackageManager.MATCH_ALL, userId);
2489
2490        final int count = list.size();
2491        List<String> result = new ArrayList<String>(count);
2492        for (int i=0; i<count; i++) {
2493            ResolveInfo info = list.get(i);
2494            if (info.activityInfo == null
2495                    || !info.handleAllWebDataURI
2496                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2497                    || result.contains(info.activityInfo.packageName)) {
2498                continue;
2499            }
2500            result.add(info.activityInfo.packageName);
2501        }
2502
2503        return result;
2504    }
2505
2506    private boolean packageIsBrowser(String packageName, int userId) {
2507        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2508                PackageManager.MATCH_ALL, userId);
2509        final int N = list.size();
2510        for (int i = 0; i < N; i++) {
2511            ResolveInfo info = list.get(i);
2512            if (packageName.equals(info.activityInfo.packageName)) {
2513                return true;
2514            }
2515        }
2516        return false;
2517    }
2518
2519    private void checkDefaultBrowser() {
2520        final int myUserId = UserHandle.myUserId();
2521        final String packageName = getDefaultBrowserPackageName(myUserId);
2522        if (packageName != null) {
2523            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2524            if (info == null) {
2525                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2526                synchronized (mPackages) {
2527                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2528                }
2529            }
2530        }
2531    }
2532
2533    @Override
2534    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2535            throws RemoteException {
2536        try {
2537            return super.onTransact(code, data, reply, flags);
2538        } catch (RuntimeException e) {
2539            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2540                Slog.wtf(TAG, "Package Manager Crash", e);
2541            }
2542            throw e;
2543        }
2544    }
2545
2546    void cleanupInstallFailedPackage(PackageSetting ps) {
2547        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2548
2549        removeDataDirsLI(ps.volumeUuid, ps.name);
2550        if (ps.codePath != null) {
2551            if (ps.codePath.isDirectory()) {
2552                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2553            } else {
2554                ps.codePath.delete();
2555            }
2556        }
2557        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2558            if (ps.resourcePath.isDirectory()) {
2559                FileUtils.deleteContents(ps.resourcePath);
2560            }
2561            ps.resourcePath.delete();
2562        }
2563        mSettings.removePackageLPw(ps.name);
2564    }
2565
2566    static int[] appendInts(int[] cur, int[] add) {
2567        if (add == null) return cur;
2568        if (cur == null) return add;
2569        final int N = add.length;
2570        for (int i=0; i<N; i++) {
2571            cur = appendInt(cur, add[i]);
2572        }
2573        return cur;
2574    }
2575
2576    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2577        if (!sUserManager.exists(userId)) return null;
2578        final PackageSetting ps = (PackageSetting) p.mExtras;
2579        if (ps == null) {
2580            return null;
2581        }
2582
2583        final PermissionsState permissionsState = ps.getPermissionsState();
2584
2585        final int[] gids = permissionsState.computeGids(userId);
2586        final Set<String> permissions = permissionsState.getPermissions(userId);
2587        final PackageUserState state = ps.readUserState(userId);
2588
2589        return PackageParser.generatePackageInfo(p, gids, flags,
2590                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2591    }
2592
2593    @Override
2594    public boolean isPackageFrozen(String packageName) {
2595        synchronized (mPackages) {
2596            final PackageSetting ps = mSettings.mPackages.get(packageName);
2597            if (ps != null) {
2598                return ps.frozen;
2599            }
2600        }
2601        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2602        return true;
2603    }
2604
2605    @Override
2606    public boolean isPackageAvailable(String packageName, int userId) {
2607        if (!sUserManager.exists(userId)) return false;
2608        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2609        synchronized (mPackages) {
2610            PackageParser.Package p = mPackages.get(packageName);
2611            if (p != null) {
2612                final PackageSetting ps = (PackageSetting) p.mExtras;
2613                if (ps != null) {
2614                    final PackageUserState state = ps.readUserState(userId);
2615                    if (state != null) {
2616                        return PackageParser.isAvailable(state);
2617                    }
2618                }
2619            }
2620        }
2621        return false;
2622    }
2623
2624    @Override
2625    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2626        if (!sUserManager.exists(userId)) return null;
2627        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2628        // reader
2629        synchronized (mPackages) {
2630            PackageParser.Package p = mPackages.get(packageName);
2631            if (DEBUG_PACKAGE_INFO)
2632                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2633            if (p != null) {
2634                return generatePackageInfo(p, flags, userId);
2635            }
2636            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2637                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2638            }
2639        }
2640        return null;
2641    }
2642
2643    @Override
2644    public String[] currentToCanonicalPackageNames(String[] names) {
2645        String[] out = new String[names.length];
2646        // reader
2647        synchronized (mPackages) {
2648            for (int i=names.length-1; i>=0; i--) {
2649                PackageSetting ps = mSettings.mPackages.get(names[i]);
2650                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2651            }
2652        }
2653        return out;
2654    }
2655
2656    @Override
2657    public String[] canonicalToCurrentPackageNames(String[] names) {
2658        String[] out = new String[names.length];
2659        // reader
2660        synchronized (mPackages) {
2661            for (int i=names.length-1; i>=0; i--) {
2662                String cur = mSettings.mRenamedPackages.get(names[i]);
2663                out[i] = cur != null ? cur : names[i];
2664            }
2665        }
2666        return out;
2667    }
2668
2669    @Override
2670    public int getPackageUid(String packageName, int userId) {
2671        if (!sUserManager.exists(userId)) return -1;
2672        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2673
2674        // reader
2675        synchronized (mPackages) {
2676            PackageParser.Package p = mPackages.get(packageName);
2677            if(p != null) {
2678                return UserHandle.getUid(userId, p.applicationInfo.uid);
2679            }
2680            PackageSetting ps = mSettings.mPackages.get(packageName);
2681            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2682                return -1;
2683            }
2684            p = ps.pkg;
2685            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2686        }
2687    }
2688
2689    @Override
2690    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2691        if (!sUserManager.exists(userId)) {
2692            return null;
2693        }
2694
2695        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2696                "getPackageGids");
2697
2698        // reader
2699        synchronized (mPackages) {
2700            PackageParser.Package p = mPackages.get(packageName);
2701            if (DEBUG_PACKAGE_INFO) {
2702                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2703            }
2704            if (p != null) {
2705                PackageSetting ps = (PackageSetting) p.mExtras;
2706                return ps.getPermissionsState().computeGids(userId);
2707            }
2708        }
2709
2710        return null;
2711    }
2712
2713    @Override
2714    public int getMountExternalMode(int uid) {
2715        if (Process.isIsolated(uid)) {
2716            return Zygote.MOUNT_EXTERNAL_NONE;
2717        } else {
2718            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2719                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2720            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2721                return Zygote.MOUNT_EXTERNAL_WRITE;
2722            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2723                return Zygote.MOUNT_EXTERNAL_READ;
2724            } else {
2725                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2726            }
2727        }
2728    }
2729
2730    static PermissionInfo generatePermissionInfo(
2731            BasePermission bp, int flags) {
2732        if (bp.perm != null) {
2733            return PackageParser.generatePermissionInfo(bp.perm, flags);
2734        }
2735        PermissionInfo pi = new PermissionInfo();
2736        pi.name = bp.name;
2737        pi.packageName = bp.sourcePackage;
2738        pi.nonLocalizedLabel = bp.name;
2739        pi.protectionLevel = bp.protectionLevel;
2740        return pi;
2741    }
2742
2743    @Override
2744    public PermissionInfo getPermissionInfo(String name, int flags) {
2745        // reader
2746        synchronized (mPackages) {
2747            final BasePermission p = mSettings.mPermissions.get(name);
2748            if (p != null) {
2749                return generatePermissionInfo(p, flags);
2750            }
2751            return null;
2752        }
2753    }
2754
2755    @Override
2756    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2757        // reader
2758        synchronized (mPackages) {
2759            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2760            for (BasePermission p : mSettings.mPermissions.values()) {
2761                if (group == null) {
2762                    if (p.perm == null || p.perm.info.group == null) {
2763                        out.add(generatePermissionInfo(p, flags));
2764                    }
2765                } else {
2766                    if (p.perm != null && group.equals(p.perm.info.group)) {
2767                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2768                    }
2769                }
2770            }
2771
2772            if (out.size() > 0) {
2773                return out;
2774            }
2775            return mPermissionGroups.containsKey(group) ? out : null;
2776        }
2777    }
2778
2779    @Override
2780    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2781        // reader
2782        synchronized (mPackages) {
2783            return PackageParser.generatePermissionGroupInfo(
2784                    mPermissionGroups.get(name), flags);
2785        }
2786    }
2787
2788    @Override
2789    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2790        // reader
2791        synchronized (mPackages) {
2792            final int N = mPermissionGroups.size();
2793            ArrayList<PermissionGroupInfo> out
2794                    = new ArrayList<PermissionGroupInfo>(N);
2795            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2796                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2797            }
2798            return out;
2799        }
2800    }
2801
2802    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2803            int userId) {
2804        if (!sUserManager.exists(userId)) return null;
2805        PackageSetting ps = mSettings.mPackages.get(packageName);
2806        if (ps != null) {
2807            if (ps.pkg == null) {
2808                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2809                        flags, userId);
2810                if (pInfo != null) {
2811                    return pInfo.applicationInfo;
2812                }
2813                return null;
2814            }
2815            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2816                    ps.readUserState(userId), userId);
2817        }
2818        return null;
2819    }
2820
2821    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2822            int userId) {
2823        if (!sUserManager.exists(userId)) return null;
2824        PackageSetting ps = mSettings.mPackages.get(packageName);
2825        if (ps != null) {
2826            PackageParser.Package pkg = ps.pkg;
2827            if (pkg == null) {
2828                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2829                    return null;
2830                }
2831                // Only data remains, so we aren't worried about code paths
2832                pkg = new PackageParser.Package(packageName);
2833                pkg.applicationInfo.packageName = packageName;
2834                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2835                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2836                pkg.applicationInfo.dataDir = Environment
2837                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2838                        .getAbsolutePath();
2839                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2840                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2841            }
2842            return generatePackageInfo(pkg, flags, userId);
2843        }
2844        return null;
2845    }
2846
2847    @Override
2848    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2849        if (!sUserManager.exists(userId)) return null;
2850        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2851        // writer
2852        synchronized (mPackages) {
2853            PackageParser.Package p = mPackages.get(packageName);
2854            if (DEBUG_PACKAGE_INFO) Log.v(
2855                    TAG, "getApplicationInfo " + packageName
2856                    + ": " + p);
2857            if (p != null) {
2858                PackageSetting ps = mSettings.mPackages.get(packageName);
2859                if (ps == null) return null;
2860                // Note: isEnabledLP() does not apply here - always return info
2861                return PackageParser.generateApplicationInfo(
2862                        p, flags, ps.readUserState(userId), userId);
2863            }
2864            if ("android".equals(packageName)||"system".equals(packageName)) {
2865                return mAndroidApplication;
2866            }
2867            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2868                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2869            }
2870        }
2871        return null;
2872    }
2873
2874    @Override
2875    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2876            final IPackageDataObserver observer) {
2877        mContext.enforceCallingOrSelfPermission(
2878                android.Manifest.permission.CLEAR_APP_CACHE, null);
2879        // Queue up an async operation since clearing cache may take a little while.
2880        mHandler.post(new Runnable() {
2881            public void run() {
2882                mHandler.removeCallbacks(this);
2883                int retCode = -1;
2884                synchronized (mInstallLock) {
2885                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2886                    if (retCode < 0) {
2887                        Slog.w(TAG, "Couldn't clear application caches");
2888                    }
2889                }
2890                if (observer != null) {
2891                    try {
2892                        observer.onRemoveCompleted(null, (retCode >= 0));
2893                    } catch (RemoteException e) {
2894                        Slog.w(TAG, "RemoveException when invoking call back");
2895                    }
2896                }
2897            }
2898        });
2899    }
2900
2901    @Override
2902    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2903            final IntentSender pi) {
2904        mContext.enforceCallingOrSelfPermission(
2905                android.Manifest.permission.CLEAR_APP_CACHE, null);
2906        // Queue up an async operation since clearing cache may take a little while.
2907        mHandler.post(new Runnable() {
2908            public void run() {
2909                mHandler.removeCallbacks(this);
2910                int retCode = -1;
2911                synchronized (mInstallLock) {
2912                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2913                    if (retCode < 0) {
2914                        Slog.w(TAG, "Couldn't clear application caches");
2915                    }
2916                }
2917                if(pi != null) {
2918                    try {
2919                        // Callback via pending intent
2920                        int code = (retCode >= 0) ? 1 : 0;
2921                        pi.sendIntent(null, code, null,
2922                                null, null);
2923                    } catch (SendIntentException e1) {
2924                        Slog.i(TAG, "Failed to send pending intent");
2925                    }
2926                }
2927            }
2928        });
2929    }
2930
2931    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2932        synchronized (mInstallLock) {
2933            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2934                throw new IOException("Failed to free enough space");
2935            }
2936        }
2937    }
2938
2939    @Override
2940    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2941        if (!sUserManager.exists(userId)) return null;
2942        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2943        synchronized (mPackages) {
2944            PackageParser.Activity a = mActivities.mActivities.get(component);
2945
2946            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2947            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2948                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2949                if (ps == null) return null;
2950                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2951                        userId);
2952            }
2953            if (mResolveComponentName.equals(component)) {
2954                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2955                        new PackageUserState(), userId);
2956            }
2957        }
2958        return null;
2959    }
2960
2961    @Override
2962    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2963            String resolvedType) {
2964        synchronized (mPackages) {
2965            PackageParser.Activity a = mActivities.mActivities.get(component);
2966            if (a == null) {
2967                return false;
2968            }
2969            for (int i=0; i<a.intents.size(); i++) {
2970                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2971                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2972                    return true;
2973                }
2974            }
2975            return false;
2976        }
2977    }
2978
2979    @Override
2980    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2981        if (!sUserManager.exists(userId)) return null;
2982        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2983        synchronized (mPackages) {
2984            PackageParser.Activity a = mReceivers.mActivities.get(component);
2985            if (DEBUG_PACKAGE_INFO) Log.v(
2986                TAG, "getReceiverInfo " + component + ": " + a);
2987            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2988                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2989                if (ps == null) return null;
2990                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2991                        userId);
2992            }
2993        }
2994        return null;
2995    }
2996
2997    @Override
2998    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2999        if (!sUserManager.exists(userId)) return null;
3000        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3001        synchronized (mPackages) {
3002            PackageParser.Service s = mServices.mServices.get(component);
3003            if (DEBUG_PACKAGE_INFO) Log.v(
3004                TAG, "getServiceInfo " + component + ": " + s);
3005            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3006                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3007                if (ps == null) return null;
3008                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3009                        userId);
3010            }
3011        }
3012        return null;
3013    }
3014
3015    @Override
3016    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3017        if (!sUserManager.exists(userId)) return null;
3018        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3019        synchronized (mPackages) {
3020            PackageParser.Provider p = mProviders.mProviders.get(component);
3021            if (DEBUG_PACKAGE_INFO) Log.v(
3022                TAG, "getProviderInfo " + component + ": " + p);
3023            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3024                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3025                if (ps == null) return null;
3026                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3027                        userId);
3028            }
3029        }
3030        return null;
3031    }
3032
3033    @Override
3034    public String[] getSystemSharedLibraryNames() {
3035        Set<String> libSet;
3036        synchronized (mPackages) {
3037            libSet = mSharedLibraries.keySet();
3038            int size = libSet.size();
3039            if (size > 0) {
3040                String[] libs = new String[size];
3041                libSet.toArray(libs);
3042                return libs;
3043            }
3044        }
3045        return null;
3046    }
3047
3048    /**
3049     * @hide
3050     */
3051    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3052        synchronized (mPackages) {
3053            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3054            if (lib != null && lib.apk != null) {
3055                return mPackages.get(lib.apk);
3056            }
3057        }
3058        return null;
3059    }
3060
3061    @Override
3062    public FeatureInfo[] getSystemAvailableFeatures() {
3063        Collection<FeatureInfo> featSet;
3064        synchronized (mPackages) {
3065            featSet = mAvailableFeatures.values();
3066            int size = featSet.size();
3067            if (size > 0) {
3068                FeatureInfo[] features = new FeatureInfo[size+1];
3069                featSet.toArray(features);
3070                FeatureInfo fi = new FeatureInfo();
3071                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3072                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3073                features[size] = fi;
3074                return features;
3075            }
3076        }
3077        return null;
3078    }
3079
3080    @Override
3081    public boolean hasSystemFeature(String name) {
3082        synchronized (mPackages) {
3083            return mAvailableFeatures.containsKey(name);
3084        }
3085    }
3086
3087    private void checkValidCaller(int uid, int userId) {
3088        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3089            return;
3090
3091        throw new SecurityException("Caller uid=" + uid
3092                + " is not privileged to communicate with user=" + userId);
3093    }
3094
3095    @Override
3096    public int checkPermission(String permName, String pkgName, int userId) {
3097        if (!sUserManager.exists(userId)) {
3098            return PackageManager.PERMISSION_DENIED;
3099        }
3100
3101        synchronized (mPackages) {
3102            final PackageParser.Package p = mPackages.get(pkgName);
3103            if (p != null && p.mExtras != null) {
3104                final PackageSetting ps = (PackageSetting) p.mExtras;
3105                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3106                    return PackageManager.PERMISSION_GRANTED;
3107                }
3108            }
3109        }
3110
3111        return PackageManager.PERMISSION_DENIED;
3112    }
3113
3114    @Override
3115    public int checkUidPermission(String permName, int uid) {
3116        final int userId = UserHandle.getUserId(uid);
3117
3118        if (!sUserManager.exists(userId)) {
3119            return PackageManager.PERMISSION_DENIED;
3120        }
3121
3122        synchronized (mPackages) {
3123            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3124            if (obj != null) {
3125                final SettingBase ps = (SettingBase) obj;
3126                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3127                    return PackageManager.PERMISSION_GRANTED;
3128                }
3129            } else {
3130                ArraySet<String> perms = mSystemPermissions.get(uid);
3131                if (perms != null && perms.contains(permName)) {
3132                    return PackageManager.PERMISSION_GRANTED;
3133                }
3134            }
3135        }
3136
3137        return PackageManager.PERMISSION_DENIED;
3138    }
3139
3140    @Override
3141    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3142        if (UserHandle.getCallingUserId() != userId) {
3143            mContext.enforceCallingPermission(
3144                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3145                    "isPermissionRevokedByPolicy for user " + userId);
3146        }
3147
3148        if (checkPermission(permission, packageName, userId)
3149                == PackageManager.PERMISSION_GRANTED) {
3150            return false;
3151        }
3152
3153        final long identity = Binder.clearCallingIdentity();
3154        try {
3155            final int flags = getPermissionFlags(permission, packageName, userId);
3156            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3157        } finally {
3158            Binder.restoreCallingIdentity(identity);
3159        }
3160    }
3161
3162    /**
3163     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3164     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3165     * @param checkShell TODO(yamasani):
3166     * @param message the message to log on security exception
3167     */
3168    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3169            boolean checkShell, String message) {
3170        if (userId < 0) {
3171            throw new IllegalArgumentException("Invalid userId " + userId);
3172        }
3173        if (checkShell) {
3174            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3175        }
3176        if (userId == UserHandle.getUserId(callingUid)) return;
3177        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3178            if (requireFullPermission) {
3179                mContext.enforceCallingOrSelfPermission(
3180                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3181            } else {
3182                try {
3183                    mContext.enforceCallingOrSelfPermission(
3184                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3185                } catch (SecurityException se) {
3186                    mContext.enforceCallingOrSelfPermission(
3187                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3188                }
3189            }
3190        }
3191    }
3192
3193    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3194        if (callingUid == Process.SHELL_UID) {
3195            if (userHandle >= 0
3196                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3197                throw new SecurityException("Shell does not have permission to access user "
3198                        + userHandle);
3199            } else if (userHandle < 0) {
3200                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3201                        + Debug.getCallers(3));
3202            }
3203        }
3204    }
3205
3206    private BasePermission findPermissionTreeLP(String permName) {
3207        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3208            if (permName.startsWith(bp.name) &&
3209                    permName.length() > bp.name.length() &&
3210                    permName.charAt(bp.name.length()) == '.') {
3211                return bp;
3212            }
3213        }
3214        return null;
3215    }
3216
3217    private BasePermission checkPermissionTreeLP(String permName) {
3218        if (permName != null) {
3219            BasePermission bp = findPermissionTreeLP(permName);
3220            if (bp != null) {
3221                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3222                    return bp;
3223                }
3224                throw new SecurityException("Calling uid "
3225                        + Binder.getCallingUid()
3226                        + " is not allowed to add to permission tree "
3227                        + bp.name + " owned by uid " + bp.uid);
3228            }
3229        }
3230        throw new SecurityException("No permission tree found for " + permName);
3231    }
3232
3233    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3234        if (s1 == null) {
3235            return s2 == null;
3236        }
3237        if (s2 == null) {
3238            return false;
3239        }
3240        if (s1.getClass() != s2.getClass()) {
3241            return false;
3242        }
3243        return s1.equals(s2);
3244    }
3245
3246    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3247        if (pi1.icon != pi2.icon) return false;
3248        if (pi1.logo != pi2.logo) return false;
3249        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3250        if (!compareStrings(pi1.name, pi2.name)) return false;
3251        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3252        // We'll take care of setting this one.
3253        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3254        // These are not currently stored in settings.
3255        //if (!compareStrings(pi1.group, pi2.group)) return false;
3256        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3257        //if (pi1.labelRes != pi2.labelRes) return false;
3258        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3259        return true;
3260    }
3261
3262    int permissionInfoFootprint(PermissionInfo info) {
3263        int size = info.name.length();
3264        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3265        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3266        return size;
3267    }
3268
3269    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3270        int size = 0;
3271        for (BasePermission perm : mSettings.mPermissions.values()) {
3272            if (perm.uid == tree.uid) {
3273                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3274            }
3275        }
3276        return size;
3277    }
3278
3279    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3280        // We calculate the max size of permissions defined by this uid and throw
3281        // if that plus the size of 'info' would exceed our stated maximum.
3282        if (tree.uid != Process.SYSTEM_UID) {
3283            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3284            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3285                throw new SecurityException("Permission tree size cap exceeded");
3286            }
3287        }
3288    }
3289
3290    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3291        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3292            throw new SecurityException("Label must be specified in permission");
3293        }
3294        BasePermission tree = checkPermissionTreeLP(info.name);
3295        BasePermission bp = mSettings.mPermissions.get(info.name);
3296        boolean added = bp == null;
3297        boolean changed = true;
3298        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3299        if (added) {
3300            enforcePermissionCapLocked(info, tree);
3301            bp = new BasePermission(info.name, tree.sourcePackage,
3302                    BasePermission.TYPE_DYNAMIC);
3303        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3304            throw new SecurityException(
3305                    "Not allowed to modify non-dynamic permission "
3306                    + info.name);
3307        } else {
3308            if (bp.protectionLevel == fixedLevel
3309                    && bp.perm.owner.equals(tree.perm.owner)
3310                    && bp.uid == tree.uid
3311                    && comparePermissionInfos(bp.perm.info, info)) {
3312                changed = false;
3313            }
3314        }
3315        bp.protectionLevel = fixedLevel;
3316        info = new PermissionInfo(info);
3317        info.protectionLevel = fixedLevel;
3318        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3319        bp.perm.info.packageName = tree.perm.info.packageName;
3320        bp.uid = tree.uid;
3321        if (added) {
3322            mSettings.mPermissions.put(info.name, bp);
3323        }
3324        if (changed) {
3325            if (!async) {
3326                mSettings.writeLPr();
3327            } else {
3328                scheduleWriteSettingsLocked();
3329            }
3330        }
3331        return added;
3332    }
3333
3334    @Override
3335    public boolean addPermission(PermissionInfo info) {
3336        synchronized (mPackages) {
3337            return addPermissionLocked(info, false);
3338        }
3339    }
3340
3341    @Override
3342    public boolean addPermissionAsync(PermissionInfo info) {
3343        synchronized (mPackages) {
3344            return addPermissionLocked(info, true);
3345        }
3346    }
3347
3348    @Override
3349    public void removePermission(String name) {
3350        synchronized (mPackages) {
3351            checkPermissionTreeLP(name);
3352            BasePermission bp = mSettings.mPermissions.get(name);
3353            if (bp != null) {
3354                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3355                    throw new SecurityException(
3356                            "Not allowed to modify non-dynamic permission "
3357                            + name);
3358                }
3359                mSettings.mPermissions.remove(name);
3360                mSettings.writeLPr();
3361            }
3362        }
3363    }
3364
3365    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3366            BasePermission bp) {
3367        int index = pkg.requestedPermissions.indexOf(bp.name);
3368        if (index == -1) {
3369            throw new SecurityException("Package " + pkg.packageName
3370                    + " has not requested permission " + bp.name);
3371        }
3372        if (!bp.isRuntime()) {
3373            throw new SecurityException("Permission " + bp.name
3374                    + " is not a changeable permission type");
3375        }
3376    }
3377
3378    @Override
3379    public void grantRuntimePermission(String packageName, String name, final int userId) {
3380        if (!sUserManager.exists(userId)) {
3381            Log.e(TAG, "No such user:" + userId);
3382            return;
3383        }
3384
3385        mContext.enforceCallingOrSelfPermission(
3386                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3387                "grantRuntimePermission");
3388
3389        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3390                "grantRuntimePermission");
3391
3392        final int uid;
3393        final SettingBase sb;
3394
3395        synchronized (mPackages) {
3396            final PackageParser.Package pkg = mPackages.get(packageName);
3397            if (pkg == null) {
3398                throw new IllegalArgumentException("Unknown package: " + packageName);
3399            }
3400
3401            final BasePermission bp = mSettings.mPermissions.get(name);
3402            if (bp == null) {
3403                throw new IllegalArgumentException("Unknown permission: " + name);
3404            }
3405
3406            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3407
3408            uid = pkg.applicationInfo.uid;
3409            sb = (SettingBase) pkg.mExtras;
3410            if (sb == null) {
3411                throw new IllegalArgumentException("Unknown package: " + packageName);
3412            }
3413
3414            final PermissionsState permissionsState = sb.getPermissionsState();
3415
3416            final int flags = permissionsState.getPermissionFlags(name, userId);
3417            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3418                throw new SecurityException("Cannot grant system fixed permission: "
3419                        + name + " for package: " + packageName);
3420            }
3421
3422            final int result = permissionsState.grantRuntimePermission(bp, userId);
3423            switch (result) {
3424                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3425                    return;
3426                }
3427
3428                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3429                    mHandler.post(new Runnable() {
3430                        @Override
3431                        public void run() {
3432                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3433                        }
3434                    });
3435                } break;
3436            }
3437
3438            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3439
3440            // Not critical if that is lost - app has to request again.
3441            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3442        }
3443
3444        if (READ_EXTERNAL_STORAGE.equals(name)
3445                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3446            final long token = Binder.clearCallingIdentity();
3447            try {
3448                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3449                storage.remountUid(uid);
3450            } finally {
3451                Binder.restoreCallingIdentity(token);
3452            }
3453        }
3454    }
3455
3456    @Override
3457    public void revokeRuntimePermission(String packageName, String name, int userId) {
3458        if (!sUserManager.exists(userId)) {
3459            Log.e(TAG, "No such user:" + userId);
3460            return;
3461        }
3462
3463        mContext.enforceCallingOrSelfPermission(
3464                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3465                "revokeRuntimePermission");
3466
3467        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3468                "revokeRuntimePermission");
3469
3470        final SettingBase sb;
3471
3472        synchronized (mPackages) {
3473            final PackageParser.Package pkg = mPackages.get(packageName);
3474            if (pkg == null) {
3475                throw new IllegalArgumentException("Unknown package: " + packageName);
3476            }
3477
3478            final BasePermission bp = mSettings.mPermissions.get(name);
3479            if (bp == null) {
3480                throw new IllegalArgumentException("Unknown permission: " + name);
3481            }
3482
3483            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3484
3485            sb = (SettingBase) pkg.mExtras;
3486            if (sb == null) {
3487                throw new IllegalArgumentException("Unknown package: " + packageName);
3488            }
3489
3490            final PermissionsState permissionsState = sb.getPermissionsState();
3491
3492            final int flags = permissionsState.getPermissionFlags(name, userId);
3493            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3494                throw new SecurityException("Cannot revoke system fixed permission: "
3495                        + name + " for package: " + packageName);
3496            }
3497
3498            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3499                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3500                return;
3501            }
3502
3503            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3504
3505            // Critical, after this call app should never have the permission.
3506            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3507        }
3508
3509        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3510    }
3511
3512    @Override
3513    public void resetRuntimePermissions() {
3514        mContext.enforceCallingOrSelfPermission(
3515                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3516                "revokeRuntimePermission");
3517
3518        int callingUid = Binder.getCallingUid();
3519        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3520            mContext.enforceCallingOrSelfPermission(
3521                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3522                    "resetRuntimePermissions");
3523        }
3524
3525        final int[] userIds;
3526
3527        synchronized (mPackages) {
3528            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3529            final int userCount = UserManagerService.getInstance().getUserIds().length;
3530            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3531        }
3532
3533        for (int userId : userIds) {
3534            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3535        }
3536    }
3537
3538    @Override
3539    public int getPermissionFlags(String name, String packageName, int userId) {
3540        if (!sUserManager.exists(userId)) {
3541            return 0;
3542        }
3543
3544        mContext.enforceCallingOrSelfPermission(
3545                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3546                "getPermissionFlags");
3547
3548        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3549                "getPermissionFlags");
3550
3551        synchronized (mPackages) {
3552            final PackageParser.Package pkg = mPackages.get(packageName);
3553            if (pkg == null) {
3554                throw new IllegalArgumentException("Unknown package: " + packageName);
3555            }
3556
3557            final BasePermission bp = mSettings.mPermissions.get(name);
3558            if (bp == null) {
3559                throw new IllegalArgumentException("Unknown permission: " + name);
3560            }
3561
3562            SettingBase sb = (SettingBase) pkg.mExtras;
3563            if (sb == null) {
3564                throw new IllegalArgumentException("Unknown package: " + packageName);
3565            }
3566
3567            PermissionsState permissionsState = sb.getPermissionsState();
3568            return permissionsState.getPermissionFlags(name, userId);
3569        }
3570    }
3571
3572    @Override
3573    public void updatePermissionFlags(String name, String packageName, int flagMask,
3574            int flagValues, int userId) {
3575        if (!sUserManager.exists(userId)) {
3576            return;
3577        }
3578
3579        mContext.enforceCallingOrSelfPermission(
3580                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3581                "updatePermissionFlags");
3582
3583        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3584                "updatePermissionFlags");
3585
3586        // Only the system can change system fixed flags.
3587        if (getCallingUid() != Process.SYSTEM_UID) {
3588            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3589            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3590        }
3591
3592        synchronized (mPackages) {
3593            final PackageParser.Package pkg = mPackages.get(packageName);
3594            if (pkg == null) {
3595                throw new IllegalArgumentException("Unknown package: " + packageName);
3596            }
3597
3598            final BasePermission bp = mSettings.mPermissions.get(name);
3599            if (bp == null) {
3600                throw new IllegalArgumentException("Unknown permission: " + name);
3601            }
3602
3603            SettingBase sb = (SettingBase) pkg.mExtras;
3604            if (sb == null) {
3605                throw new IllegalArgumentException("Unknown package: " + packageName);
3606            }
3607
3608            PermissionsState permissionsState = sb.getPermissionsState();
3609
3610            // Only the package manager can change flags for system component permissions.
3611            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3612            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3613                return;
3614            }
3615
3616            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3617
3618            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3619                // Install and runtime permissions are stored in different places,
3620                // so figure out what permission changed and persist the change.
3621                if (permissionsState.getInstallPermissionState(name) != null) {
3622                    scheduleWriteSettingsLocked();
3623                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3624                        || hadState) {
3625                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3626                }
3627            }
3628        }
3629    }
3630
3631    /**
3632     * Update the permission flags for all packages and runtime permissions of a user in order
3633     * to allow device or profile owner to remove POLICY_FIXED.
3634     */
3635    @Override
3636    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3637        if (!sUserManager.exists(userId)) {
3638            return;
3639        }
3640
3641        mContext.enforceCallingOrSelfPermission(
3642                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3643                "updatePermissionFlagsForAllApps");
3644
3645        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3646                "updatePermissionFlagsForAllApps");
3647
3648        // Only the system can change system fixed flags.
3649        if (getCallingUid() != Process.SYSTEM_UID) {
3650            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3651            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3652        }
3653
3654        synchronized (mPackages) {
3655            boolean changed = false;
3656            final int packageCount = mPackages.size();
3657            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3658                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3659                SettingBase sb = (SettingBase) pkg.mExtras;
3660                if (sb == null) {
3661                    continue;
3662                }
3663                PermissionsState permissionsState = sb.getPermissionsState();
3664                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3665                        userId, flagMask, flagValues);
3666            }
3667            if (changed) {
3668                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3669            }
3670        }
3671    }
3672
3673    @Override
3674    public boolean shouldShowRequestPermissionRationale(String permissionName,
3675            String packageName, int userId) {
3676        if (UserHandle.getCallingUserId() != userId) {
3677            mContext.enforceCallingPermission(
3678                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3679                    "canShowRequestPermissionRationale for user " + userId);
3680        }
3681
3682        final int uid = getPackageUid(packageName, userId);
3683        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3684            return false;
3685        }
3686
3687        if (checkPermission(permissionName, packageName, userId)
3688                == PackageManager.PERMISSION_GRANTED) {
3689            return false;
3690        }
3691
3692        final int flags;
3693
3694        final long identity = Binder.clearCallingIdentity();
3695        try {
3696            flags = getPermissionFlags(permissionName,
3697                    packageName, userId);
3698        } finally {
3699            Binder.restoreCallingIdentity(identity);
3700        }
3701
3702        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3703                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3704                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3705
3706        if ((flags & fixedFlags) != 0) {
3707            return false;
3708        }
3709
3710        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3711    }
3712
3713    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3714        BasePermission bp = mSettings.mPermissions.get(permission);
3715        if (bp == null) {
3716            throw new SecurityException("Missing " + permission + " permission");
3717        }
3718
3719        SettingBase sb = (SettingBase) pkg.mExtras;
3720        PermissionsState permissionsState = sb.getPermissionsState();
3721
3722        if (permissionsState.grantInstallPermission(bp) !=
3723                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3724            scheduleWriteSettingsLocked();
3725        }
3726    }
3727
3728    @Override
3729    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3730        mContext.enforceCallingOrSelfPermission(
3731                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3732                "addOnPermissionsChangeListener");
3733
3734        synchronized (mPackages) {
3735            mOnPermissionChangeListeners.addListenerLocked(listener);
3736        }
3737    }
3738
3739    @Override
3740    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3741        synchronized (mPackages) {
3742            mOnPermissionChangeListeners.removeListenerLocked(listener);
3743        }
3744    }
3745
3746    @Override
3747    public boolean isProtectedBroadcast(String actionName) {
3748        synchronized (mPackages) {
3749            return mProtectedBroadcasts.contains(actionName);
3750        }
3751    }
3752
3753    @Override
3754    public int checkSignatures(String pkg1, String pkg2) {
3755        synchronized (mPackages) {
3756            final PackageParser.Package p1 = mPackages.get(pkg1);
3757            final PackageParser.Package p2 = mPackages.get(pkg2);
3758            if (p1 == null || p1.mExtras == null
3759                    || p2 == null || p2.mExtras == null) {
3760                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3761            }
3762            return compareSignatures(p1.mSignatures, p2.mSignatures);
3763        }
3764    }
3765
3766    @Override
3767    public int checkUidSignatures(int uid1, int uid2) {
3768        // Map to base uids.
3769        uid1 = UserHandle.getAppId(uid1);
3770        uid2 = UserHandle.getAppId(uid2);
3771        // reader
3772        synchronized (mPackages) {
3773            Signature[] s1;
3774            Signature[] s2;
3775            Object obj = mSettings.getUserIdLPr(uid1);
3776            if (obj != null) {
3777                if (obj instanceof SharedUserSetting) {
3778                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3779                } else if (obj instanceof PackageSetting) {
3780                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3781                } else {
3782                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3783                }
3784            } else {
3785                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3786            }
3787            obj = mSettings.getUserIdLPr(uid2);
3788            if (obj != null) {
3789                if (obj instanceof SharedUserSetting) {
3790                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3791                } else if (obj instanceof PackageSetting) {
3792                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3793                } else {
3794                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3795                }
3796            } else {
3797                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3798            }
3799            return compareSignatures(s1, s2);
3800        }
3801    }
3802
3803    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3804        final long identity = Binder.clearCallingIdentity();
3805        try {
3806            if (sb instanceof SharedUserSetting) {
3807                SharedUserSetting sus = (SharedUserSetting) sb;
3808                final int packageCount = sus.packages.size();
3809                for (int i = 0; i < packageCount; i++) {
3810                    PackageSetting susPs = sus.packages.valueAt(i);
3811                    if (userId == UserHandle.USER_ALL) {
3812                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3813                    } else {
3814                        final int uid = UserHandle.getUid(userId, susPs.appId);
3815                        killUid(uid, reason);
3816                    }
3817                }
3818            } else if (sb instanceof PackageSetting) {
3819                PackageSetting ps = (PackageSetting) sb;
3820                if (userId == UserHandle.USER_ALL) {
3821                    killApplication(ps.pkg.packageName, ps.appId, reason);
3822                } else {
3823                    final int uid = UserHandle.getUid(userId, ps.appId);
3824                    killUid(uid, reason);
3825                }
3826            }
3827        } finally {
3828            Binder.restoreCallingIdentity(identity);
3829        }
3830    }
3831
3832    private static void killUid(int uid, String reason) {
3833        IActivityManager am = ActivityManagerNative.getDefault();
3834        if (am != null) {
3835            try {
3836                am.killUid(uid, reason);
3837            } catch (RemoteException e) {
3838                /* ignore - same process */
3839            }
3840        }
3841    }
3842
3843    /**
3844     * Compares two sets of signatures. Returns:
3845     * <br />
3846     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3847     * <br />
3848     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3849     * <br />
3850     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3851     * <br />
3852     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3853     * <br />
3854     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3855     */
3856    static int compareSignatures(Signature[] s1, Signature[] s2) {
3857        if (s1 == null) {
3858            return s2 == null
3859                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3860                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3861        }
3862
3863        if (s2 == null) {
3864            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3865        }
3866
3867        if (s1.length != s2.length) {
3868            return PackageManager.SIGNATURE_NO_MATCH;
3869        }
3870
3871        // Since both signature sets are of size 1, we can compare without HashSets.
3872        if (s1.length == 1) {
3873            return s1[0].equals(s2[0]) ?
3874                    PackageManager.SIGNATURE_MATCH :
3875                    PackageManager.SIGNATURE_NO_MATCH;
3876        }
3877
3878        ArraySet<Signature> set1 = new ArraySet<Signature>();
3879        for (Signature sig : s1) {
3880            set1.add(sig);
3881        }
3882        ArraySet<Signature> set2 = new ArraySet<Signature>();
3883        for (Signature sig : s2) {
3884            set2.add(sig);
3885        }
3886        // Make sure s2 contains all signatures in s1.
3887        if (set1.equals(set2)) {
3888            return PackageManager.SIGNATURE_MATCH;
3889        }
3890        return PackageManager.SIGNATURE_NO_MATCH;
3891    }
3892
3893    /**
3894     * If the database version for this type of package (internal storage or
3895     * external storage) is less than the version where package signatures
3896     * were updated, return true.
3897     */
3898    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3899        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3900                DatabaseVersion.SIGNATURE_END_ENTITY))
3901                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3902                        DatabaseVersion.SIGNATURE_END_ENTITY));
3903    }
3904
3905    /**
3906     * Used for backward compatibility to make sure any packages with
3907     * certificate chains get upgraded to the new style. {@code existingSigs}
3908     * will be in the old format (since they were stored on disk from before the
3909     * system upgrade) and {@code scannedSigs} will be in the newer format.
3910     */
3911    private int compareSignaturesCompat(PackageSignatures existingSigs,
3912            PackageParser.Package scannedPkg) {
3913        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3914            return PackageManager.SIGNATURE_NO_MATCH;
3915        }
3916
3917        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3918        for (Signature sig : existingSigs.mSignatures) {
3919            existingSet.add(sig);
3920        }
3921        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3922        for (Signature sig : scannedPkg.mSignatures) {
3923            try {
3924                Signature[] chainSignatures = sig.getChainSignatures();
3925                for (Signature chainSig : chainSignatures) {
3926                    scannedCompatSet.add(chainSig);
3927                }
3928            } catch (CertificateEncodingException e) {
3929                scannedCompatSet.add(sig);
3930            }
3931        }
3932        /*
3933         * Make sure the expanded scanned set contains all signatures in the
3934         * existing one.
3935         */
3936        if (scannedCompatSet.equals(existingSet)) {
3937            // Migrate the old signatures to the new scheme.
3938            existingSigs.assignSignatures(scannedPkg.mSignatures);
3939            // The new KeySets will be re-added later in the scanning process.
3940            synchronized (mPackages) {
3941                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3942            }
3943            return PackageManager.SIGNATURE_MATCH;
3944        }
3945        return PackageManager.SIGNATURE_NO_MATCH;
3946    }
3947
3948    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3949        if (isExternal(scannedPkg)) {
3950            return mSettings.isExternalDatabaseVersionOlderThan(
3951                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3952        } else {
3953            return mSettings.isInternalDatabaseVersionOlderThan(
3954                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3955        }
3956    }
3957
3958    private int compareSignaturesRecover(PackageSignatures existingSigs,
3959            PackageParser.Package scannedPkg) {
3960        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3961            return PackageManager.SIGNATURE_NO_MATCH;
3962        }
3963
3964        String msg = null;
3965        try {
3966            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3967                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3968                        + scannedPkg.packageName);
3969                return PackageManager.SIGNATURE_MATCH;
3970            }
3971        } catch (CertificateException e) {
3972            msg = e.getMessage();
3973        }
3974
3975        logCriticalInfo(Log.INFO,
3976                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3977        return PackageManager.SIGNATURE_NO_MATCH;
3978    }
3979
3980    @Override
3981    public String[] getPackagesForUid(int uid) {
3982        uid = UserHandle.getAppId(uid);
3983        // reader
3984        synchronized (mPackages) {
3985            Object obj = mSettings.getUserIdLPr(uid);
3986            if (obj instanceof SharedUserSetting) {
3987                final SharedUserSetting sus = (SharedUserSetting) obj;
3988                final int N = sus.packages.size();
3989                final String[] res = new String[N];
3990                final Iterator<PackageSetting> it = sus.packages.iterator();
3991                int i = 0;
3992                while (it.hasNext()) {
3993                    res[i++] = it.next().name;
3994                }
3995                return res;
3996            } else if (obj instanceof PackageSetting) {
3997                final PackageSetting ps = (PackageSetting) obj;
3998                return new String[] { ps.name };
3999            }
4000        }
4001        return null;
4002    }
4003
4004    @Override
4005    public String getNameForUid(int uid) {
4006        // reader
4007        synchronized (mPackages) {
4008            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4009            if (obj instanceof SharedUserSetting) {
4010                final SharedUserSetting sus = (SharedUserSetting) obj;
4011                return sus.name + ":" + sus.userId;
4012            } else if (obj instanceof PackageSetting) {
4013                final PackageSetting ps = (PackageSetting) obj;
4014                return ps.name;
4015            }
4016        }
4017        return null;
4018    }
4019
4020    @Override
4021    public int getUidForSharedUser(String sharedUserName) {
4022        if(sharedUserName == null) {
4023            return -1;
4024        }
4025        // reader
4026        synchronized (mPackages) {
4027            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4028            if (suid == null) {
4029                return -1;
4030            }
4031            return suid.userId;
4032        }
4033    }
4034
4035    @Override
4036    public int getFlagsForUid(int uid) {
4037        synchronized (mPackages) {
4038            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4039            if (obj instanceof SharedUserSetting) {
4040                final SharedUserSetting sus = (SharedUserSetting) obj;
4041                return sus.pkgFlags;
4042            } else if (obj instanceof PackageSetting) {
4043                final PackageSetting ps = (PackageSetting) obj;
4044                return ps.pkgFlags;
4045            }
4046        }
4047        return 0;
4048    }
4049
4050    @Override
4051    public int getPrivateFlagsForUid(int uid) {
4052        synchronized (mPackages) {
4053            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4054            if (obj instanceof SharedUserSetting) {
4055                final SharedUserSetting sus = (SharedUserSetting) obj;
4056                return sus.pkgPrivateFlags;
4057            } else if (obj instanceof PackageSetting) {
4058                final PackageSetting ps = (PackageSetting) obj;
4059                return ps.pkgPrivateFlags;
4060            }
4061        }
4062        return 0;
4063    }
4064
4065    @Override
4066    public boolean isUidPrivileged(int uid) {
4067        uid = UserHandle.getAppId(uid);
4068        // reader
4069        synchronized (mPackages) {
4070            Object obj = mSettings.getUserIdLPr(uid);
4071            if (obj instanceof SharedUserSetting) {
4072                final SharedUserSetting sus = (SharedUserSetting) obj;
4073                final Iterator<PackageSetting> it = sus.packages.iterator();
4074                while (it.hasNext()) {
4075                    if (it.next().isPrivileged()) {
4076                        return true;
4077                    }
4078                }
4079            } else if (obj instanceof PackageSetting) {
4080                final PackageSetting ps = (PackageSetting) obj;
4081                return ps.isPrivileged();
4082            }
4083        }
4084        return false;
4085    }
4086
4087    @Override
4088    public String[] getAppOpPermissionPackages(String permissionName) {
4089        synchronized (mPackages) {
4090            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4091            if (pkgs == null) {
4092                return null;
4093            }
4094            return pkgs.toArray(new String[pkgs.size()]);
4095        }
4096    }
4097
4098    @Override
4099    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4100            int flags, int userId) {
4101        if (!sUserManager.exists(userId)) return null;
4102        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4103        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4104        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4105    }
4106
4107    @Override
4108    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4109            IntentFilter filter, int match, ComponentName activity) {
4110        final int userId = UserHandle.getCallingUserId();
4111        if (DEBUG_PREFERRED) {
4112            Log.v(TAG, "setLastChosenActivity intent=" + intent
4113                + " resolvedType=" + resolvedType
4114                + " flags=" + flags
4115                + " filter=" + filter
4116                + " match=" + match
4117                + " activity=" + activity);
4118            filter.dump(new PrintStreamPrinter(System.out), "    ");
4119        }
4120        intent.setComponent(null);
4121        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4122        // Find any earlier preferred or last chosen entries and nuke them
4123        findPreferredActivity(intent, resolvedType,
4124                flags, query, 0, false, true, false, userId);
4125        // Add the new activity as the last chosen for this filter
4126        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4127                "Setting last chosen");
4128    }
4129
4130    @Override
4131    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4132        final int userId = UserHandle.getCallingUserId();
4133        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4134        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4135        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4136                false, false, false, userId);
4137    }
4138
4139    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4140            int flags, List<ResolveInfo> query, int userId) {
4141        if (query != null) {
4142            final int N = query.size();
4143            if (N == 1) {
4144                return query.get(0);
4145            } else if (N > 1) {
4146                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4147                // If there is more than one activity with the same priority,
4148                // then let the user decide between them.
4149                ResolveInfo r0 = query.get(0);
4150                ResolveInfo r1 = query.get(1);
4151                if (DEBUG_INTENT_MATCHING || debug) {
4152                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4153                            + r1.activityInfo.name + "=" + r1.priority);
4154                }
4155                // If the first activity has a higher priority, or a different
4156                // default, then it is always desireable to pick it.
4157                if (r0.priority != r1.priority
4158                        || r0.preferredOrder != r1.preferredOrder
4159                        || r0.isDefault != r1.isDefault) {
4160                    return query.get(0);
4161                }
4162                // If we have saved a preference for a preferred activity for
4163                // this Intent, use that.
4164                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4165                        flags, query, r0.priority, true, false, debug, userId);
4166                if (ri != null) {
4167                    return ri;
4168                }
4169                if (userId != 0) {
4170                    ri = new ResolveInfo(mResolveInfo);
4171                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4172                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4173                            ri.activityInfo.applicationInfo);
4174                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4175                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4176                    return ri;
4177                }
4178                return mResolveInfo;
4179            }
4180        }
4181        return null;
4182    }
4183
4184    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4185            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4186        final int N = query.size();
4187        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4188                .get(userId);
4189        // Get the list of persistent preferred activities that handle the intent
4190        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4191        List<PersistentPreferredActivity> pprefs = ppir != null
4192                ? ppir.queryIntent(intent, resolvedType,
4193                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4194                : null;
4195        if (pprefs != null && pprefs.size() > 0) {
4196            final int M = pprefs.size();
4197            for (int i=0; i<M; i++) {
4198                final PersistentPreferredActivity ppa = pprefs.get(i);
4199                if (DEBUG_PREFERRED || debug) {
4200                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4201                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4202                            + "\n  component=" + ppa.mComponent);
4203                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4204                }
4205                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4206                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4207                if (DEBUG_PREFERRED || debug) {
4208                    Slog.v(TAG, "Found persistent preferred activity:");
4209                    if (ai != null) {
4210                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4211                    } else {
4212                        Slog.v(TAG, "  null");
4213                    }
4214                }
4215                if (ai == null) {
4216                    // This previously registered persistent preferred activity
4217                    // component is no longer known. Ignore it and do NOT remove it.
4218                    continue;
4219                }
4220                for (int j=0; j<N; j++) {
4221                    final ResolveInfo ri = query.get(j);
4222                    if (!ri.activityInfo.applicationInfo.packageName
4223                            .equals(ai.applicationInfo.packageName)) {
4224                        continue;
4225                    }
4226                    if (!ri.activityInfo.name.equals(ai.name)) {
4227                        continue;
4228                    }
4229                    //  Found a persistent preference that can handle the intent.
4230                    if (DEBUG_PREFERRED || debug) {
4231                        Slog.v(TAG, "Returning persistent preferred activity: " +
4232                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4233                    }
4234                    return ri;
4235                }
4236            }
4237        }
4238        return null;
4239    }
4240
4241    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4242            List<ResolveInfo> query, int priority, boolean always,
4243            boolean removeMatches, boolean debug, int userId) {
4244        if (!sUserManager.exists(userId)) return null;
4245        // writer
4246        synchronized (mPackages) {
4247            if (intent.getSelector() != null) {
4248                intent = intent.getSelector();
4249            }
4250            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4251
4252            // Try to find a matching persistent preferred activity.
4253            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4254                    debug, userId);
4255
4256            // If a persistent preferred activity matched, use it.
4257            if (pri != null) {
4258                return pri;
4259            }
4260
4261            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4262            // Get the list of preferred activities that handle the intent
4263            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4264            List<PreferredActivity> prefs = pir != null
4265                    ? pir.queryIntent(intent, resolvedType,
4266                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4267                    : null;
4268            if (prefs != null && prefs.size() > 0) {
4269                boolean changed = false;
4270                try {
4271                    // First figure out how good the original match set is.
4272                    // We will only allow preferred activities that came
4273                    // from the same match quality.
4274                    int match = 0;
4275
4276                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4277
4278                    final int N = query.size();
4279                    for (int j=0; j<N; j++) {
4280                        final ResolveInfo ri = query.get(j);
4281                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4282                                + ": 0x" + Integer.toHexString(match));
4283                        if (ri.match > match) {
4284                            match = ri.match;
4285                        }
4286                    }
4287
4288                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4289                            + Integer.toHexString(match));
4290
4291                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4292                    final int M = prefs.size();
4293                    for (int i=0; i<M; i++) {
4294                        final PreferredActivity pa = prefs.get(i);
4295                        if (DEBUG_PREFERRED || debug) {
4296                            Slog.v(TAG, "Checking PreferredActivity ds="
4297                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4298                                    + "\n  component=" + pa.mPref.mComponent);
4299                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4300                        }
4301                        if (pa.mPref.mMatch != match) {
4302                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4303                                    + Integer.toHexString(pa.mPref.mMatch));
4304                            continue;
4305                        }
4306                        // If it's not an "always" type preferred activity and that's what we're
4307                        // looking for, skip it.
4308                        if (always && !pa.mPref.mAlways) {
4309                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4310                            continue;
4311                        }
4312                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4313                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4314                        if (DEBUG_PREFERRED || debug) {
4315                            Slog.v(TAG, "Found preferred activity:");
4316                            if (ai != null) {
4317                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4318                            } else {
4319                                Slog.v(TAG, "  null");
4320                            }
4321                        }
4322                        if (ai == null) {
4323                            // This previously registered preferred activity
4324                            // component is no longer known.  Most likely an update
4325                            // to the app was installed and in the new version this
4326                            // component no longer exists.  Clean it up by removing
4327                            // it from the preferred activities list, and skip it.
4328                            Slog.w(TAG, "Removing dangling preferred activity: "
4329                                    + pa.mPref.mComponent);
4330                            pir.removeFilter(pa);
4331                            changed = true;
4332                            continue;
4333                        }
4334                        for (int j=0; j<N; j++) {
4335                            final ResolveInfo ri = query.get(j);
4336                            if (!ri.activityInfo.applicationInfo.packageName
4337                                    .equals(ai.applicationInfo.packageName)) {
4338                                continue;
4339                            }
4340                            if (!ri.activityInfo.name.equals(ai.name)) {
4341                                continue;
4342                            }
4343
4344                            if (removeMatches) {
4345                                pir.removeFilter(pa);
4346                                changed = true;
4347                                if (DEBUG_PREFERRED) {
4348                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4349                                }
4350                                break;
4351                            }
4352
4353                            // Okay we found a previously set preferred or last chosen app.
4354                            // If the result set is different from when this
4355                            // was created, we need to clear it and re-ask the
4356                            // user their preference, if we're looking for an "always" type entry.
4357                            if (always && !pa.mPref.sameSet(query)) {
4358                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4359                                        + intent + " type " + resolvedType);
4360                                if (DEBUG_PREFERRED) {
4361                                    Slog.v(TAG, "Removing preferred activity since set changed "
4362                                            + pa.mPref.mComponent);
4363                                }
4364                                pir.removeFilter(pa);
4365                                // Re-add the filter as a "last chosen" entry (!always)
4366                                PreferredActivity lastChosen = new PreferredActivity(
4367                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4368                                pir.addFilter(lastChosen);
4369                                changed = true;
4370                                return null;
4371                            }
4372
4373                            // Yay! Either the set matched or we're looking for the last chosen
4374                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4375                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4376                            return ri;
4377                        }
4378                    }
4379                } finally {
4380                    if (changed) {
4381                        if (DEBUG_PREFERRED) {
4382                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4383                        }
4384                        scheduleWritePackageRestrictionsLocked(userId);
4385                    }
4386                }
4387            }
4388        }
4389        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4390        return null;
4391    }
4392
4393    /*
4394     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4395     */
4396    @Override
4397    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4398            int targetUserId) {
4399        mContext.enforceCallingOrSelfPermission(
4400                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4401        List<CrossProfileIntentFilter> matches =
4402                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4403        if (matches != null) {
4404            int size = matches.size();
4405            for (int i = 0; i < size; i++) {
4406                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4407            }
4408        }
4409        if (hasWebURI(intent)) {
4410            // cross-profile app linking works only towards the parent.
4411            final UserInfo parent = getProfileParent(sourceUserId);
4412            synchronized(mPackages) {
4413                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4414                        parent.id) != null;
4415            }
4416        }
4417        return false;
4418    }
4419
4420    private UserInfo getProfileParent(int userId) {
4421        final long identity = Binder.clearCallingIdentity();
4422        try {
4423            return sUserManager.getProfileParent(userId);
4424        } finally {
4425            Binder.restoreCallingIdentity(identity);
4426        }
4427    }
4428
4429    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4430            String resolvedType, int userId) {
4431        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4432        if (resolver != null) {
4433            return resolver.queryIntent(intent, resolvedType, false, userId);
4434        }
4435        return null;
4436    }
4437
4438    @Override
4439    public List<ResolveInfo> queryIntentActivities(Intent intent,
4440            String resolvedType, int flags, int userId) {
4441        if (!sUserManager.exists(userId)) return Collections.emptyList();
4442        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4443        ComponentName comp = intent.getComponent();
4444        if (comp == null) {
4445            if (intent.getSelector() != null) {
4446                intent = intent.getSelector();
4447                comp = intent.getComponent();
4448            }
4449        }
4450
4451        if (comp != null) {
4452            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4453            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4454            if (ai != null) {
4455                final ResolveInfo ri = new ResolveInfo();
4456                ri.activityInfo = ai;
4457                list.add(ri);
4458            }
4459            return list;
4460        }
4461
4462        // reader
4463        synchronized (mPackages) {
4464            final String pkgName = intent.getPackage();
4465            if (pkgName == null) {
4466                List<CrossProfileIntentFilter> matchingFilters =
4467                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4468                // Check for results that need to skip the current profile.
4469                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4470                        resolvedType, flags, userId);
4471                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4472                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4473                    result.add(xpResolveInfo);
4474                    return filterIfNotPrimaryUser(result, userId);
4475                }
4476
4477                // Check for results in the current profile.
4478                List<ResolveInfo> result = mActivities.queryIntent(
4479                        intent, resolvedType, flags, userId);
4480
4481                // Check for cross profile results.
4482                xpResolveInfo = queryCrossProfileIntents(
4483                        matchingFilters, intent, resolvedType, flags, userId);
4484                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4485                    result.add(xpResolveInfo);
4486                    Collections.sort(result, mResolvePrioritySorter);
4487                }
4488                result = filterIfNotPrimaryUser(result, userId);
4489                if (hasWebURI(intent)) {
4490                    CrossProfileDomainInfo xpDomainInfo = null;
4491                    final UserInfo parent = getProfileParent(userId);
4492                    if (parent != null) {
4493                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4494                                flags, userId, parent.id);
4495                    }
4496                    if (xpDomainInfo != null) {
4497                        if (xpResolveInfo != null) {
4498                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4499                            // in the result.
4500                            result.remove(xpResolveInfo);
4501                        }
4502                        if (result.size() == 0) {
4503                            result.add(xpDomainInfo.resolveInfo);
4504                            return result;
4505                        }
4506                    } else if (result.size() <= 1) {
4507                        return result;
4508                    }
4509                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4510                            xpDomainInfo);
4511                    Collections.sort(result, mResolvePrioritySorter);
4512                }
4513                return result;
4514            }
4515            final PackageParser.Package pkg = mPackages.get(pkgName);
4516            if (pkg != null) {
4517                return filterIfNotPrimaryUser(
4518                        mActivities.queryIntentForPackage(
4519                                intent, resolvedType, flags, pkg.activities, userId),
4520                        userId);
4521            }
4522            return new ArrayList<ResolveInfo>();
4523        }
4524    }
4525
4526    private static class CrossProfileDomainInfo {
4527        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4528        ResolveInfo resolveInfo;
4529        /* Best domain verification status of the activities found in the other profile */
4530        int bestDomainVerificationStatus;
4531    }
4532
4533    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4534            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4535        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4536                sourceUserId)) {
4537            return null;
4538        }
4539        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4540                resolvedType, flags, parentUserId);
4541
4542        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4543            return null;
4544        }
4545        CrossProfileDomainInfo result = null;
4546        int size = resultTargetUser.size();
4547        for (int i = 0; i < size; i++) {
4548            ResolveInfo riTargetUser = resultTargetUser.get(i);
4549            // Intent filter verification is only for filters that specify a host. So don't return
4550            // those that handle all web uris.
4551            if (riTargetUser.handleAllWebDataURI) {
4552                continue;
4553            }
4554            String packageName = riTargetUser.activityInfo.packageName;
4555            PackageSetting ps = mSettings.mPackages.get(packageName);
4556            if (ps == null) {
4557                continue;
4558            }
4559            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4560            if (result == null) {
4561                result = new CrossProfileDomainInfo();
4562                result.resolveInfo =
4563                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4564                result.bestDomainVerificationStatus = status;
4565            } else {
4566                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4567                        result.bestDomainVerificationStatus);
4568            }
4569        }
4570        return result;
4571    }
4572
4573    /**
4574     * Verification statuses are ordered from the worse to the best, except for
4575     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4576     */
4577    private int bestDomainVerificationStatus(int status1, int status2) {
4578        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4579            return status2;
4580        }
4581        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4582            return status1;
4583        }
4584        return (int) MathUtils.max(status1, status2);
4585    }
4586
4587    private boolean isUserEnabled(int userId) {
4588        long callingId = Binder.clearCallingIdentity();
4589        try {
4590            UserInfo userInfo = sUserManager.getUserInfo(userId);
4591            return userInfo != null && userInfo.isEnabled();
4592        } finally {
4593            Binder.restoreCallingIdentity(callingId);
4594        }
4595    }
4596
4597    /**
4598     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4599     *
4600     * @return filtered list
4601     */
4602    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4603        if (userId == UserHandle.USER_OWNER) {
4604            return resolveInfos;
4605        }
4606        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4607            ResolveInfo info = resolveInfos.get(i);
4608            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4609                resolveInfos.remove(i);
4610            }
4611        }
4612        return resolveInfos;
4613    }
4614
4615    private static boolean hasWebURI(Intent intent) {
4616        if (intent.getData() == null) {
4617            return false;
4618        }
4619        final String scheme = intent.getScheme();
4620        if (TextUtils.isEmpty(scheme)) {
4621            return false;
4622        }
4623        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4624    }
4625
4626    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4627            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4628        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4629            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4630                    candidates.size());
4631        }
4632
4633        final int userId = UserHandle.getCallingUserId();
4634        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4635        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4636        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4637        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4638        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4639
4640        synchronized (mPackages) {
4641            final int count = candidates.size();
4642            // First, try to use linked apps. Partition the candidates into four lists:
4643            // one for the final results, one for the "do not use ever", one for "undefined status"
4644            // and finally one for "browser app type".
4645            for (int n=0; n<count; n++) {
4646                ResolveInfo info = candidates.get(n);
4647                String packageName = info.activityInfo.packageName;
4648                PackageSetting ps = mSettings.mPackages.get(packageName);
4649                if (ps != null) {
4650                    // Add to the special match all list (Browser use case)
4651                    if (info.handleAllWebDataURI) {
4652                        matchAllList.add(info);
4653                        continue;
4654                    }
4655                    // Try to get the status from User settings first
4656                    int status = getDomainVerificationStatusLPr(ps, userId);
4657                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4658                        if (DEBUG_DOMAIN_VERIFICATION) {
4659                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4660                        }
4661                        alwaysList.add(info);
4662                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4663                        if (DEBUG_DOMAIN_VERIFICATION) {
4664                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4665                        }
4666                        neverList.add(info);
4667                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4668                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4669                        if (DEBUG_DOMAIN_VERIFICATION) {
4670                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4671                        }
4672                        undefinedList.add(info);
4673                    }
4674                }
4675            }
4676            // First try to add the "always" resolution for the current user if there is any
4677            if (alwaysList.size() > 0) {
4678                result.addAll(alwaysList);
4679            // if there is an "always" for the parent user, add it.
4680            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4681                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4682                result.add(xpDomainInfo.resolveInfo);
4683            } else {
4684                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4685                result.addAll(undefinedList);
4686                if (xpDomainInfo != null && (
4687                        xpDomainInfo.bestDomainVerificationStatus
4688                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4689                        || xpDomainInfo.bestDomainVerificationStatus
4690                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4691                    result.add(xpDomainInfo.resolveInfo);
4692                }
4693                // Also add Browsers (all of them or only the default one)
4694                if ((flags & MATCH_ALL) != 0) {
4695                    result.addAll(matchAllList);
4696                } else {
4697                    // Try to add the Default Browser if we can
4698                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4699                            UserHandle.myUserId());
4700                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4701                        boolean defaultBrowserFound = false;
4702                        final int browserCount = matchAllList.size();
4703                        for (int n=0; n<browserCount; n++) {
4704                            ResolveInfo browser = matchAllList.get(n);
4705                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4706                                result.add(browser);
4707                                defaultBrowserFound = true;
4708                                break;
4709                            }
4710                        }
4711                        if (!defaultBrowserFound) {
4712                            result.addAll(matchAllList);
4713                        }
4714                    } else {
4715                        result.addAll(matchAllList);
4716                    }
4717                }
4718
4719                // If there is nothing selected, add all candidates and remove the ones that the user
4720                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4721                if (result.size() == 0) {
4722                    result.addAll(candidates);
4723                    result.removeAll(neverList);
4724                }
4725            }
4726        }
4727        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4728            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4729                    result.size());
4730            for (ResolveInfo info : result) {
4731                Slog.v(TAG, "  + " + info.activityInfo);
4732            }
4733        }
4734        return result;
4735    }
4736
4737    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4738        int status = ps.getDomainVerificationStatusForUser(userId);
4739        // if none available, get the master status
4740        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4741            if (ps.getIntentFilterVerificationInfo() != null) {
4742                status = ps.getIntentFilterVerificationInfo().getStatus();
4743            }
4744        }
4745        return status;
4746    }
4747
4748    private ResolveInfo querySkipCurrentProfileIntents(
4749            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4750            int flags, int sourceUserId) {
4751        if (matchingFilters != null) {
4752            int size = matchingFilters.size();
4753            for (int i = 0; i < size; i ++) {
4754                CrossProfileIntentFilter filter = matchingFilters.get(i);
4755                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4756                    // Checking if there are activities in the target user that can handle the
4757                    // intent.
4758                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4759                            flags, sourceUserId);
4760                    if (resolveInfo != null) {
4761                        return resolveInfo;
4762                    }
4763                }
4764            }
4765        }
4766        return null;
4767    }
4768
4769    // Return matching ResolveInfo if any for skip current profile intent filters.
4770    private ResolveInfo queryCrossProfileIntents(
4771            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4772            int flags, int sourceUserId) {
4773        if (matchingFilters != null) {
4774            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4775            // match the same intent. For performance reasons, it is better not to
4776            // run queryIntent twice for the same userId
4777            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4778            int size = matchingFilters.size();
4779            for (int i = 0; i < size; i++) {
4780                CrossProfileIntentFilter filter = matchingFilters.get(i);
4781                int targetUserId = filter.getTargetUserId();
4782                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4783                        && !alreadyTriedUserIds.get(targetUserId)) {
4784                    // Checking if there are activities in the target user that can handle the
4785                    // intent.
4786                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4787                            flags, sourceUserId);
4788                    if (resolveInfo != null) return resolveInfo;
4789                    alreadyTriedUserIds.put(targetUserId, true);
4790                }
4791            }
4792        }
4793        return null;
4794    }
4795
4796    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4797            String resolvedType, int flags, int sourceUserId) {
4798        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4799                resolvedType, flags, filter.getTargetUserId());
4800        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4801            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4802        }
4803        return null;
4804    }
4805
4806    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4807            int sourceUserId, int targetUserId) {
4808        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4809        String className;
4810        if (targetUserId == UserHandle.USER_OWNER) {
4811            className = FORWARD_INTENT_TO_USER_OWNER;
4812        } else {
4813            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4814        }
4815        ComponentName forwardingActivityComponentName = new ComponentName(
4816                mAndroidApplication.packageName, className);
4817        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4818                sourceUserId);
4819        if (targetUserId == UserHandle.USER_OWNER) {
4820            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4821            forwardingResolveInfo.noResourceId = true;
4822        }
4823        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4824        forwardingResolveInfo.priority = 0;
4825        forwardingResolveInfo.preferredOrder = 0;
4826        forwardingResolveInfo.match = 0;
4827        forwardingResolveInfo.isDefault = true;
4828        forwardingResolveInfo.filter = filter;
4829        forwardingResolveInfo.targetUserId = targetUserId;
4830        return forwardingResolveInfo;
4831    }
4832
4833    @Override
4834    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4835            Intent[] specifics, String[] specificTypes, Intent intent,
4836            String resolvedType, int flags, int userId) {
4837        if (!sUserManager.exists(userId)) return Collections.emptyList();
4838        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4839                false, "query intent activity options");
4840        final String resultsAction = intent.getAction();
4841
4842        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4843                | PackageManager.GET_RESOLVED_FILTER, userId);
4844
4845        if (DEBUG_INTENT_MATCHING) {
4846            Log.v(TAG, "Query " + intent + ": " + results);
4847        }
4848
4849        int specificsPos = 0;
4850        int N;
4851
4852        // todo: note that the algorithm used here is O(N^2).  This
4853        // isn't a problem in our current environment, but if we start running
4854        // into situations where we have more than 5 or 10 matches then this
4855        // should probably be changed to something smarter...
4856
4857        // First we go through and resolve each of the specific items
4858        // that were supplied, taking care of removing any corresponding
4859        // duplicate items in the generic resolve list.
4860        if (specifics != null) {
4861            for (int i=0; i<specifics.length; i++) {
4862                final Intent sintent = specifics[i];
4863                if (sintent == null) {
4864                    continue;
4865                }
4866
4867                if (DEBUG_INTENT_MATCHING) {
4868                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4869                }
4870
4871                String action = sintent.getAction();
4872                if (resultsAction != null && resultsAction.equals(action)) {
4873                    // If this action was explicitly requested, then don't
4874                    // remove things that have it.
4875                    action = null;
4876                }
4877
4878                ResolveInfo ri = null;
4879                ActivityInfo ai = null;
4880
4881                ComponentName comp = sintent.getComponent();
4882                if (comp == null) {
4883                    ri = resolveIntent(
4884                        sintent,
4885                        specificTypes != null ? specificTypes[i] : null,
4886                            flags, userId);
4887                    if (ri == null) {
4888                        continue;
4889                    }
4890                    if (ri == mResolveInfo) {
4891                        // ACK!  Must do something better with this.
4892                    }
4893                    ai = ri.activityInfo;
4894                    comp = new ComponentName(ai.applicationInfo.packageName,
4895                            ai.name);
4896                } else {
4897                    ai = getActivityInfo(comp, flags, userId);
4898                    if (ai == null) {
4899                        continue;
4900                    }
4901                }
4902
4903                // Look for any generic query activities that are duplicates
4904                // of this specific one, and remove them from the results.
4905                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4906                N = results.size();
4907                int j;
4908                for (j=specificsPos; j<N; j++) {
4909                    ResolveInfo sri = results.get(j);
4910                    if ((sri.activityInfo.name.equals(comp.getClassName())
4911                            && sri.activityInfo.applicationInfo.packageName.equals(
4912                                    comp.getPackageName()))
4913                        || (action != null && sri.filter.matchAction(action))) {
4914                        results.remove(j);
4915                        if (DEBUG_INTENT_MATCHING) Log.v(
4916                            TAG, "Removing duplicate item from " + j
4917                            + " due to specific " + specificsPos);
4918                        if (ri == null) {
4919                            ri = sri;
4920                        }
4921                        j--;
4922                        N--;
4923                    }
4924                }
4925
4926                // Add this specific item to its proper place.
4927                if (ri == null) {
4928                    ri = new ResolveInfo();
4929                    ri.activityInfo = ai;
4930                }
4931                results.add(specificsPos, ri);
4932                ri.specificIndex = i;
4933                specificsPos++;
4934            }
4935        }
4936
4937        // Now we go through the remaining generic results and remove any
4938        // duplicate actions that are found here.
4939        N = results.size();
4940        for (int i=specificsPos; i<N-1; i++) {
4941            final ResolveInfo rii = results.get(i);
4942            if (rii.filter == null) {
4943                continue;
4944            }
4945
4946            // Iterate over all of the actions of this result's intent
4947            // filter...  typically this should be just one.
4948            final Iterator<String> it = rii.filter.actionsIterator();
4949            if (it == null) {
4950                continue;
4951            }
4952            while (it.hasNext()) {
4953                final String action = it.next();
4954                if (resultsAction != null && resultsAction.equals(action)) {
4955                    // If this action was explicitly requested, then don't
4956                    // remove things that have it.
4957                    continue;
4958                }
4959                for (int j=i+1; j<N; j++) {
4960                    final ResolveInfo rij = results.get(j);
4961                    if (rij.filter != null && rij.filter.hasAction(action)) {
4962                        results.remove(j);
4963                        if (DEBUG_INTENT_MATCHING) Log.v(
4964                            TAG, "Removing duplicate item from " + j
4965                            + " due to action " + action + " at " + i);
4966                        j--;
4967                        N--;
4968                    }
4969                }
4970            }
4971
4972            // If the caller didn't request filter information, drop it now
4973            // so we don't have to marshall/unmarshall it.
4974            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4975                rii.filter = null;
4976            }
4977        }
4978
4979        // Filter out the caller activity if so requested.
4980        if (caller != null) {
4981            N = results.size();
4982            for (int i=0; i<N; i++) {
4983                ActivityInfo ainfo = results.get(i).activityInfo;
4984                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4985                        && caller.getClassName().equals(ainfo.name)) {
4986                    results.remove(i);
4987                    break;
4988                }
4989            }
4990        }
4991
4992        // If the caller didn't request filter information,
4993        // drop them now so we don't have to
4994        // marshall/unmarshall it.
4995        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4996            N = results.size();
4997            for (int i=0; i<N; i++) {
4998                results.get(i).filter = null;
4999            }
5000        }
5001
5002        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5003        return results;
5004    }
5005
5006    @Override
5007    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5008            int userId) {
5009        if (!sUserManager.exists(userId)) return Collections.emptyList();
5010        ComponentName comp = intent.getComponent();
5011        if (comp == null) {
5012            if (intent.getSelector() != null) {
5013                intent = intent.getSelector();
5014                comp = intent.getComponent();
5015            }
5016        }
5017        if (comp != null) {
5018            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5019            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5020            if (ai != null) {
5021                ResolveInfo ri = new ResolveInfo();
5022                ri.activityInfo = ai;
5023                list.add(ri);
5024            }
5025            return list;
5026        }
5027
5028        // reader
5029        synchronized (mPackages) {
5030            String pkgName = intent.getPackage();
5031            if (pkgName == null) {
5032                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5033            }
5034            final PackageParser.Package pkg = mPackages.get(pkgName);
5035            if (pkg != null) {
5036                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5037                        userId);
5038            }
5039            return null;
5040        }
5041    }
5042
5043    @Override
5044    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5045        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5046        if (!sUserManager.exists(userId)) return null;
5047        if (query != null) {
5048            if (query.size() >= 1) {
5049                // If there is more than one service with the same priority,
5050                // just arbitrarily pick the first one.
5051                return query.get(0);
5052            }
5053        }
5054        return null;
5055    }
5056
5057    @Override
5058    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5059            int userId) {
5060        if (!sUserManager.exists(userId)) return Collections.emptyList();
5061        ComponentName comp = intent.getComponent();
5062        if (comp == null) {
5063            if (intent.getSelector() != null) {
5064                intent = intent.getSelector();
5065                comp = intent.getComponent();
5066            }
5067        }
5068        if (comp != null) {
5069            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5070            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5071            if (si != null) {
5072                final ResolveInfo ri = new ResolveInfo();
5073                ri.serviceInfo = si;
5074                list.add(ri);
5075            }
5076            return list;
5077        }
5078
5079        // reader
5080        synchronized (mPackages) {
5081            String pkgName = intent.getPackage();
5082            if (pkgName == null) {
5083                return mServices.queryIntent(intent, resolvedType, flags, userId);
5084            }
5085            final PackageParser.Package pkg = mPackages.get(pkgName);
5086            if (pkg != null) {
5087                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5088                        userId);
5089            }
5090            return null;
5091        }
5092    }
5093
5094    @Override
5095    public List<ResolveInfo> queryIntentContentProviders(
5096            Intent intent, String resolvedType, int flags, int userId) {
5097        if (!sUserManager.exists(userId)) return Collections.emptyList();
5098        ComponentName comp = intent.getComponent();
5099        if (comp == null) {
5100            if (intent.getSelector() != null) {
5101                intent = intent.getSelector();
5102                comp = intent.getComponent();
5103            }
5104        }
5105        if (comp != null) {
5106            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5107            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5108            if (pi != null) {
5109                final ResolveInfo ri = new ResolveInfo();
5110                ri.providerInfo = pi;
5111                list.add(ri);
5112            }
5113            return list;
5114        }
5115
5116        // reader
5117        synchronized (mPackages) {
5118            String pkgName = intent.getPackage();
5119            if (pkgName == null) {
5120                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5121            }
5122            final PackageParser.Package pkg = mPackages.get(pkgName);
5123            if (pkg != null) {
5124                return mProviders.queryIntentForPackage(
5125                        intent, resolvedType, flags, pkg.providers, userId);
5126            }
5127            return null;
5128        }
5129    }
5130
5131    @Override
5132    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5133        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5134
5135        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5136
5137        // writer
5138        synchronized (mPackages) {
5139            ArrayList<PackageInfo> list;
5140            if (listUninstalled) {
5141                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5142                for (PackageSetting ps : mSettings.mPackages.values()) {
5143                    PackageInfo pi;
5144                    if (ps.pkg != null) {
5145                        pi = generatePackageInfo(ps.pkg, flags, userId);
5146                    } else {
5147                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5148                    }
5149                    if (pi != null) {
5150                        list.add(pi);
5151                    }
5152                }
5153            } else {
5154                list = new ArrayList<PackageInfo>(mPackages.size());
5155                for (PackageParser.Package p : mPackages.values()) {
5156                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5157                    if (pi != null) {
5158                        list.add(pi);
5159                    }
5160                }
5161            }
5162
5163            return new ParceledListSlice<PackageInfo>(list);
5164        }
5165    }
5166
5167    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5168            String[] permissions, boolean[] tmp, int flags, int userId) {
5169        int numMatch = 0;
5170        final PermissionsState permissionsState = ps.getPermissionsState();
5171        for (int i=0; i<permissions.length; i++) {
5172            final String permission = permissions[i];
5173            if (permissionsState.hasPermission(permission, userId)) {
5174                tmp[i] = true;
5175                numMatch++;
5176            } else {
5177                tmp[i] = false;
5178            }
5179        }
5180        if (numMatch == 0) {
5181            return;
5182        }
5183        PackageInfo pi;
5184        if (ps.pkg != null) {
5185            pi = generatePackageInfo(ps.pkg, flags, userId);
5186        } else {
5187            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5188        }
5189        // The above might return null in cases of uninstalled apps or install-state
5190        // skew across users/profiles.
5191        if (pi != null) {
5192            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5193                if (numMatch == permissions.length) {
5194                    pi.requestedPermissions = permissions;
5195                } else {
5196                    pi.requestedPermissions = new String[numMatch];
5197                    numMatch = 0;
5198                    for (int i=0; i<permissions.length; i++) {
5199                        if (tmp[i]) {
5200                            pi.requestedPermissions[numMatch] = permissions[i];
5201                            numMatch++;
5202                        }
5203                    }
5204                }
5205            }
5206            list.add(pi);
5207        }
5208    }
5209
5210    @Override
5211    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5212            String[] permissions, int flags, int userId) {
5213        if (!sUserManager.exists(userId)) return null;
5214        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5215
5216        // writer
5217        synchronized (mPackages) {
5218            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5219            boolean[] tmpBools = new boolean[permissions.length];
5220            if (listUninstalled) {
5221                for (PackageSetting ps : mSettings.mPackages.values()) {
5222                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5223                }
5224            } else {
5225                for (PackageParser.Package pkg : mPackages.values()) {
5226                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5227                    if (ps != null) {
5228                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5229                                userId);
5230                    }
5231                }
5232            }
5233
5234            return new ParceledListSlice<PackageInfo>(list);
5235        }
5236    }
5237
5238    @Override
5239    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5240        if (!sUserManager.exists(userId)) return null;
5241        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5242
5243        // writer
5244        synchronized (mPackages) {
5245            ArrayList<ApplicationInfo> list;
5246            if (listUninstalled) {
5247                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5248                for (PackageSetting ps : mSettings.mPackages.values()) {
5249                    ApplicationInfo ai;
5250                    if (ps.pkg != null) {
5251                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5252                                ps.readUserState(userId), userId);
5253                    } else {
5254                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5255                    }
5256                    if (ai != null) {
5257                        list.add(ai);
5258                    }
5259                }
5260            } else {
5261                list = new ArrayList<ApplicationInfo>(mPackages.size());
5262                for (PackageParser.Package p : mPackages.values()) {
5263                    if (p.mExtras != null) {
5264                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5265                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5266                        if (ai != null) {
5267                            list.add(ai);
5268                        }
5269                    }
5270                }
5271            }
5272
5273            return new ParceledListSlice<ApplicationInfo>(list);
5274        }
5275    }
5276
5277    public List<ApplicationInfo> getPersistentApplications(int flags) {
5278        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5279
5280        // reader
5281        synchronized (mPackages) {
5282            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5283            final int userId = UserHandle.getCallingUserId();
5284            while (i.hasNext()) {
5285                final PackageParser.Package p = i.next();
5286                if (p.applicationInfo != null
5287                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5288                        && (!mSafeMode || isSystemApp(p))) {
5289                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5290                    if (ps != null) {
5291                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5292                                ps.readUserState(userId), userId);
5293                        if (ai != null) {
5294                            finalList.add(ai);
5295                        }
5296                    }
5297                }
5298            }
5299        }
5300
5301        return finalList;
5302    }
5303
5304    @Override
5305    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5306        if (!sUserManager.exists(userId)) return null;
5307        // reader
5308        synchronized (mPackages) {
5309            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5310            PackageSetting ps = provider != null
5311                    ? mSettings.mPackages.get(provider.owner.packageName)
5312                    : null;
5313            return ps != null
5314                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5315                    && (!mSafeMode || (provider.info.applicationInfo.flags
5316                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5317                    ? PackageParser.generateProviderInfo(provider, flags,
5318                            ps.readUserState(userId), userId)
5319                    : null;
5320        }
5321    }
5322
5323    /**
5324     * @deprecated
5325     */
5326    @Deprecated
5327    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5328        // reader
5329        synchronized (mPackages) {
5330            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5331                    .entrySet().iterator();
5332            final int userId = UserHandle.getCallingUserId();
5333            while (i.hasNext()) {
5334                Map.Entry<String, PackageParser.Provider> entry = i.next();
5335                PackageParser.Provider p = entry.getValue();
5336                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5337
5338                if (ps != null && p.syncable
5339                        && (!mSafeMode || (p.info.applicationInfo.flags
5340                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5341                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5342                            ps.readUserState(userId), userId);
5343                    if (info != null) {
5344                        outNames.add(entry.getKey());
5345                        outInfo.add(info);
5346                    }
5347                }
5348            }
5349        }
5350    }
5351
5352    @Override
5353    public List<ProviderInfo> queryContentProviders(String processName,
5354            int uid, int flags) {
5355        ArrayList<ProviderInfo> finalList = null;
5356        // reader
5357        synchronized (mPackages) {
5358            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5359            final int userId = processName != null ?
5360                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5361            while (i.hasNext()) {
5362                final PackageParser.Provider p = i.next();
5363                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5364                if (ps != null && p.info.authority != null
5365                        && (processName == null
5366                                || (p.info.processName.equals(processName)
5367                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5368                        && mSettings.isEnabledLPr(p.info, flags, userId)
5369                        && (!mSafeMode
5370                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5371                    if (finalList == null) {
5372                        finalList = new ArrayList<ProviderInfo>(3);
5373                    }
5374                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5375                            ps.readUserState(userId), userId);
5376                    if (info != null) {
5377                        finalList.add(info);
5378                    }
5379                }
5380            }
5381        }
5382
5383        if (finalList != null) {
5384            Collections.sort(finalList, mProviderInitOrderSorter);
5385        }
5386
5387        return finalList;
5388    }
5389
5390    @Override
5391    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5392            int flags) {
5393        // reader
5394        synchronized (mPackages) {
5395            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5396            return PackageParser.generateInstrumentationInfo(i, flags);
5397        }
5398    }
5399
5400    @Override
5401    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5402            int flags) {
5403        ArrayList<InstrumentationInfo> finalList =
5404            new ArrayList<InstrumentationInfo>();
5405
5406        // reader
5407        synchronized (mPackages) {
5408            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5409            while (i.hasNext()) {
5410                final PackageParser.Instrumentation p = i.next();
5411                if (targetPackage == null
5412                        || targetPackage.equals(p.info.targetPackage)) {
5413                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5414                            flags);
5415                    if (ii != null) {
5416                        finalList.add(ii);
5417                    }
5418                }
5419            }
5420        }
5421
5422        return finalList;
5423    }
5424
5425    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5426        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5427        if (overlays == null) {
5428            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5429            return;
5430        }
5431        for (PackageParser.Package opkg : overlays.values()) {
5432            // Not much to do if idmap fails: we already logged the error
5433            // and we certainly don't want to abort installation of pkg simply
5434            // because an overlay didn't fit properly. For these reasons,
5435            // ignore the return value of createIdmapForPackagePairLI.
5436            createIdmapForPackagePairLI(pkg, opkg);
5437        }
5438    }
5439
5440    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5441            PackageParser.Package opkg) {
5442        if (!opkg.mTrustedOverlay) {
5443            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5444                    opkg.baseCodePath + ": overlay not trusted");
5445            return false;
5446        }
5447        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5448        if (overlaySet == null) {
5449            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5450                    opkg.baseCodePath + " but target package has no known overlays");
5451            return false;
5452        }
5453        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5454        // TODO: generate idmap for split APKs
5455        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5456            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5457                    + opkg.baseCodePath);
5458            return false;
5459        }
5460        PackageParser.Package[] overlayArray =
5461            overlaySet.values().toArray(new PackageParser.Package[0]);
5462        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5463            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5464                return p1.mOverlayPriority - p2.mOverlayPriority;
5465            }
5466        };
5467        Arrays.sort(overlayArray, cmp);
5468
5469        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5470        int i = 0;
5471        for (PackageParser.Package p : overlayArray) {
5472            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5473        }
5474        return true;
5475    }
5476
5477    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5478        final File[] files = dir.listFiles();
5479        if (ArrayUtils.isEmpty(files)) {
5480            Log.d(TAG, "No files in app dir " + dir);
5481            return;
5482        }
5483
5484        if (DEBUG_PACKAGE_SCANNING) {
5485            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5486                    + " flags=0x" + Integer.toHexString(parseFlags));
5487        }
5488
5489        for (File file : files) {
5490            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5491                    && !PackageInstallerService.isStageName(file.getName());
5492            if (!isPackage) {
5493                // Ignore entries which are not packages
5494                continue;
5495            }
5496            try {
5497                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5498                        scanFlags, currentTime, null);
5499            } catch (PackageManagerException e) {
5500                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5501
5502                // Delete invalid userdata apps
5503                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5504                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5505                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5506                    if (file.isDirectory()) {
5507                        mInstaller.rmPackageDir(file.getAbsolutePath());
5508                    } else {
5509                        file.delete();
5510                    }
5511                }
5512            }
5513        }
5514    }
5515
5516    private static File getSettingsProblemFile() {
5517        File dataDir = Environment.getDataDirectory();
5518        File systemDir = new File(dataDir, "system");
5519        File fname = new File(systemDir, "uiderrors.txt");
5520        return fname;
5521    }
5522
5523    static void reportSettingsProblem(int priority, String msg) {
5524        logCriticalInfo(priority, msg);
5525    }
5526
5527    static void logCriticalInfo(int priority, String msg) {
5528        Slog.println(priority, TAG, msg);
5529        EventLogTags.writePmCriticalInfo(msg);
5530        try {
5531            File fname = getSettingsProblemFile();
5532            FileOutputStream out = new FileOutputStream(fname, true);
5533            PrintWriter pw = new FastPrintWriter(out);
5534            SimpleDateFormat formatter = new SimpleDateFormat();
5535            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5536            pw.println(dateString + ": " + msg);
5537            pw.close();
5538            FileUtils.setPermissions(
5539                    fname.toString(),
5540                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5541                    -1, -1);
5542        } catch (java.io.IOException e) {
5543        }
5544    }
5545
5546    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5547            PackageParser.Package pkg, File srcFile, int parseFlags)
5548            throws PackageManagerException {
5549        if (ps != null
5550                && ps.codePath.equals(srcFile)
5551                && ps.timeStamp == srcFile.lastModified()
5552                && !isCompatSignatureUpdateNeeded(pkg)
5553                && !isRecoverSignatureUpdateNeeded(pkg)) {
5554            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5555            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5556            ArraySet<PublicKey> signingKs;
5557            synchronized (mPackages) {
5558                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5559            }
5560            if (ps.signatures.mSignatures != null
5561                    && ps.signatures.mSignatures.length != 0
5562                    && signingKs != null) {
5563                // Optimization: reuse the existing cached certificates
5564                // if the package appears to be unchanged.
5565                pkg.mSignatures = ps.signatures.mSignatures;
5566                pkg.mSigningKeys = signingKs;
5567                return;
5568            }
5569
5570            Slog.w(TAG, "PackageSetting for " + ps.name
5571                    + " is missing signatures.  Collecting certs again to recover them.");
5572        } else {
5573            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5574        }
5575
5576        try {
5577            pp.collectCertificates(pkg, parseFlags);
5578            pp.collectManifestDigest(pkg);
5579        } catch (PackageParserException e) {
5580            throw PackageManagerException.from(e);
5581        }
5582    }
5583
5584    /*
5585     *  Scan a package and return the newly parsed package.
5586     *  Returns null in case of errors and the error code is stored in mLastScanError
5587     */
5588    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5589            long currentTime, UserHandle user) throws PackageManagerException {
5590        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5591        parseFlags |= mDefParseFlags;
5592        PackageParser pp = new PackageParser();
5593        pp.setSeparateProcesses(mSeparateProcesses);
5594        pp.setOnlyCoreApps(mOnlyCore);
5595        pp.setDisplayMetrics(mMetrics);
5596
5597        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5598            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5599        }
5600
5601        final PackageParser.Package pkg;
5602        try {
5603            pkg = pp.parsePackage(scanFile, parseFlags);
5604        } catch (PackageParserException e) {
5605            throw PackageManagerException.from(e);
5606        }
5607
5608        PackageSetting ps = null;
5609        PackageSetting updatedPkg;
5610        // reader
5611        synchronized (mPackages) {
5612            // Look to see if we already know about this package.
5613            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5614            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5615                // This package has been renamed to its original name.  Let's
5616                // use that.
5617                ps = mSettings.peekPackageLPr(oldName);
5618            }
5619            // If there was no original package, see one for the real package name.
5620            if (ps == null) {
5621                ps = mSettings.peekPackageLPr(pkg.packageName);
5622            }
5623            // Check to see if this package could be hiding/updating a system
5624            // package.  Must look for it either under the original or real
5625            // package name depending on our state.
5626            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5627            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5628        }
5629        boolean updatedPkgBetter = false;
5630        // First check if this is a system package that may involve an update
5631        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5632            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5633            // it needs to drop FLAG_PRIVILEGED.
5634            if (locationIsPrivileged(scanFile)) {
5635                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5636            } else {
5637                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5638            }
5639
5640            if (ps != null && !ps.codePath.equals(scanFile)) {
5641                // The path has changed from what was last scanned...  check the
5642                // version of the new path against what we have stored to determine
5643                // what to do.
5644                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5645                if (pkg.mVersionCode <= ps.versionCode) {
5646                    // The system package has been updated and the code path does not match
5647                    // Ignore entry. Skip it.
5648                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5649                            + " ignored: updated version " + ps.versionCode
5650                            + " better than this " + pkg.mVersionCode);
5651                    if (!updatedPkg.codePath.equals(scanFile)) {
5652                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5653                                + ps.name + " changing from " + updatedPkg.codePathString
5654                                + " to " + scanFile);
5655                        updatedPkg.codePath = scanFile;
5656                        updatedPkg.codePathString = scanFile.toString();
5657                        updatedPkg.resourcePath = scanFile;
5658                        updatedPkg.resourcePathString = scanFile.toString();
5659                    }
5660                    updatedPkg.pkg = pkg;
5661                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5662                } else {
5663                    // The current app on the system partition is better than
5664                    // what we have updated to on the data partition; switch
5665                    // back to the system partition version.
5666                    // At this point, its safely assumed that package installation for
5667                    // apps in system partition will go through. If not there won't be a working
5668                    // version of the app
5669                    // writer
5670                    synchronized (mPackages) {
5671                        // Just remove the loaded entries from package lists.
5672                        mPackages.remove(ps.name);
5673                    }
5674
5675                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5676                            + " reverting from " + ps.codePathString
5677                            + ": new version " + pkg.mVersionCode
5678                            + " better than installed " + ps.versionCode);
5679
5680                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5681                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5682                    synchronized (mInstallLock) {
5683                        args.cleanUpResourcesLI();
5684                    }
5685                    synchronized (mPackages) {
5686                        mSettings.enableSystemPackageLPw(ps.name);
5687                    }
5688                    updatedPkgBetter = true;
5689                }
5690            }
5691        }
5692
5693        if (updatedPkg != null) {
5694            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5695            // initially
5696            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5697
5698            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5699            // flag set initially
5700            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5701                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5702            }
5703        }
5704
5705        // Verify certificates against what was last scanned
5706        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5707
5708        /*
5709         * A new system app appeared, but we already had a non-system one of the
5710         * same name installed earlier.
5711         */
5712        boolean shouldHideSystemApp = false;
5713        if (updatedPkg == null && ps != null
5714                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5715            /*
5716             * Check to make sure the signatures match first. If they don't,
5717             * wipe the installed application and its data.
5718             */
5719            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5720                    != PackageManager.SIGNATURE_MATCH) {
5721                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5722                        + " signatures don't match existing userdata copy; removing");
5723                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5724                ps = null;
5725            } else {
5726                /*
5727                 * If the newly-added system app is an older version than the
5728                 * already installed version, hide it. It will be scanned later
5729                 * and re-added like an update.
5730                 */
5731                if (pkg.mVersionCode <= ps.versionCode) {
5732                    shouldHideSystemApp = true;
5733                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5734                            + " but new version " + pkg.mVersionCode + " better than installed "
5735                            + ps.versionCode + "; hiding system");
5736                } else {
5737                    /*
5738                     * The newly found system app is a newer version that the
5739                     * one previously installed. Simply remove the
5740                     * already-installed application and replace it with our own
5741                     * while keeping the application data.
5742                     */
5743                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5744                            + " reverting from " + ps.codePathString + ": new version "
5745                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5746                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5747                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5748                    synchronized (mInstallLock) {
5749                        args.cleanUpResourcesLI();
5750                    }
5751                }
5752            }
5753        }
5754
5755        // The apk is forward locked (not public) if its code and resources
5756        // are kept in different files. (except for app in either system or
5757        // vendor path).
5758        // TODO grab this value from PackageSettings
5759        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5760            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5761                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5762            }
5763        }
5764
5765        // TODO: extend to support forward-locked splits
5766        String resourcePath = null;
5767        String baseResourcePath = null;
5768        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5769            if (ps != null && ps.resourcePathString != null) {
5770                resourcePath = ps.resourcePathString;
5771                baseResourcePath = ps.resourcePathString;
5772            } else {
5773                // Should not happen at all. Just log an error.
5774                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5775            }
5776        } else {
5777            resourcePath = pkg.codePath;
5778            baseResourcePath = pkg.baseCodePath;
5779        }
5780
5781        // Set application objects path explicitly.
5782        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5783        pkg.applicationInfo.setCodePath(pkg.codePath);
5784        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5785        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5786        pkg.applicationInfo.setResourcePath(resourcePath);
5787        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5788        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5789
5790        // Note that we invoke the following method only if we are about to unpack an application
5791        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5792                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5793
5794        /*
5795         * If the system app should be overridden by a previously installed
5796         * data, hide the system app now and let the /data/app scan pick it up
5797         * again.
5798         */
5799        if (shouldHideSystemApp) {
5800            synchronized (mPackages) {
5801                /*
5802                 * We have to grant systems permissions before we hide, because
5803                 * grantPermissions will assume the package update is trying to
5804                 * expand its permissions.
5805                 */
5806                grantPermissionsLPw(pkg, true, pkg.packageName);
5807                mSettings.disableSystemPackageLPw(pkg.packageName);
5808            }
5809        }
5810
5811        return scannedPkg;
5812    }
5813
5814    private static String fixProcessName(String defProcessName,
5815            String processName, int uid) {
5816        if (processName == null) {
5817            return defProcessName;
5818        }
5819        return processName;
5820    }
5821
5822    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5823            throws PackageManagerException {
5824        if (pkgSetting.signatures.mSignatures != null) {
5825            // Already existing package. Make sure signatures match
5826            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5827                    == PackageManager.SIGNATURE_MATCH;
5828            if (!match) {
5829                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5830                        == PackageManager.SIGNATURE_MATCH;
5831            }
5832            if (!match) {
5833                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5834                        == PackageManager.SIGNATURE_MATCH;
5835            }
5836            if (!match) {
5837                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5838                        + pkg.packageName + " signatures do not match the "
5839                        + "previously installed version; ignoring!");
5840            }
5841        }
5842
5843        // Check for shared user signatures
5844        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5845            // Already existing package. Make sure signatures match
5846            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5847                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5848            if (!match) {
5849                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5850                        == PackageManager.SIGNATURE_MATCH;
5851            }
5852            if (!match) {
5853                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5854                        == PackageManager.SIGNATURE_MATCH;
5855            }
5856            if (!match) {
5857                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5858                        "Package " + pkg.packageName
5859                        + " has no signatures that match those in shared user "
5860                        + pkgSetting.sharedUser.name + "; ignoring!");
5861            }
5862        }
5863    }
5864
5865    /**
5866     * Enforces that only the system UID or root's UID can call a method exposed
5867     * via Binder.
5868     *
5869     * @param message used as message if SecurityException is thrown
5870     * @throws SecurityException if the caller is not system or root
5871     */
5872    private static final void enforceSystemOrRoot(String message) {
5873        final int uid = Binder.getCallingUid();
5874        if (uid != Process.SYSTEM_UID && uid != 0) {
5875            throw new SecurityException(message);
5876        }
5877    }
5878
5879    @Override
5880    public void performBootDexOpt() {
5881        enforceSystemOrRoot("Only the system can request dexopt be performed");
5882
5883        // Before everything else, see whether we need to fstrim.
5884        try {
5885            IMountService ms = PackageHelper.getMountService();
5886            if (ms != null) {
5887                final boolean isUpgrade = isUpgrade();
5888                boolean doTrim = isUpgrade;
5889                if (doTrim) {
5890                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5891                } else {
5892                    final long interval = android.provider.Settings.Global.getLong(
5893                            mContext.getContentResolver(),
5894                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5895                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5896                    if (interval > 0) {
5897                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5898                        if (timeSinceLast > interval) {
5899                            doTrim = true;
5900                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5901                                    + "; running immediately");
5902                        }
5903                    }
5904                }
5905                if (doTrim) {
5906                    if (!isFirstBoot()) {
5907                        try {
5908                            ActivityManagerNative.getDefault().showBootMessage(
5909                                    mContext.getResources().getString(
5910                                            R.string.android_upgrading_fstrim), true);
5911                        } catch (RemoteException e) {
5912                        }
5913                    }
5914                    ms.runMaintenance();
5915                }
5916            } else {
5917                Slog.e(TAG, "Mount service unavailable!");
5918            }
5919        } catch (RemoteException e) {
5920            // Can't happen; MountService is local
5921        }
5922
5923        final ArraySet<PackageParser.Package> pkgs;
5924        synchronized (mPackages) {
5925            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5926        }
5927
5928        if (pkgs != null) {
5929            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5930            // in case the device runs out of space.
5931            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5932            // Give priority to core apps.
5933            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5934                PackageParser.Package pkg = it.next();
5935                if (pkg.coreApp) {
5936                    if (DEBUG_DEXOPT) {
5937                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5938                    }
5939                    sortedPkgs.add(pkg);
5940                    it.remove();
5941                }
5942            }
5943            // Give priority to system apps that listen for pre boot complete.
5944            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5945            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5946            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5947                PackageParser.Package pkg = it.next();
5948                if (pkgNames.contains(pkg.packageName)) {
5949                    if (DEBUG_DEXOPT) {
5950                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5951                    }
5952                    sortedPkgs.add(pkg);
5953                    it.remove();
5954                }
5955            }
5956            // Give priority to system apps.
5957            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5958                PackageParser.Package pkg = it.next();
5959                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5960                    if (DEBUG_DEXOPT) {
5961                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5962                    }
5963                    sortedPkgs.add(pkg);
5964                    it.remove();
5965                }
5966            }
5967            // Give priority to updated system apps.
5968            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5969                PackageParser.Package pkg = it.next();
5970                if (pkg.isUpdatedSystemApp()) {
5971                    if (DEBUG_DEXOPT) {
5972                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5973                    }
5974                    sortedPkgs.add(pkg);
5975                    it.remove();
5976                }
5977            }
5978            // Give priority to apps that listen for boot complete.
5979            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5980            pkgNames = getPackageNamesForIntent(intent);
5981            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5982                PackageParser.Package pkg = it.next();
5983                if (pkgNames.contains(pkg.packageName)) {
5984                    if (DEBUG_DEXOPT) {
5985                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5986                    }
5987                    sortedPkgs.add(pkg);
5988                    it.remove();
5989                }
5990            }
5991            // Filter out packages that aren't recently used.
5992            filterRecentlyUsedApps(pkgs);
5993            // Add all remaining apps.
5994            for (PackageParser.Package pkg : pkgs) {
5995                if (DEBUG_DEXOPT) {
5996                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5997                }
5998                sortedPkgs.add(pkg);
5999            }
6000
6001            // If we want to be lazy, filter everything that wasn't recently used.
6002            if (mLazyDexOpt) {
6003                filterRecentlyUsedApps(sortedPkgs);
6004            }
6005
6006            int i = 0;
6007            int total = sortedPkgs.size();
6008            File dataDir = Environment.getDataDirectory();
6009            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6010            if (lowThreshold == 0) {
6011                throw new IllegalStateException("Invalid low memory threshold");
6012            }
6013            for (PackageParser.Package pkg : sortedPkgs) {
6014                long usableSpace = dataDir.getUsableSpace();
6015                if (usableSpace < lowThreshold) {
6016                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6017                    break;
6018                }
6019                performBootDexOpt(pkg, ++i, total);
6020            }
6021        }
6022    }
6023
6024    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6025        // Filter out packages that aren't recently used.
6026        //
6027        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6028        // should do a full dexopt.
6029        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6030            int total = pkgs.size();
6031            int skipped = 0;
6032            long now = System.currentTimeMillis();
6033            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6034                PackageParser.Package pkg = i.next();
6035                long then = pkg.mLastPackageUsageTimeInMills;
6036                if (then + mDexOptLRUThresholdInMills < now) {
6037                    if (DEBUG_DEXOPT) {
6038                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6039                              ((then == 0) ? "never" : new Date(then)));
6040                    }
6041                    i.remove();
6042                    skipped++;
6043                }
6044            }
6045            if (DEBUG_DEXOPT) {
6046                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6047            }
6048        }
6049    }
6050
6051    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6052        List<ResolveInfo> ris = null;
6053        try {
6054            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6055                    intent, null, 0, UserHandle.USER_OWNER);
6056        } catch (RemoteException e) {
6057        }
6058        ArraySet<String> pkgNames = new ArraySet<String>();
6059        if (ris != null) {
6060            for (ResolveInfo ri : ris) {
6061                pkgNames.add(ri.activityInfo.packageName);
6062            }
6063        }
6064        return pkgNames;
6065    }
6066
6067    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6068        if (DEBUG_DEXOPT) {
6069            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6070        }
6071        if (!isFirstBoot()) {
6072            try {
6073                ActivityManagerNative.getDefault().showBootMessage(
6074                        mContext.getResources().getString(R.string.android_upgrading_apk,
6075                                curr, total), true);
6076            } catch (RemoteException e) {
6077            }
6078        }
6079        PackageParser.Package p = pkg;
6080        synchronized (mInstallLock) {
6081            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6082                    false /* force dex */, false /* defer */, true /* include dependencies */);
6083        }
6084    }
6085
6086    @Override
6087    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6088        return performDexOpt(packageName, instructionSet, false);
6089    }
6090
6091    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6092        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6093        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6094        if (!dexopt && !updateUsage) {
6095            // We aren't going to dexopt or update usage, so bail early.
6096            return false;
6097        }
6098        PackageParser.Package p;
6099        final String targetInstructionSet;
6100        synchronized (mPackages) {
6101            p = mPackages.get(packageName);
6102            if (p == null) {
6103                return false;
6104            }
6105            if (updateUsage) {
6106                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6107            }
6108            mPackageUsage.write(false);
6109            if (!dexopt) {
6110                // We aren't going to dexopt, so bail early.
6111                return false;
6112            }
6113
6114            targetInstructionSet = instructionSet != null ? instructionSet :
6115                    getPrimaryInstructionSet(p.applicationInfo);
6116            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6117                return false;
6118            }
6119        }
6120
6121        synchronized (mInstallLock) {
6122            final String[] instructionSets = new String[] { targetInstructionSet };
6123            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6124                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6125            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6126        }
6127    }
6128
6129    public ArraySet<String> getPackagesThatNeedDexOpt() {
6130        ArraySet<String> pkgs = null;
6131        synchronized (mPackages) {
6132            for (PackageParser.Package p : mPackages.values()) {
6133                if (DEBUG_DEXOPT) {
6134                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6135                }
6136                if (!p.mDexOptPerformed.isEmpty()) {
6137                    continue;
6138                }
6139                if (pkgs == null) {
6140                    pkgs = new ArraySet<String>();
6141                }
6142                pkgs.add(p.packageName);
6143            }
6144        }
6145        return pkgs;
6146    }
6147
6148    public void shutdown() {
6149        mPackageUsage.write(true);
6150    }
6151
6152    @Override
6153    public void forceDexOpt(String packageName) {
6154        enforceSystemOrRoot("forceDexOpt");
6155
6156        PackageParser.Package pkg;
6157        synchronized (mPackages) {
6158            pkg = mPackages.get(packageName);
6159            if (pkg == null) {
6160                throw new IllegalArgumentException("Missing package: " + packageName);
6161            }
6162        }
6163
6164        synchronized (mInstallLock) {
6165            final String[] instructionSets = new String[] {
6166                    getPrimaryInstructionSet(pkg.applicationInfo) };
6167            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6168                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6169            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6170                throw new IllegalStateException("Failed to dexopt: " + res);
6171            }
6172        }
6173    }
6174
6175    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6176        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6177            Slog.w(TAG, "Unable to update from " + oldPkg.name
6178                    + " to " + newPkg.packageName
6179                    + ": old package not in system partition");
6180            return false;
6181        } else if (mPackages.get(oldPkg.name) != null) {
6182            Slog.w(TAG, "Unable to update from " + oldPkg.name
6183                    + " to " + newPkg.packageName
6184                    + ": old package still exists");
6185            return false;
6186        }
6187        return true;
6188    }
6189
6190    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6191        int[] users = sUserManager.getUserIds();
6192        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6193        if (res < 0) {
6194            return res;
6195        }
6196        for (int user : users) {
6197            if (user != 0) {
6198                res = mInstaller.createUserData(volumeUuid, packageName,
6199                        UserHandle.getUid(user, uid), user, seinfo);
6200                if (res < 0) {
6201                    return res;
6202                }
6203            }
6204        }
6205        return res;
6206    }
6207
6208    private int removeDataDirsLI(String volumeUuid, String packageName) {
6209        int[] users = sUserManager.getUserIds();
6210        int res = 0;
6211        for (int user : users) {
6212            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6213            if (resInner < 0) {
6214                res = resInner;
6215            }
6216        }
6217
6218        return res;
6219    }
6220
6221    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6222        int[] users = sUserManager.getUserIds();
6223        int res = 0;
6224        for (int user : users) {
6225            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6226            if (resInner < 0) {
6227                res = resInner;
6228            }
6229        }
6230        return res;
6231    }
6232
6233    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6234            PackageParser.Package changingLib) {
6235        if (file.path != null) {
6236            usesLibraryFiles.add(file.path);
6237            return;
6238        }
6239        PackageParser.Package p = mPackages.get(file.apk);
6240        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6241            // If we are doing this while in the middle of updating a library apk,
6242            // then we need to make sure to use that new apk for determining the
6243            // dependencies here.  (We haven't yet finished committing the new apk
6244            // to the package manager state.)
6245            if (p == null || p.packageName.equals(changingLib.packageName)) {
6246                p = changingLib;
6247            }
6248        }
6249        if (p != null) {
6250            usesLibraryFiles.addAll(p.getAllCodePaths());
6251        }
6252    }
6253
6254    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6255            PackageParser.Package changingLib) throws PackageManagerException {
6256        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6257            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6258            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6259            for (int i=0; i<N; i++) {
6260                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6261                if (file == null) {
6262                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6263                            "Package " + pkg.packageName + " requires unavailable shared library "
6264                            + pkg.usesLibraries.get(i) + "; failing!");
6265                }
6266                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6267            }
6268            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6269            for (int i=0; i<N; i++) {
6270                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6271                if (file == null) {
6272                    Slog.w(TAG, "Package " + pkg.packageName
6273                            + " desires unavailable shared library "
6274                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6275                } else {
6276                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6277                }
6278            }
6279            N = usesLibraryFiles.size();
6280            if (N > 0) {
6281                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6282            } else {
6283                pkg.usesLibraryFiles = null;
6284            }
6285        }
6286    }
6287
6288    private static boolean hasString(List<String> list, List<String> which) {
6289        if (list == null) {
6290            return false;
6291        }
6292        for (int i=list.size()-1; i>=0; i--) {
6293            for (int j=which.size()-1; j>=0; j--) {
6294                if (which.get(j).equals(list.get(i))) {
6295                    return true;
6296                }
6297            }
6298        }
6299        return false;
6300    }
6301
6302    private void updateAllSharedLibrariesLPw() {
6303        for (PackageParser.Package pkg : mPackages.values()) {
6304            try {
6305                updateSharedLibrariesLPw(pkg, null);
6306            } catch (PackageManagerException e) {
6307                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6308            }
6309        }
6310    }
6311
6312    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6313            PackageParser.Package changingPkg) {
6314        ArrayList<PackageParser.Package> res = null;
6315        for (PackageParser.Package pkg : mPackages.values()) {
6316            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6317                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6318                if (res == null) {
6319                    res = new ArrayList<PackageParser.Package>();
6320                }
6321                res.add(pkg);
6322                try {
6323                    updateSharedLibrariesLPw(pkg, changingPkg);
6324                } catch (PackageManagerException e) {
6325                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6326                }
6327            }
6328        }
6329        return res;
6330    }
6331
6332    /**
6333     * Derive the value of the {@code cpuAbiOverride} based on the provided
6334     * value and an optional stored value from the package settings.
6335     */
6336    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6337        String cpuAbiOverride = null;
6338
6339        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6340            cpuAbiOverride = null;
6341        } else if (abiOverride != null) {
6342            cpuAbiOverride = abiOverride;
6343        } else if (settings != null) {
6344            cpuAbiOverride = settings.cpuAbiOverrideString;
6345        }
6346
6347        return cpuAbiOverride;
6348    }
6349
6350    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6351            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6352        boolean success = false;
6353        try {
6354            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6355                    currentTime, user);
6356            success = true;
6357            return res;
6358        } finally {
6359            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6360                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6361            }
6362        }
6363    }
6364
6365    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6366            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6367        final File scanFile = new File(pkg.codePath);
6368        if (pkg.applicationInfo.getCodePath() == null ||
6369                pkg.applicationInfo.getResourcePath() == null) {
6370            // Bail out. The resource and code paths haven't been set.
6371            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6372                    "Code and resource paths haven't been set correctly");
6373        }
6374
6375        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6376            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6377        } else {
6378            // Only allow system apps to be flagged as core apps.
6379            pkg.coreApp = false;
6380        }
6381
6382        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6383            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6384        }
6385
6386        if (mCustomResolverComponentName != null &&
6387                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6388            setUpCustomResolverActivity(pkg);
6389        }
6390
6391        if (pkg.packageName.equals("android")) {
6392            synchronized (mPackages) {
6393                if (mAndroidApplication != null) {
6394                    Slog.w(TAG, "*************************************************");
6395                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6396                    Slog.w(TAG, " file=" + scanFile);
6397                    Slog.w(TAG, "*************************************************");
6398                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6399                            "Core android package being redefined.  Skipping.");
6400                }
6401
6402                // Set up information for our fall-back user intent resolution activity.
6403                mPlatformPackage = pkg;
6404                pkg.mVersionCode = mSdkVersion;
6405                mAndroidApplication = pkg.applicationInfo;
6406
6407                if (!mResolverReplaced) {
6408                    mResolveActivity.applicationInfo = mAndroidApplication;
6409                    mResolveActivity.name = ResolverActivity.class.getName();
6410                    mResolveActivity.packageName = mAndroidApplication.packageName;
6411                    mResolveActivity.processName = "system:ui";
6412                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6413                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6414                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6415                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6416                    mResolveActivity.exported = true;
6417                    mResolveActivity.enabled = true;
6418                    mResolveInfo.activityInfo = mResolveActivity;
6419                    mResolveInfo.priority = 0;
6420                    mResolveInfo.preferredOrder = 0;
6421                    mResolveInfo.match = 0;
6422                    mResolveComponentName = new ComponentName(
6423                            mAndroidApplication.packageName, mResolveActivity.name);
6424                }
6425            }
6426        }
6427
6428        if (DEBUG_PACKAGE_SCANNING) {
6429            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6430                Log.d(TAG, "Scanning package " + pkg.packageName);
6431        }
6432
6433        if (mPackages.containsKey(pkg.packageName)
6434                || mSharedLibraries.containsKey(pkg.packageName)) {
6435            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6436                    "Application package " + pkg.packageName
6437                    + " already installed.  Skipping duplicate.");
6438        }
6439
6440        // If we're only installing presumed-existing packages, require that the
6441        // scanned APK is both already known and at the path previously established
6442        // for it.  Previously unknown packages we pick up normally, but if we have an
6443        // a priori expectation about this package's install presence, enforce it.
6444        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6445            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6446            if (known != null) {
6447                if (DEBUG_PACKAGE_SCANNING) {
6448                    Log.d(TAG, "Examining " + pkg.codePath
6449                            + " and requiring known paths " + known.codePathString
6450                            + " & " + known.resourcePathString);
6451                }
6452                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6453                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6454                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6455                            "Application package " + pkg.packageName
6456                            + " found at " + pkg.applicationInfo.getCodePath()
6457                            + " but expected at " + known.codePathString + "; ignoring.");
6458                }
6459            }
6460        }
6461
6462        // Initialize package source and resource directories
6463        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6464        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6465
6466        SharedUserSetting suid = null;
6467        PackageSetting pkgSetting = null;
6468
6469        if (!isSystemApp(pkg)) {
6470            // Only system apps can use these features.
6471            pkg.mOriginalPackages = null;
6472            pkg.mRealPackage = null;
6473            pkg.mAdoptPermissions = null;
6474        }
6475
6476        // writer
6477        synchronized (mPackages) {
6478            if (pkg.mSharedUserId != null) {
6479                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6480                if (suid == null) {
6481                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6482                            "Creating application package " + pkg.packageName
6483                            + " for shared user failed");
6484                }
6485                if (DEBUG_PACKAGE_SCANNING) {
6486                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6487                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6488                                + "): packages=" + suid.packages);
6489                }
6490            }
6491
6492            // Check if we are renaming from an original package name.
6493            PackageSetting origPackage = null;
6494            String realName = null;
6495            if (pkg.mOriginalPackages != null) {
6496                // This package may need to be renamed to a previously
6497                // installed name.  Let's check on that...
6498                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6499                if (pkg.mOriginalPackages.contains(renamed)) {
6500                    // This package had originally been installed as the
6501                    // original name, and we have already taken care of
6502                    // transitioning to the new one.  Just update the new
6503                    // one to continue using the old name.
6504                    realName = pkg.mRealPackage;
6505                    if (!pkg.packageName.equals(renamed)) {
6506                        // Callers into this function may have already taken
6507                        // care of renaming the package; only do it here if
6508                        // it is not already done.
6509                        pkg.setPackageName(renamed);
6510                    }
6511
6512                } else {
6513                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6514                        if ((origPackage = mSettings.peekPackageLPr(
6515                                pkg.mOriginalPackages.get(i))) != null) {
6516                            // We do have the package already installed under its
6517                            // original name...  should we use it?
6518                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6519                                // New package is not compatible with original.
6520                                origPackage = null;
6521                                continue;
6522                            } else if (origPackage.sharedUser != null) {
6523                                // Make sure uid is compatible between packages.
6524                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6525                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6526                                            + " to " + pkg.packageName + ": old uid "
6527                                            + origPackage.sharedUser.name
6528                                            + " differs from " + pkg.mSharedUserId);
6529                                    origPackage = null;
6530                                    continue;
6531                                }
6532                            } else {
6533                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6534                                        + pkg.packageName + " to old name " + origPackage.name);
6535                            }
6536                            break;
6537                        }
6538                    }
6539                }
6540            }
6541
6542            if (mTransferedPackages.contains(pkg.packageName)) {
6543                Slog.w(TAG, "Package " + pkg.packageName
6544                        + " was transferred to another, but its .apk remains");
6545            }
6546
6547            // Just create the setting, don't add it yet. For already existing packages
6548            // the PkgSetting exists already and doesn't have to be created.
6549            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6550                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6551                    pkg.applicationInfo.primaryCpuAbi,
6552                    pkg.applicationInfo.secondaryCpuAbi,
6553                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6554                    user, false);
6555            if (pkgSetting == null) {
6556                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6557                        "Creating application package " + pkg.packageName + " failed");
6558            }
6559
6560            if (pkgSetting.origPackage != null) {
6561                // If we are first transitioning from an original package,
6562                // fix up the new package's name now.  We need to do this after
6563                // looking up the package under its new name, so getPackageLP
6564                // can take care of fiddling things correctly.
6565                pkg.setPackageName(origPackage.name);
6566
6567                // File a report about this.
6568                String msg = "New package " + pkgSetting.realName
6569                        + " renamed to replace old package " + pkgSetting.name;
6570                reportSettingsProblem(Log.WARN, msg);
6571
6572                // Make a note of it.
6573                mTransferedPackages.add(origPackage.name);
6574
6575                // No longer need to retain this.
6576                pkgSetting.origPackage = null;
6577            }
6578
6579            if (realName != null) {
6580                // Make a note of it.
6581                mTransferedPackages.add(pkg.packageName);
6582            }
6583
6584            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6585                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6586            }
6587
6588            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6589                // Check all shared libraries and map to their actual file path.
6590                // We only do this here for apps not on a system dir, because those
6591                // are the only ones that can fail an install due to this.  We
6592                // will take care of the system apps by updating all of their
6593                // library paths after the scan is done.
6594                updateSharedLibrariesLPw(pkg, null);
6595            }
6596
6597            if (mFoundPolicyFile) {
6598                SELinuxMMAC.assignSeinfoValue(pkg);
6599            }
6600
6601            pkg.applicationInfo.uid = pkgSetting.appId;
6602            pkg.mExtras = pkgSetting;
6603            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6604                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6605                    // We just determined the app is signed correctly, so bring
6606                    // over the latest parsed certs.
6607                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6608                } else {
6609                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6610                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6611                                "Package " + pkg.packageName + " upgrade keys do not match the "
6612                                + "previously installed version");
6613                    } else {
6614                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6615                        String msg = "System package " + pkg.packageName
6616                            + " signature changed; retaining data.";
6617                        reportSettingsProblem(Log.WARN, msg);
6618                    }
6619                }
6620            } else {
6621                try {
6622                    verifySignaturesLP(pkgSetting, pkg);
6623                    // We just determined the app is signed correctly, so bring
6624                    // over the latest parsed certs.
6625                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6626                } catch (PackageManagerException e) {
6627                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6628                        throw e;
6629                    }
6630                    // The signature has changed, but this package is in the system
6631                    // image...  let's recover!
6632                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6633                    // However...  if this package is part of a shared user, but it
6634                    // doesn't match the signature of the shared user, let's fail.
6635                    // What this means is that you can't change the signatures
6636                    // associated with an overall shared user, which doesn't seem all
6637                    // that unreasonable.
6638                    if (pkgSetting.sharedUser != null) {
6639                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6640                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6641                            throw new PackageManagerException(
6642                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6643                                            "Signature mismatch for shared user : "
6644                                            + pkgSetting.sharedUser);
6645                        }
6646                    }
6647                    // File a report about this.
6648                    String msg = "System package " + pkg.packageName
6649                        + " signature changed; retaining data.";
6650                    reportSettingsProblem(Log.WARN, msg);
6651                }
6652            }
6653            // Verify that this new package doesn't have any content providers
6654            // that conflict with existing packages.  Only do this if the
6655            // package isn't already installed, since we don't want to break
6656            // things that are installed.
6657            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6658                final int N = pkg.providers.size();
6659                int i;
6660                for (i=0; i<N; i++) {
6661                    PackageParser.Provider p = pkg.providers.get(i);
6662                    if (p.info.authority != null) {
6663                        String names[] = p.info.authority.split(";");
6664                        for (int j = 0; j < names.length; j++) {
6665                            if (mProvidersByAuthority.containsKey(names[j])) {
6666                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6667                                final String otherPackageName =
6668                                        ((other != null && other.getComponentName() != null) ?
6669                                                other.getComponentName().getPackageName() : "?");
6670                                throw new PackageManagerException(
6671                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6672                                                "Can't install because provider name " + names[j]
6673                                                + " (in package " + pkg.applicationInfo.packageName
6674                                                + ") is already used by " + otherPackageName);
6675                            }
6676                        }
6677                    }
6678                }
6679            }
6680
6681            if (pkg.mAdoptPermissions != null) {
6682                // This package wants to adopt ownership of permissions from
6683                // another package.
6684                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6685                    final String origName = pkg.mAdoptPermissions.get(i);
6686                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6687                    if (orig != null) {
6688                        if (verifyPackageUpdateLPr(orig, pkg)) {
6689                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6690                                    + pkg.packageName);
6691                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6692                        }
6693                    }
6694                }
6695            }
6696        }
6697
6698        final String pkgName = pkg.packageName;
6699
6700        final long scanFileTime = scanFile.lastModified();
6701        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6702        pkg.applicationInfo.processName = fixProcessName(
6703                pkg.applicationInfo.packageName,
6704                pkg.applicationInfo.processName,
6705                pkg.applicationInfo.uid);
6706
6707        File dataPath;
6708        if (mPlatformPackage == pkg) {
6709            // The system package is special.
6710            dataPath = new File(Environment.getDataDirectory(), "system");
6711
6712            pkg.applicationInfo.dataDir = dataPath.getPath();
6713
6714        } else {
6715            // This is a normal package, need to make its data directory.
6716            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6717                    UserHandle.USER_OWNER, pkg.packageName);
6718
6719            boolean uidError = false;
6720            if (dataPath.exists()) {
6721                int currentUid = 0;
6722                try {
6723                    StructStat stat = Os.stat(dataPath.getPath());
6724                    currentUid = stat.st_uid;
6725                } catch (ErrnoException e) {
6726                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6727                }
6728
6729                // If we have mismatched owners for the data path, we have a problem.
6730                if (currentUid != pkg.applicationInfo.uid) {
6731                    boolean recovered = false;
6732                    if (currentUid == 0) {
6733                        // The directory somehow became owned by root.  Wow.
6734                        // This is probably because the system was stopped while
6735                        // installd was in the middle of messing with its libs
6736                        // directory.  Ask installd to fix that.
6737                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6738                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6739                        if (ret >= 0) {
6740                            recovered = true;
6741                            String msg = "Package " + pkg.packageName
6742                                    + " unexpectedly changed to uid 0; recovered to " +
6743                                    + pkg.applicationInfo.uid;
6744                            reportSettingsProblem(Log.WARN, msg);
6745                        }
6746                    }
6747                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6748                            || (scanFlags&SCAN_BOOTING) != 0)) {
6749                        // If this is a system app, we can at least delete its
6750                        // current data so the application will still work.
6751                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6752                        if (ret >= 0) {
6753                            // TODO: Kill the processes first
6754                            // Old data gone!
6755                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6756                                    ? "System package " : "Third party package ";
6757                            String msg = prefix + pkg.packageName
6758                                    + " has changed from uid: "
6759                                    + currentUid + " to "
6760                                    + pkg.applicationInfo.uid + "; old data erased";
6761                            reportSettingsProblem(Log.WARN, msg);
6762                            recovered = true;
6763
6764                            // And now re-install the app.
6765                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6766                                    pkg.applicationInfo.seinfo);
6767                            if (ret == -1) {
6768                                // Ack should not happen!
6769                                msg = prefix + pkg.packageName
6770                                        + " could not have data directory re-created after delete.";
6771                                reportSettingsProblem(Log.WARN, msg);
6772                                throw new PackageManagerException(
6773                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6774                            }
6775                        }
6776                        if (!recovered) {
6777                            mHasSystemUidErrors = true;
6778                        }
6779                    } else if (!recovered) {
6780                        // If we allow this install to proceed, we will be broken.
6781                        // Abort, abort!
6782                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6783                                "scanPackageLI");
6784                    }
6785                    if (!recovered) {
6786                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6787                            + pkg.applicationInfo.uid + "/fs_"
6788                            + currentUid;
6789                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6790                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6791                        String msg = "Package " + pkg.packageName
6792                                + " has mismatched uid: "
6793                                + currentUid + " on disk, "
6794                                + pkg.applicationInfo.uid + " in settings";
6795                        // writer
6796                        synchronized (mPackages) {
6797                            mSettings.mReadMessages.append(msg);
6798                            mSettings.mReadMessages.append('\n');
6799                            uidError = true;
6800                            if (!pkgSetting.uidError) {
6801                                reportSettingsProblem(Log.ERROR, msg);
6802                            }
6803                        }
6804                    }
6805                }
6806                pkg.applicationInfo.dataDir = dataPath.getPath();
6807                if (mShouldRestoreconData) {
6808                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6809                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6810                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6811                }
6812            } else {
6813                if (DEBUG_PACKAGE_SCANNING) {
6814                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6815                        Log.v(TAG, "Want this data dir: " + dataPath);
6816                }
6817                //invoke installer to do the actual installation
6818                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6819                        pkg.applicationInfo.seinfo);
6820                if (ret < 0) {
6821                    // Error from installer
6822                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6823                            "Unable to create data dirs [errorCode=" + ret + "]");
6824                }
6825
6826                if (dataPath.exists()) {
6827                    pkg.applicationInfo.dataDir = dataPath.getPath();
6828                } else {
6829                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6830                    pkg.applicationInfo.dataDir = null;
6831                }
6832            }
6833
6834            pkgSetting.uidError = uidError;
6835        }
6836
6837        final String path = scanFile.getPath();
6838        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6839
6840        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6841            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6842
6843            // Some system apps still use directory structure for native libraries
6844            // in which case we might end up not detecting abi solely based on apk
6845            // structure. Try to detect abi based on directory structure.
6846            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6847                    pkg.applicationInfo.primaryCpuAbi == null) {
6848                setBundledAppAbisAndRoots(pkg, pkgSetting);
6849                setNativeLibraryPaths(pkg);
6850            }
6851
6852        } else {
6853            if ((scanFlags & SCAN_MOVE) != 0) {
6854                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6855                // but we already have this packages package info in the PackageSetting. We just
6856                // use that and derive the native library path based on the new codepath.
6857                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6858                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6859            }
6860
6861            // Set native library paths again. For moves, the path will be updated based on the
6862            // ABIs we've determined above. For non-moves, the path will be updated based on the
6863            // ABIs we determined during compilation, but the path will depend on the final
6864            // package path (after the rename away from the stage path).
6865            setNativeLibraryPaths(pkg);
6866        }
6867
6868        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6869        final int[] userIds = sUserManager.getUserIds();
6870        synchronized (mInstallLock) {
6871            // Make sure all user data directories are ready to roll; we're okay
6872            // if they already exist
6873            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6874                for (int userId : userIds) {
6875                    if (userId != 0) {
6876                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6877                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6878                                pkg.applicationInfo.seinfo);
6879                    }
6880                }
6881            }
6882
6883            // Create a native library symlink only if we have native libraries
6884            // and if the native libraries are 32 bit libraries. We do not provide
6885            // this symlink for 64 bit libraries.
6886            if (pkg.applicationInfo.primaryCpuAbi != null &&
6887                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6888                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6889                for (int userId : userIds) {
6890                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6891                            nativeLibPath, userId) < 0) {
6892                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6893                                "Failed linking native library dir (user=" + userId + ")");
6894                    }
6895                }
6896            }
6897        }
6898
6899        // This is a special case for the "system" package, where the ABI is
6900        // dictated by the zygote configuration (and init.rc). We should keep track
6901        // of this ABI so that we can deal with "normal" applications that run under
6902        // the same UID correctly.
6903        if (mPlatformPackage == pkg) {
6904            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6905                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6906        }
6907
6908        // If there's a mismatch between the abi-override in the package setting
6909        // and the abiOverride specified for the install. Warn about this because we
6910        // would've already compiled the app without taking the package setting into
6911        // account.
6912        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6913            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6914                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6915                        " for package: " + pkg.packageName);
6916            }
6917        }
6918
6919        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6920        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6921        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6922
6923        // Copy the derived override back to the parsed package, so that we can
6924        // update the package settings accordingly.
6925        pkg.cpuAbiOverride = cpuAbiOverride;
6926
6927        if (DEBUG_ABI_SELECTION) {
6928            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6929                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6930                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6931        }
6932
6933        // Push the derived path down into PackageSettings so we know what to
6934        // clean up at uninstall time.
6935        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6936
6937        if (DEBUG_ABI_SELECTION) {
6938            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6939                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6940                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6941        }
6942
6943        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6944            // We don't do this here during boot because we can do it all
6945            // at once after scanning all existing packages.
6946            //
6947            // We also do this *before* we perform dexopt on this package, so that
6948            // we can avoid redundant dexopts, and also to make sure we've got the
6949            // code and package path correct.
6950            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6951                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6952        }
6953
6954        if ((scanFlags & SCAN_NO_DEX) == 0) {
6955            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6956                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6957            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6958                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6959            }
6960        }
6961        if (mFactoryTest && pkg.requestedPermissions.contains(
6962                android.Manifest.permission.FACTORY_TEST)) {
6963            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6964        }
6965
6966        ArrayList<PackageParser.Package> clientLibPkgs = null;
6967
6968        // writer
6969        synchronized (mPackages) {
6970            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6971                // Only system apps can add new shared libraries.
6972                if (pkg.libraryNames != null) {
6973                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6974                        String name = pkg.libraryNames.get(i);
6975                        boolean allowed = false;
6976                        if (pkg.isUpdatedSystemApp()) {
6977                            // New library entries can only be added through the
6978                            // system image.  This is important to get rid of a lot
6979                            // of nasty edge cases: for example if we allowed a non-
6980                            // system update of the app to add a library, then uninstalling
6981                            // the update would make the library go away, and assumptions
6982                            // we made such as through app install filtering would now
6983                            // have allowed apps on the device which aren't compatible
6984                            // with it.  Better to just have the restriction here, be
6985                            // conservative, and create many fewer cases that can negatively
6986                            // impact the user experience.
6987                            final PackageSetting sysPs = mSettings
6988                                    .getDisabledSystemPkgLPr(pkg.packageName);
6989                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6990                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6991                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6992                                        allowed = true;
6993                                        allowed = true;
6994                                        break;
6995                                    }
6996                                }
6997                            }
6998                        } else {
6999                            allowed = true;
7000                        }
7001                        if (allowed) {
7002                            if (!mSharedLibraries.containsKey(name)) {
7003                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7004                            } else if (!name.equals(pkg.packageName)) {
7005                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7006                                        + name + " already exists; skipping");
7007                            }
7008                        } else {
7009                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7010                                    + name + " that is not declared on system image; skipping");
7011                        }
7012                    }
7013                    if ((scanFlags&SCAN_BOOTING) == 0) {
7014                        // If we are not booting, we need to update any applications
7015                        // that are clients of our shared library.  If we are booting,
7016                        // this will all be done once the scan is complete.
7017                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7018                    }
7019                }
7020            }
7021        }
7022
7023        // We also need to dexopt any apps that are dependent on this library.  Note that
7024        // if these fail, we should abort the install since installing the library will
7025        // result in some apps being broken.
7026        if (clientLibPkgs != null) {
7027            if ((scanFlags & SCAN_NO_DEX) == 0) {
7028                for (int i = 0; i < clientLibPkgs.size(); i++) {
7029                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7030                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7031                            null /* instruction sets */, forceDex,
7032                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7033                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7034                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7035                                "scanPackageLI failed to dexopt clientLibPkgs");
7036                    }
7037                }
7038            }
7039        }
7040
7041        // Also need to kill any apps that are dependent on the library.
7042        if (clientLibPkgs != null) {
7043            for (int i=0; i<clientLibPkgs.size(); i++) {
7044                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7045                killApplication(clientPkg.applicationInfo.packageName,
7046                        clientPkg.applicationInfo.uid, "update lib");
7047            }
7048        }
7049
7050        // Make sure we're not adding any bogus keyset info
7051        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7052        ksms.assertScannedPackageValid(pkg);
7053
7054        // writer
7055        synchronized (mPackages) {
7056            // We don't expect installation to fail beyond this point
7057
7058            // Add the new setting to mSettings
7059            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7060            // Add the new setting to mPackages
7061            mPackages.put(pkg.applicationInfo.packageName, pkg);
7062            // Make sure we don't accidentally delete its data.
7063            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7064            while (iter.hasNext()) {
7065                PackageCleanItem item = iter.next();
7066                if (pkgName.equals(item.packageName)) {
7067                    iter.remove();
7068                }
7069            }
7070
7071            // Take care of first install / last update times.
7072            if (currentTime != 0) {
7073                if (pkgSetting.firstInstallTime == 0) {
7074                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7075                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7076                    pkgSetting.lastUpdateTime = currentTime;
7077                }
7078            } else if (pkgSetting.firstInstallTime == 0) {
7079                // We need *something*.  Take time time stamp of the file.
7080                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7081            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7082                if (scanFileTime != pkgSetting.timeStamp) {
7083                    // A package on the system image has changed; consider this
7084                    // to be an update.
7085                    pkgSetting.lastUpdateTime = scanFileTime;
7086                }
7087            }
7088
7089            // Add the package's KeySets to the global KeySetManagerService
7090            ksms.addScannedPackageLPw(pkg);
7091
7092            int N = pkg.providers.size();
7093            StringBuilder r = null;
7094            int i;
7095            for (i=0; i<N; i++) {
7096                PackageParser.Provider p = pkg.providers.get(i);
7097                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7098                        p.info.processName, pkg.applicationInfo.uid);
7099                mProviders.addProvider(p);
7100                p.syncable = p.info.isSyncable;
7101                if (p.info.authority != null) {
7102                    String names[] = p.info.authority.split(";");
7103                    p.info.authority = null;
7104                    for (int j = 0; j < names.length; j++) {
7105                        if (j == 1 && p.syncable) {
7106                            // We only want the first authority for a provider to possibly be
7107                            // syncable, so if we already added this provider using a different
7108                            // authority clear the syncable flag. We copy the provider before
7109                            // changing it because the mProviders object contains a reference
7110                            // to a provider that we don't want to change.
7111                            // Only do this for the second authority since the resulting provider
7112                            // object can be the same for all future authorities for this provider.
7113                            p = new PackageParser.Provider(p);
7114                            p.syncable = false;
7115                        }
7116                        if (!mProvidersByAuthority.containsKey(names[j])) {
7117                            mProvidersByAuthority.put(names[j], p);
7118                            if (p.info.authority == null) {
7119                                p.info.authority = names[j];
7120                            } else {
7121                                p.info.authority = p.info.authority + ";" + names[j];
7122                            }
7123                            if (DEBUG_PACKAGE_SCANNING) {
7124                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7125                                    Log.d(TAG, "Registered content provider: " + names[j]
7126                                            + ", className = " + p.info.name + ", isSyncable = "
7127                                            + p.info.isSyncable);
7128                            }
7129                        } else {
7130                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7131                            Slog.w(TAG, "Skipping provider name " + names[j] +
7132                                    " (in package " + pkg.applicationInfo.packageName +
7133                                    "): name already used by "
7134                                    + ((other != null && other.getComponentName() != null)
7135                                            ? other.getComponentName().getPackageName() : "?"));
7136                        }
7137                    }
7138                }
7139                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7140                    if (r == null) {
7141                        r = new StringBuilder(256);
7142                    } else {
7143                        r.append(' ');
7144                    }
7145                    r.append(p.info.name);
7146                }
7147            }
7148            if (r != null) {
7149                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7150            }
7151
7152            N = pkg.services.size();
7153            r = null;
7154            for (i=0; i<N; i++) {
7155                PackageParser.Service s = pkg.services.get(i);
7156                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7157                        s.info.processName, pkg.applicationInfo.uid);
7158                mServices.addService(s);
7159                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7160                    if (r == null) {
7161                        r = new StringBuilder(256);
7162                    } else {
7163                        r.append(' ');
7164                    }
7165                    r.append(s.info.name);
7166                }
7167            }
7168            if (r != null) {
7169                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7170            }
7171
7172            N = pkg.receivers.size();
7173            r = null;
7174            for (i=0; i<N; i++) {
7175                PackageParser.Activity a = pkg.receivers.get(i);
7176                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7177                        a.info.processName, pkg.applicationInfo.uid);
7178                mReceivers.addActivity(a, "receiver");
7179                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7180                    if (r == null) {
7181                        r = new StringBuilder(256);
7182                    } else {
7183                        r.append(' ');
7184                    }
7185                    r.append(a.info.name);
7186                }
7187            }
7188            if (r != null) {
7189                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7190            }
7191
7192            N = pkg.activities.size();
7193            r = null;
7194            for (i=0; i<N; i++) {
7195                PackageParser.Activity a = pkg.activities.get(i);
7196                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7197                        a.info.processName, pkg.applicationInfo.uid);
7198                mActivities.addActivity(a, "activity");
7199                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7200                    if (r == null) {
7201                        r = new StringBuilder(256);
7202                    } else {
7203                        r.append(' ');
7204                    }
7205                    r.append(a.info.name);
7206                }
7207            }
7208            if (r != null) {
7209                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7210            }
7211
7212            N = pkg.permissionGroups.size();
7213            r = null;
7214            for (i=0; i<N; i++) {
7215                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7216                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7217                if (cur == null) {
7218                    mPermissionGroups.put(pg.info.name, pg);
7219                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7220                        if (r == null) {
7221                            r = new StringBuilder(256);
7222                        } else {
7223                            r.append(' ');
7224                        }
7225                        r.append(pg.info.name);
7226                    }
7227                } else {
7228                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7229                            + pg.info.packageName + " ignored: original from "
7230                            + cur.info.packageName);
7231                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7232                        if (r == null) {
7233                            r = new StringBuilder(256);
7234                        } else {
7235                            r.append(' ');
7236                        }
7237                        r.append("DUP:");
7238                        r.append(pg.info.name);
7239                    }
7240                }
7241            }
7242            if (r != null) {
7243                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7244            }
7245
7246            N = pkg.permissions.size();
7247            r = null;
7248            for (i=0; i<N; i++) {
7249                PackageParser.Permission p = pkg.permissions.get(i);
7250
7251                // Now that permission groups have a special meaning, we ignore permission
7252                // groups for legacy apps to prevent unexpected behavior. In particular,
7253                // permissions for one app being granted to someone just becuase they happen
7254                // to be in a group defined by another app (before this had no implications).
7255                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7256                    p.group = mPermissionGroups.get(p.info.group);
7257                    // Warn for a permission in an unknown group.
7258                    if (p.info.group != null && p.group == null) {
7259                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7260                                + p.info.packageName + " in an unknown group " + p.info.group);
7261                    }
7262                }
7263
7264                ArrayMap<String, BasePermission> permissionMap =
7265                        p.tree ? mSettings.mPermissionTrees
7266                                : mSettings.mPermissions;
7267                BasePermission bp = permissionMap.get(p.info.name);
7268
7269                // Allow system apps to redefine non-system permissions
7270                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7271                    final boolean currentOwnerIsSystem = (bp.perm != null
7272                            && isSystemApp(bp.perm.owner));
7273                    if (isSystemApp(p.owner)) {
7274                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7275                            // It's a built-in permission and no owner, take ownership now
7276                            bp.packageSetting = pkgSetting;
7277                            bp.perm = p;
7278                            bp.uid = pkg.applicationInfo.uid;
7279                            bp.sourcePackage = p.info.packageName;
7280                        } else if (!currentOwnerIsSystem) {
7281                            String msg = "New decl " + p.owner + " of permission  "
7282                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7283                            reportSettingsProblem(Log.WARN, msg);
7284                            bp = null;
7285                        }
7286                    }
7287                }
7288
7289                if (bp == null) {
7290                    bp = new BasePermission(p.info.name, p.info.packageName,
7291                            BasePermission.TYPE_NORMAL);
7292                    permissionMap.put(p.info.name, bp);
7293                }
7294
7295                if (bp.perm == null) {
7296                    if (bp.sourcePackage == null
7297                            || bp.sourcePackage.equals(p.info.packageName)) {
7298                        BasePermission tree = findPermissionTreeLP(p.info.name);
7299                        if (tree == null
7300                                || tree.sourcePackage.equals(p.info.packageName)) {
7301                            bp.packageSetting = pkgSetting;
7302                            bp.perm = p;
7303                            bp.uid = pkg.applicationInfo.uid;
7304                            bp.sourcePackage = p.info.packageName;
7305                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7306                                if (r == null) {
7307                                    r = new StringBuilder(256);
7308                                } else {
7309                                    r.append(' ');
7310                                }
7311                                r.append(p.info.name);
7312                            }
7313                        } else {
7314                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7315                                    + p.info.packageName + " ignored: base tree "
7316                                    + tree.name + " is from package "
7317                                    + tree.sourcePackage);
7318                        }
7319                    } else {
7320                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7321                                + p.info.packageName + " ignored: original from "
7322                                + bp.sourcePackage);
7323                    }
7324                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7325                    if (r == null) {
7326                        r = new StringBuilder(256);
7327                    } else {
7328                        r.append(' ');
7329                    }
7330                    r.append("DUP:");
7331                    r.append(p.info.name);
7332                }
7333                if (bp.perm == p) {
7334                    bp.protectionLevel = p.info.protectionLevel;
7335                }
7336            }
7337
7338            if (r != null) {
7339                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7340            }
7341
7342            N = pkg.instrumentation.size();
7343            r = null;
7344            for (i=0; i<N; i++) {
7345                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7346                a.info.packageName = pkg.applicationInfo.packageName;
7347                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7348                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7349                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7350                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7351                a.info.dataDir = pkg.applicationInfo.dataDir;
7352
7353                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7354                // need other information about the application, like the ABI and what not ?
7355                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7356                mInstrumentation.put(a.getComponentName(), a);
7357                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7358                    if (r == null) {
7359                        r = new StringBuilder(256);
7360                    } else {
7361                        r.append(' ');
7362                    }
7363                    r.append(a.info.name);
7364                }
7365            }
7366            if (r != null) {
7367                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7368            }
7369
7370            if (pkg.protectedBroadcasts != null) {
7371                N = pkg.protectedBroadcasts.size();
7372                for (i=0; i<N; i++) {
7373                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7374                }
7375            }
7376
7377            pkgSetting.setTimeStamp(scanFileTime);
7378
7379            // Create idmap files for pairs of (packages, overlay packages).
7380            // Note: "android", ie framework-res.apk, is handled by native layers.
7381            if (pkg.mOverlayTarget != null) {
7382                // This is an overlay package.
7383                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7384                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7385                        mOverlays.put(pkg.mOverlayTarget,
7386                                new ArrayMap<String, PackageParser.Package>());
7387                    }
7388                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7389                    map.put(pkg.packageName, pkg);
7390                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7391                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7392                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7393                                "scanPackageLI failed to createIdmap");
7394                    }
7395                }
7396            } else if (mOverlays.containsKey(pkg.packageName) &&
7397                    !pkg.packageName.equals("android")) {
7398                // This is a regular package, with one or more known overlay packages.
7399                createIdmapsForPackageLI(pkg);
7400            }
7401        }
7402
7403        return pkg;
7404    }
7405
7406    /**
7407     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7408     * is derived purely on the basis of the contents of {@code scanFile} and
7409     * {@code cpuAbiOverride}.
7410     *
7411     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7412     */
7413    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7414                                 String cpuAbiOverride, boolean extractLibs)
7415            throws PackageManagerException {
7416        // TODO: We can probably be smarter about this stuff. For installed apps,
7417        // we can calculate this information at install time once and for all. For
7418        // system apps, we can probably assume that this information doesn't change
7419        // after the first boot scan. As things stand, we do lots of unnecessary work.
7420
7421        // Give ourselves some initial paths; we'll come back for another
7422        // pass once we've determined ABI below.
7423        setNativeLibraryPaths(pkg);
7424
7425        // We would never need to extract libs for forward-locked and external packages,
7426        // since the container service will do it for us. We shouldn't attempt to
7427        // extract libs from system app when it was not updated.
7428        if (pkg.isForwardLocked() || isExternal(pkg) ||
7429            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7430            extractLibs = false;
7431        }
7432
7433        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7434        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7435
7436        NativeLibraryHelper.Handle handle = null;
7437        try {
7438            handle = NativeLibraryHelper.Handle.create(scanFile);
7439            // TODO(multiArch): This can be null for apps that didn't go through the
7440            // usual installation process. We can calculate it again, like we
7441            // do during install time.
7442            //
7443            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7444            // unnecessary.
7445            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7446
7447            // Null out the abis so that they can be recalculated.
7448            pkg.applicationInfo.primaryCpuAbi = null;
7449            pkg.applicationInfo.secondaryCpuAbi = null;
7450            if (isMultiArch(pkg.applicationInfo)) {
7451                // Warn if we've set an abiOverride for multi-lib packages..
7452                // By definition, we need to copy both 32 and 64 bit libraries for
7453                // such packages.
7454                if (pkg.cpuAbiOverride != null
7455                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7456                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7457                }
7458
7459                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7460                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7461                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7462                    if (extractLibs) {
7463                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7464                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7465                                useIsaSpecificSubdirs);
7466                    } else {
7467                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7468                    }
7469                }
7470
7471                maybeThrowExceptionForMultiArchCopy(
7472                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7473
7474                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7475                    if (extractLibs) {
7476                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7477                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7478                                useIsaSpecificSubdirs);
7479                    } else {
7480                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7481                    }
7482                }
7483
7484                maybeThrowExceptionForMultiArchCopy(
7485                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7486
7487                if (abi64 >= 0) {
7488                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7489                }
7490
7491                if (abi32 >= 0) {
7492                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7493                    if (abi64 >= 0) {
7494                        pkg.applicationInfo.secondaryCpuAbi = abi;
7495                    } else {
7496                        pkg.applicationInfo.primaryCpuAbi = abi;
7497                    }
7498                }
7499            } else {
7500                String[] abiList = (cpuAbiOverride != null) ?
7501                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7502
7503                // Enable gross and lame hacks for apps that are built with old
7504                // SDK tools. We must scan their APKs for renderscript bitcode and
7505                // not launch them if it's present. Don't bother checking on devices
7506                // that don't have 64 bit support.
7507                boolean needsRenderScriptOverride = false;
7508                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7509                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7510                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7511                    needsRenderScriptOverride = true;
7512                }
7513
7514                final int copyRet;
7515                if (extractLibs) {
7516                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7517                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7518                } else {
7519                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7520                }
7521
7522                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7523                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7524                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7525                }
7526
7527                if (copyRet >= 0) {
7528                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7529                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7530                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7531                } else if (needsRenderScriptOverride) {
7532                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7533                }
7534            }
7535        } catch (IOException ioe) {
7536            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7537        } finally {
7538            IoUtils.closeQuietly(handle);
7539        }
7540
7541        // Now that we've calculated the ABIs and determined if it's an internal app,
7542        // we will go ahead and populate the nativeLibraryPath.
7543        setNativeLibraryPaths(pkg);
7544    }
7545
7546    /**
7547     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7548     * i.e, so that all packages can be run inside a single process if required.
7549     *
7550     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7551     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7552     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7553     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7554     * updating a package that belongs to a shared user.
7555     *
7556     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7557     * adds unnecessary complexity.
7558     */
7559    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7560            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7561        String requiredInstructionSet = null;
7562        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7563            requiredInstructionSet = VMRuntime.getInstructionSet(
7564                     scannedPackage.applicationInfo.primaryCpuAbi);
7565        }
7566
7567        PackageSetting requirer = null;
7568        for (PackageSetting ps : packagesForUser) {
7569            // If packagesForUser contains scannedPackage, we skip it. This will happen
7570            // when scannedPackage is an update of an existing package. Without this check,
7571            // we will never be able to change the ABI of any package belonging to a shared
7572            // user, even if it's compatible with other packages.
7573            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7574                if (ps.primaryCpuAbiString == null) {
7575                    continue;
7576                }
7577
7578                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7579                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7580                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7581                    // this but there's not much we can do.
7582                    String errorMessage = "Instruction set mismatch, "
7583                            + ((requirer == null) ? "[caller]" : requirer)
7584                            + " requires " + requiredInstructionSet + " whereas " + ps
7585                            + " requires " + instructionSet;
7586                    Slog.w(TAG, errorMessage);
7587                }
7588
7589                if (requiredInstructionSet == null) {
7590                    requiredInstructionSet = instructionSet;
7591                    requirer = ps;
7592                }
7593            }
7594        }
7595
7596        if (requiredInstructionSet != null) {
7597            String adjustedAbi;
7598            if (requirer != null) {
7599                // requirer != null implies that either scannedPackage was null or that scannedPackage
7600                // did not require an ABI, in which case we have to adjust scannedPackage to match
7601                // the ABI of the set (which is the same as requirer's ABI)
7602                adjustedAbi = requirer.primaryCpuAbiString;
7603                if (scannedPackage != null) {
7604                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7605                }
7606            } else {
7607                // requirer == null implies that we're updating all ABIs in the set to
7608                // match scannedPackage.
7609                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7610            }
7611
7612            for (PackageSetting ps : packagesForUser) {
7613                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7614                    if (ps.primaryCpuAbiString != null) {
7615                        continue;
7616                    }
7617
7618                    ps.primaryCpuAbiString = adjustedAbi;
7619                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7620                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7621                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7622
7623                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7624                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7625                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7626                            ps.primaryCpuAbiString = null;
7627                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7628                            return;
7629                        } else {
7630                            mInstaller.rmdex(ps.codePathString,
7631                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7632                        }
7633                    }
7634                }
7635            }
7636        }
7637    }
7638
7639    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7640        synchronized (mPackages) {
7641            mResolverReplaced = true;
7642            // Set up information for custom user intent resolution activity.
7643            mResolveActivity.applicationInfo = pkg.applicationInfo;
7644            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7645            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7646            mResolveActivity.processName = pkg.applicationInfo.packageName;
7647            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7648            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7649                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7650            mResolveActivity.theme = 0;
7651            mResolveActivity.exported = true;
7652            mResolveActivity.enabled = true;
7653            mResolveInfo.activityInfo = mResolveActivity;
7654            mResolveInfo.priority = 0;
7655            mResolveInfo.preferredOrder = 0;
7656            mResolveInfo.match = 0;
7657            mResolveComponentName = mCustomResolverComponentName;
7658            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7659                    mResolveComponentName);
7660        }
7661    }
7662
7663    private static String calculateBundledApkRoot(final String codePathString) {
7664        final File codePath = new File(codePathString);
7665        final File codeRoot;
7666        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7667            codeRoot = Environment.getRootDirectory();
7668        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7669            codeRoot = Environment.getOemDirectory();
7670        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7671            codeRoot = Environment.getVendorDirectory();
7672        } else {
7673            // Unrecognized code path; take its top real segment as the apk root:
7674            // e.g. /something/app/blah.apk => /something
7675            try {
7676                File f = codePath.getCanonicalFile();
7677                File parent = f.getParentFile();    // non-null because codePath is a file
7678                File tmp;
7679                while ((tmp = parent.getParentFile()) != null) {
7680                    f = parent;
7681                    parent = tmp;
7682                }
7683                codeRoot = f;
7684                Slog.w(TAG, "Unrecognized code path "
7685                        + codePath + " - using " + codeRoot);
7686            } catch (IOException e) {
7687                // Can't canonicalize the code path -- shenanigans?
7688                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7689                return Environment.getRootDirectory().getPath();
7690            }
7691        }
7692        return codeRoot.getPath();
7693    }
7694
7695    /**
7696     * Derive and set the location of native libraries for the given package,
7697     * which varies depending on where and how the package was installed.
7698     */
7699    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7700        final ApplicationInfo info = pkg.applicationInfo;
7701        final String codePath = pkg.codePath;
7702        final File codeFile = new File(codePath);
7703        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7704        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7705
7706        info.nativeLibraryRootDir = null;
7707        info.nativeLibraryRootRequiresIsa = false;
7708        info.nativeLibraryDir = null;
7709        info.secondaryNativeLibraryDir = null;
7710
7711        if (isApkFile(codeFile)) {
7712            // Monolithic install
7713            if (bundledApp) {
7714                // If "/system/lib64/apkname" exists, assume that is the per-package
7715                // native library directory to use; otherwise use "/system/lib/apkname".
7716                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7717                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7718                        getPrimaryInstructionSet(info));
7719
7720                // This is a bundled system app so choose the path based on the ABI.
7721                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7722                // is just the default path.
7723                final String apkName = deriveCodePathName(codePath);
7724                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7725                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7726                        apkName).getAbsolutePath();
7727
7728                if (info.secondaryCpuAbi != null) {
7729                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7730                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7731                            secondaryLibDir, apkName).getAbsolutePath();
7732                }
7733            } else if (asecApp) {
7734                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7735                        .getAbsolutePath();
7736            } else {
7737                final String apkName = deriveCodePathName(codePath);
7738                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7739                        .getAbsolutePath();
7740            }
7741
7742            info.nativeLibraryRootRequiresIsa = false;
7743            info.nativeLibraryDir = info.nativeLibraryRootDir;
7744        } else {
7745            // Cluster install
7746            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7747            info.nativeLibraryRootRequiresIsa = true;
7748
7749            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7750                    getPrimaryInstructionSet(info)).getAbsolutePath();
7751
7752            if (info.secondaryCpuAbi != null) {
7753                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7754                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7755            }
7756        }
7757    }
7758
7759    /**
7760     * Calculate the abis and roots for a bundled app. These can uniquely
7761     * be determined from the contents of the system partition, i.e whether
7762     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7763     * of this information, and instead assume that the system was built
7764     * sensibly.
7765     */
7766    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7767                                           PackageSetting pkgSetting) {
7768        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7769
7770        // If "/system/lib64/apkname" exists, assume that is the per-package
7771        // native library directory to use; otherwise use "/system/lib/apkname".
7772        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7773        setBundledAppAbi(pkg, apkRoot, apkName);
7774        // pkgSetting might be null during rescan following uninstall of updates
7775        // to a bundled app, so accommodate that possibility.  The settings in
7776        // that case will be established later from the parsed package.
7777        //
7778        // If the settings aren't null, sync them up with what we've just derived.
7779        // note that apkRoot isn't stored in the package settings.
7780        if (pkgSetting != null) {
7781            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7782            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7783        }
7784    }
7785
7786    /**
7787     * Deduces the ABI of a bundled app and sets the relevant fields on the
7788     * parsed pkg object.
7789     *
7790     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7791     *        under which system libraries are installed.
7792     * @param apkName the name of the installed package.
7793     */
7794    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7795        final File codeFile = new File(pkg.codePath);
7796
7797        final boolean has64BitLibs;
7798        final boolean has32BitLibs;
7799        if (isApkFile(codeFile)) {
7800            // Monolithic install
7801            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7802            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7803        } else {
7804            // Cluster install
7805            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7806            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7807                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7808                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7809                has64BitLibs = (new File(rootDir, isa)).exists();
7810            } else {
7811                has64BitLibs = false;
7812            }
7813            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7814                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7815                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7816                has32BitLibs = (new File(rootDir, isa)).exists();
7817            } else {
7818                has32BitLibs = false;
7819            }
7820        }
7821
7822        if (has64BitLibs && !has32BitLibs) {
7823            // The package has 64 bit libs, but not 32 bit libs. Its primary
7824            // ABI should be 64 bit. We can safely assume here that the bundled
7825            // native libraries correspond to the most preferred ABI in the list.
7826
7827            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7828            pkg.applicationInfo.secondaryCpuAbi = null;
7829        } else if (has32BitLibs && !has64BitLibs) {
7830            // The package has 32 bit libs but not 64 bit libs. Its primary
7831            // ABI should be 32 bit.
7832
7833            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7834            pkg.applicationInfo.secondaryCpuAbi = null;
7835        } else if (has32BitLibs && has64BitLibs) {
7836            // The application has both 64 and 32 bit bundled libraries. We check
7837            // here that the app declares multiArch support, and warn if it doesn't.
7838            //
7839            // We will be lenient here and record both ABIs. The primary will be the
7840            // ABI that's higher on the list, i.e, a device that's configured to prefer
7841            // 64 bit apps will see a 64 bit primary ABI,
7842
7843            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7844                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7845            }
7846
7847            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7848                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7849                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7850            } else {
7851                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7852                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7853            }
7854        } else {
7855            pkg.applicationInfo.primaryCpuAbi = null;
7856            pkg.applicationInfo.secondaryCpuAbi = null;
7857        }
7858    }
7859
7860    private void killApplication(String pkgName, int appId, String reason) {
7861        // Request the ActivityManager to kill the process(only for existing packages)
7862        // so that we do not end up in a confused state while the user is still using the older
7863        // version of the application while the new one gets installed.
7864        IActivityManager am = ActivityManagerNative.getDefault();
7865        if (am != null) {
7866            try {
7867                am.killApplicationWithAppId(pkgName, appId, reason);
7868            } catch (RemoteException e) {
7869            }
7870        }
7871    }
7872
7873    void removePackageLI(PackageSetting ps, boolean chatty) {
7874        if (DEBUG_INSTALL) {
7875            if (chatty)
7876                Log.d(TAG, "Removing package " + ps.name);
7877        }
7878
7879        // writer
7880        synchronized (mPackages) {
7881            mPackages.remove(ps.name);
7882            final PackageParser.Package pkg = ps.pkg;
7883            if (pkg != null) {
7884                cleanPackageDataStructuresLILPw(pkg, chatty);
7885            }
7886        }
7887    }
7888
7889    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7890        if (DEBUG_INSTALL) {
7891            if (chatty)
7892                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7893        }
7894
7895        // writer
7896        synchronized (mPackages) {
7897            mPackages.remove(pkg.applicationInfo.packageName);
7898            cleanPackageDataStructuresLILPw(pkg, chatty);
7899        }
7900    }
7901
7902    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7903        int N = pkg.providers.size();
7904        StringBuilder r = null;
7905        int i;
7906        for (i=0; i<N; i++) {
7907            PackageParser.Provider p = pkg.providers.get(i);
7908            mProviders.removeProvider(p);
7909            if (p.info.authority == null) {
7910
7911                /* There was another ContentProvider with this authority when
7912                 * this app was installed so this authority is null,
7913                 * Ignore it as we don't have to unregister the provider.
7914                 */
7915                continue;
7916            }
7917            String names[] = p.info.authority.split(";");
7918            for (int j = 0; j < names.length; j++) {
7919                if (mProvidersByAuthority.get(names[j]) == p) {
7920                    mProvidersByAuthority.remove(names[j]);
7921                    if (DEBUG_REMOVE) {
7922                        if (chatty)
7923                            Log.d(TAG, "Unregistered content provider: " + names[j]
7924                                    + ", className = " + p.info.name + ", isSyncable = "
7925                                    + p.info.isSyncable);
7926                    }
7927                }
7928            }
7929            if (DEBUG_REMOVE && chatty) {
7930                if (r == null) {
7931                    r = new StringBuilder(256);
7932                } else {
7933                    r.append(' ');
7934                }
7935                r.append(p.info.name);
7936            }
7937        }
7938        if (r != null) {
7939            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7940        }
7941
7942        N = pkg.services.size();
7943        r = null;
7944        for (i=0; i<N; i++) {
7945            PackageParser.Service s = pkg.services.get(i);
7946            mServices.removeService(s);
7947            if (chatty) {
7948                if (r == null) {
7949                    r = new StringBuilder(256);
7950                } else {
7951                    r.append(' ');
7952                }
7953                r.append(s.info.name);
7954            }
7955        }
7956        if (r != null) {
7957            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7958        }
7959
7960        N = pkg.receivers.size();
7961        r = null;
7962        for (i=0; i<N; i++) {
7963            PackageParser.Activity a = pkg.receivers.get(i);
7964            mReceivers.removeActivity(a, "receiver");
7965            if (DEBUG_REMOVE && chatty) {
7966                if (r == null) {
7967                    r = new StringBuilder(256);
7968                } else {
7969                    r.append(' ');
7970                }
7971                r.append(a.info.name);
7972            }
7973        }
7974        if (r != null) {
7975            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7976        }
7977
7978        N = pkg.activities.size();
7979        r = null;
7980        for (i=0; i<N; i++) {
7981            PackageParser.Activity a = pkg.activities.get(i);
7982            mActivities.removeActivity(a, "activity");
7983            if (DEBUG_REMOVE && chatty) {
7984                if (r == null) {
7985                    r = new StringBuilder(256);
7986                } else {
7987                    r.append(' ');
7988                }
7989                r.append(a.info.name);
7990            }
7991        }
7992        if (r != null) {
7993            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7994        }
7995
7996        N = pkg.permissions.size();
7997        r = null;
7998        for (i=0; i<N; i++) {
7999            PackageParser.Permission p = pkg.permissions.get(i);
8000            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8001            if (bp == null) {
8002                bp = mSettings.mPermissionTrees.get(p.info.name);
8003            }
8004            if (bp != null && bp.perm == p) {
8005                bp.perm = null;
8006                if (DEBUG_REMOVE && chatty) {
8007                    if (r == null) {
8008                        r = new StringBuilder(256);
8009                    } else {
8010                        r.append(' ');
8011                    }
8012                    r.append(p.info.name);
8013                }
8014            }
8015            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8016                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8017                if (appOpPerms != null) {
8018                    appOpPerms.remove(pkg.packageName);
8019                }
8020            }
8021        }
8022        if (r != null) {
8023            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8024        }
8025
8026        N = pkg.requestedPermissions.size();
8027        r = null;
8028        for (i=0; i<N; i++) {
8029            String perm = pkg.requestedPermissions.get(i);
8030            BasePermission bp = mSettings.mPermissions.get(perm);
8031            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8032                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8033                if (appOpPerms != null) {
8034                    appOpPerms.remove(pkg.packageName);
8035                    if (appOpPerms.isEmpty()) {
8036                        mAppOpPermissionPackages.remove(perm);
8037                    }
8038                }
8039            }
8040        }
8041        if (r != null) {
8042            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8043        }
8044
8045        N = pkg.instrumentation.size();
8046        r = null;
8047        for (i=0; i<N; i++) {
8048            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8049            mInstrumentation.remove(a.getComponentName());
8050            if (DEBUG_REMOVE && chatty) {
8051                if (r == null) {
8052                    r = new StringBuilder(256);
8053                } else {
8054                    r.append(' ');
8055                }
8056                r.append(a.info.name);
8057            }
8058        }
8059        if (r != null) {
8060            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8061        }
8062
8063        r = null;
8064        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8065            // Only system apps can hold shared libraries.
8066            if (pkg.libraryNames != null) {
8067                for (i=0; i<pkg.libraryNames.size(); i++) {
8068                    String name = pkg.libraryNames.get(i);
8069                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8070                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8071                        mSharedLibraries.remove(name);
8072                        if (DEBUG_REMOVE && chatty) {
8073                            if (r == null) {
8074                                r = new StringBuilder(256);
8075                            } else {
8076                                r.append(' ');
8077                            }
8078                            r.append(name);
8079                        }
8080                    }
8081                }
8082            }
8083        }
8084        if (r != null) {
8085            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8086        }
8087    }
8088
8089    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8090        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8091            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8092                return true;
8093            }
8094        }
8095        return false;
8096    }
8097
8098    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8099    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8100    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8101
8102    private void updatePermissionsLPw(String changingPkg,
8103            PackageParser.Package pkgInfo, int flags) {
8104        // Make sure there are no dangling permission trees.
8105        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8106        while (it.hasNext()) {
8107            final BasePermission bp = it.next();
8108            if (bp.packageSetting == null) {
8109                // We may not yet have parsed the package, so just see if
8110                // we still know about its settings.
8111                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8112            }
8113            if (bp.packageSetting == null) {
8114                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8115                        + " from package " + bp.sourcePackage);
8116                it.remove();
8117            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8118                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8119                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8120                            + " from package " + bp.sourcePackage);
8121                    flags |= UPDATE_PERMISSIONS_ALL;
8122                    it.remove();
8123                }
8124            }
8125        }
8126
8127        // Make sure all dynamic permissions have been assigned to a package,
8128        // and make sure there are no dangling permissions.
8129        it = mSettings.mPermissions.values().iterator();
8130        while (it.hasNext()) {
8131            final BasePermission bp = it.next();
8132            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8133                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8134                        + bp.name + " pkg=" + bp.sourcePackage
8135                        + " info=" + bp.pendingInfo);
8136                if (bp.packageSetting == null && bp.pendingInfo != null) {
8137                    final BasePermission tree = findPermissionTreeLP(bp.name);
8138                    if (tree != null && tree.perm != null) {
8139                        bp.packageSetting = tree.packageSetting;
8140                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8141                                new PermissionInfo(bp.pendingInfo));
8142                        bp.perm.info.packageName = tree.perm.info.packageName;
8143                        bp.perm.info.name = bp.name;
8144                        bp.uid = tree.uid;
8145                    }
8146                }
8147            }
8148            if (bp.packageSetting == null) {
8149                // We may not yet have parsed the package, so just see if
8150                // we still know about its settings.
8151                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8152            }
8153            if (bp.packageSetting == null) {
8154                Slog.w(TAG, "Removing dangling permission: " + bp.name
8155                        + " from package " + bp.sourcePackage);
8156                it.remove();
8157            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8158                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8159                    Slog.i(TAG, "Removing old permission: " + bp.name
8160                            + " from package " + bp.sourcePackage);
8161                    flags |= UPDATE_PERMISSIONS_ALL;
8162                    it.remove();
8163                }
8164            }
8165        }
8166
8167        // Now update the permissions for all packages, in particular
8168        // replace the granted permissions of the system packages.
8169        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8170            for (PackageParser.Package pkg : mPackages.values()) {
8171                if (pkg != pkgInfo) {
8172                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8173                            changingPkg);
8174                }
8175            }
8176        }
8177
8178        if (pkgInfo != null) {
8179            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8180        }
8181    }
8182
8183    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8184            String packageOfInterest) {
8185        // IMPORTANT: There are two types of permissions: install and runtime.
8186        // Install time permissions are granted when the app is installed to
8187        // all device users and users added in the future. Runtime permissions
8188        // are granted at runtime explicitly to specific users. Normal and signature
8189        // protected permissions are install time permissions. Dangerous permissions
8190        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8191        // otherwise they are runtime permissions. This function does not manage
8192        // runtime permissions except for the case an app targeting Lollipop MR1
8193        // being upgraded to target a newer SDK, in which case dangerous permissions
8194        // are transformed from install time to runtime ones.
8195
8196        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8197        if (ps == null) {
8198            return;
8199        }
8200
8201        PermissionsState permissionsState = ps.getPermissionsState();
8202        PermissionsState origPermissions = permissionsState;
8203
8204        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8205
8206        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8207
8208        boolean changedInstallPermission = false;
8209
8210        if (replace) {
8211            ps.installPermissionsFixed = false;
8212            if (!ps.isSharedUser()) {
8213                origPermissions = new PermissionsState(permissionsState);
8214                permissionsState.reset();
8215            }
8216        }
8217
8218        permissionsState.setGlobalGids(mGlobalGids);
8219
8220        final int N = pkg.requestedPermissions.size();
8221        for (int i=0; i<N; i++) {
8222            final String name = pkg.requestedPermissions.get(i);
8223            final BasePermission bp = mSettings.mPermissions.get(name);
8224
8225            if (DEBUG_INSTALL) {
8226                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8227            }
8228
8229            if (bp == null || bp.packageSetting == null) {
8230                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8231                    Slog.w(TAG, "Unknown permission " + name
8232                            + " in package " + pkg.packageName);
8233                }
8234                continue;
8235            }
8236
8237            final String perm = bp.name;
8238            boolean allowedSig = false;
8239            int grant = GRANT_DENIED;
8240
8241            // Keep track of app op permissions.
8242            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8243                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8244                if (pkgs == null) {
8245                    pkgs = new ArraySet<>();
8246                    mAppOpPermissionPackages.put(bp.name, pkgs);
8247                }
8248                pkgs.add(pkg.packageName);
8249            }
8250
8251            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8252            switch (level) {
8253                case PermissionInfo.PROTECTION_NORMAL: {
8254                    // For all apps normal permissions are install time ones.
8255                    grant = GRANT_INSTALL;
8256                } break;
8257
8258                case PermissionInfo.PROTECTION_DANGEROUS: {
8259                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8260                        // For legacy apps dangerous permissions are install time ones.
8261                        grant = GRANT_INSTALL_LEGACY;
8262                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8263                        // For legacy apps that became modern, install becomes runtime.
8264                        grant = GRANT_UPGRADE;
8265                    } else {
8266                        // For modern apps keep runtime permissions unchanged.
8267                        grant = GRANT_RUNTIME;
8268                    }
8269                } break;
8270
8271                case PermissionInfo.PROTECTION_SIGNATURE: {
8272                    // For all apps signature permissions are install time ones.
8273                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8274                    if (allowedSig) {
8275                        grant = GRANT_INSTALL;
8276                    }
8277                } break;
8278            }
8279
8280            if (DEBUG_INSTALL) {
8281                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8282            }
8283
8284            if (grant != GRANT_DENIED) {
8285                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8286                    // If this is an existing, non-system package, then
8287                    // we can't add any new permissions to it.
8288                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8289                        // Except...  if this is a permission that was added
8290                        // to the platform (note: need to only do this when
8291                        // updating the platform).
8292                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8293                            grant = GRANT_DENIED;
8294                        }
8295                    }
8296                }
8297
8298                switch (grant) {
8299                    case GRANT_INSTALL: {
8300                        // Revoke this as runtime permission to handle the case of
8301                        // a runtime permission being downgraded to an install one.
8302                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8303                            if (origPermissions.getRuntimePermissionState(
8304                                    bp.name, userId) != null) {
8305                                // Revoke the runtime permission and clear the flags.
8306                                origPermissions.revokeRuntimePermission(bp, userId);
8307                                origPermissions.updatePermissionFlags(bp, userId,
8308                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8309                                // If we revoked a permission permission, we have to write.
8310                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8311                                        changedRuntimePermissionUserIds, userId);
8312                            }
8313                        }
8314                        // Grant an install permission.
8315                        if (permissionsState.grantInstallPermission(bp) !=
8316                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8317                            changedInstallPermission = true;
8318                        }
8319                    } break;
8320
8321                    case GRANT_INSTALL_LEGACY: {
8322                        // Grant an install permission.
8323                        if (permissionsState.grantInstallPermission(bp) !=
8324                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8325                            changedInstallPermission = true;
8326                        }
8327                    } break;
8328
8329                    case GRANT_RUNTIME: {
8330                        // Grant previously granted runtime permissions.
8331                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8332                            PermissionState permissionState = origPermissions
8333                                    .getRuntimePermissionState(bp.name, userId);
8334                            final int flags = permissionState != null
8335                                    ? permissionState.getFlags() : 0;
8336                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8337                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8338                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8339                                    // If we cannot put the permission as it was, we have to write.
8340                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8341                                            changedRuntimePermissionUserIds, userId);
8342                                }
8343                            }
8344                            // Propagate the permission flags.
8345                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8346                        }
8347                    } break;
8348
8349                    case GRANT_UPGRADE: {
8350                        // Grant runtime permissions for a previously held install permission.
8351                        PermissionState permissionState = origPermissions
8352                                .getInstallPermissionState(bp.name);
8353                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8354
8355                        if (origPermissions.revokeInstallPermission(bp)
8356                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8357                            // We will be transferring the permission flags, so clear them.
8358                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8359                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8360                            changedInstallPermission = true;
8361                        }
8362
8363                        // If the permission is not to be promoted to runtime we ignore it and
8364                        // also its other flags as they are not applicable to install permissions.
8365                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8366                            for (int userId : currentUserIds) {
8367                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8368                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8369                                    // Transfer the permission flags.
8370                                    permissionsState.updatePermissionFlags(bp, userId,
8371                                            flags, flags);
8372                                    // If we granted the permission, we have to write.
8373                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8374                                            changedRuntimePermissionUserIds, userId);
8375                                }
8376                            }
8377                        }
8378                    } break;
8379
8380                    default: {
8381                        if (packageOfInterest == null
8382                                || packageOfInterest.equals(pkg.packageName)) {
8383                            Slog.w(TAG, "Not granting permission " + perm
8384                                    + " to package " + pkg.packageName
8385                                    + " because it was previously installed without");
8386                        }
8387                    } break;
8388                }
8389            } else {
8390                if (permissionsState.revokeInstallPermission(bp) !=
8391                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8392                    // Also drop the permission flags.
8393                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8394                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8395                    changedInstallPermission = true;
8396                    Slog.i(TAG, "Un-granting permission " + perm
8397                            + " from package " + pkg.packageName
8398                            + " (protectionLevel=" + bp.protectionLevel
8399                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8400                            + ")");
8401                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8402                    // Don't print warning for app op permissions, since it is fine for them
8403                    // not to be granted, there is a UI for the user to decide.
8404                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8405                        Slog.w(TAG, "Not granting permission " + perm
8406                                + " to package " + pkg.packageName
8407                                + " (protectionLevel=" + bp.protectionLevel
8408                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8409                                + ")");
8410                    }
8411                }
8412            }
8413        }
8414
8415        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8416                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8417            // This is the first that we have heard about this package, so the
8418            // permissions we have now selected are fixed until explicitly
8419            // changed.
8420            ps.installPermissionsFixed = true;
8421        }
8422
8423        // Persist the runtime permissions state for users with changes.
8424        for (int userId : changedRuntimePermissionUserIds) {
8425            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8426        }
8427    }
8428
8429    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8430        boolean allowed = false;
8431        final int NP = PackageParser.NEW_PERMISSIONS.length;
8432        for (int ip=0; ip<NP; ip++) {
8433            final PackageParser.NewPermissionInfo npi
8434                    = PackageParser.NEW_PERMISSIONS[ip];
8435            if (npi.name.equals(perm)
8436                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8437                allowed = true;
8438                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8439                        + pkg.packageName);
8440                break;
8441            }
8442        }
8443        return allowed;
8444    }
8445
8446    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8447            BasePermission bp, PermissionsState origPermissions) {
8448        boolean allowed;
8449        allowed = (compareSignatures(
8450                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8451                        == PackageManager.SIGNATURE_MATCH)
8452                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8453                        == PackageManager.SIGNATURE_MATCH);
8454        if (!allowed && (bp.protectionLevel
8455                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8456            if (isSystemApp(pkg)) {
8457                // For updated system applications, a system permission
8458                // is granted only if it had been defined by the original application.
8459                if (pkg.isUpdatedSystemApp()) {
8460                    final PackageSetting sysPs = mSettings
8461                            .getDisabledSystemPkgLPr(pkg.packageName);
8462                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8463                        // If the original was granted this permission, we take
8464                        // that grant decision as read and propagate it to the
8465                        // update.
8466                        if (sysPs.isPrivileged()) {
8467                            allowed = true;
8468                        }
8469                    } else {
8470                        // The system apk may have been updated with an older
8471                        // version of the one on the data partition, but which
8472                        // granted a new system permission that it didn't have
8473                        // before.  In this case we do want to allow the app to
8474                        // now get the new permission if the ancestral apk is
8475                        // privileged to get it.
8476                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8477                            for (int j=0;
8478                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8479                                if (perm.equals(
8480                                        sysPs.pkg.requestedPermissions.get(j))) {
8481                                    allowed = true;
8482                                    break;
8483                                }
8484                            }
8485                        }
8486                    }
8487                } else {
8488                    allowed = isPrivilegedApp(pkg);
8489                }
8490            }
8491        }
8492        if (!allowed) {
8493            if (!allowed && (bp.protectionLevel
8494                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8495                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8496                // If this was a previously normal/dangerous permission that got moved
8497                // to a system permission as part of the runtime permission redesign, then
8498                // we still want to blindly grant it to old apps.
8499                allowed = true;
8500            }
8501            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8502                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8503                // If this permission is to be granted to the system installer and
8504                // this app is an installer, then it gets the permission.
8505                allowed = true;
8506            }
8507            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8508                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8509                // If this permission is to be granted to the system verifier and
8510                // this app is a verifier, then it gets the permission.
8511                allowed = true;
8512            }
8513            if (!allowed && (bp.protectionLevel
8514                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8515                    && isSystemApp(pkg)) {
8516                // Any pre-installed system app is allowed to get this permission.
8517                allowed = true;
8518            }
8519            if (!allowed && (bp.protectionLevel
8520                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8521                // For development permissions, a development permission
8522                // is granted only if it was already granted.
8523                allowed = origPermissions.hasInstallPermission(perm);
8524            }
8525        }
8526        return allowed;
8527    }
8528
8529    final class ActivityIntentResolver
8530            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8531        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8532                boolean defaultOnly, int userId) {
8533            if (!sUserManager.exists(userId)) return null;
8534            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8535            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8536        }
8537
8538        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8539                int userId) {
8540            if (!sUserManager.exists(userId)) return null;
8541            mFlags = flags;
8542            return super.queryIntent(intent, resolvedType,
8543                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8544        }
8545
8546        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8547                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8548            if (!sUserManager.exists(userId)) return null;
8549            if (packageActivities == null) {
8550                return null;
8551            }
8552            mFlags = flags;
8553            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8554            final int N = packageActivities.size();
8555            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8556                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8557
8558            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8559            for (int i = 0; i < N; ++i) {
8560                intentFilters = packageActivities.get(i).intents;
8561                if (intentFilters != null && intentFilters.size() > 0) {
8562                    PackageParser.ActivityIntentInfo[] array =
8563                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8564                    intentFilters.toArray(array);
8565                    listCut.add(array);
8566                }
8567            }
8568            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8569        }
8570
8571        public final void addActivity(PackageParser.Activity a, String type) {
8572            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8573            mActivities.put(a.getComponentName(), a);
8574            if (DEBUG_SHOW_INFO)
8575                Log.v(
8576                TAG, "  " + type + " " +
8577                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8578            if (DEBUG_SHOW_INFO)
8579                Log.v(TAG, "    Class=" + a.info.name);
8580            final int NI = a.intents.size();
8581            for (int j=0; j<NI; j++) {
8582                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8583                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8584                    intent.setPriority(0);
8585                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8586                            + a.className + " with priority > 0, forcing to 0");
8587                }
8588                if (DEBUG_SHOW_INFO) {
8589                    Log.v(TAG, "    IntentFilter:");
8590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8591                }
8592                if (!intent.debugCheck()) {
8593                    Log.w(TAG, "==> For Activity " + a.info.name);
8594                }
8595                addFilter(intent);
8596            }
8597        }
8598
8599        public final void removeActivity(PackageParser.Activity a, String type) {
8600            mActivities.remove(a.getComponentName());
8601            if (DEBUG_SHOW_INFO) {
8602                Log.v(TAG, "  " + type + " "
8603                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8604                                : a.info.name) + ":");
8605                Log.v(TAG, "    Class=" + a.info.name);
8606            }
8607            final int NI = a.intents.size();
8608            for (int j=0; j<NI; j++) {
8609                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8610                if (DEBUG_SHOW_INFO) {
8611                    Log.v(TAG, "    IntentFilter:");
8612                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8613                }
8614                removeFilter(intent);
8615            }
8616        }
8617
8618        @Override
8619        protected boolean allowFilterResult(
8620                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8621            ActivityInfo filterAi = filter.activity.info;
8622            for (int i=dest.size()-1; i>=0; i--) {
8623                ActivityInfo destAi = dest.get(i).activityInfo;
8624                if (destAi.name == filterAi.name
8625                        && destAi.packageName == filterAi.packageName) {
8626                    return false;
8627                }
8628            }
8629            return true;
8630        }
8631
8632        @Override
8633        protected ActivityIntentInfo[] newArray(int size) {
8634            return new ActivityIntentInfo[size];
8635        }
8636
8637        @Override
8638        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8639            if (!sUserManager.exists(userId)) return true;
8640            PackageParser.Package p = filter.activity.owner;
8641            if (p != null) {
8642                PackageSetting ps = (PackageSetting)p.mExtras;
8643                if (ps != null) {
8644                    // System apps are never considered stopped for purposes of
8645                    // filtering, because there may be no way for the user to
8646                    // actually re-launch them.
8647                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8648                            && ps.getStopped(userId);
8649                }
8650            }
8651            return false;
8652        }
8653
8654        @Override
8655        protected boolean isPackageForFilter(String packageName,
8656                PackageParser.ActivityIntentInfo info) {
8657            return packageName.equals(info.activity.owner.packageName);
8658        }
8659
8660        @Override
8661        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8662                int match, int userId) {
8663            if (!sUserManager.exists(userId)) return null;
8664            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8665                return null;
8666            }
8667            final PackageParser.Activity activity = info.activity;
8668            if (mSafeMode && (activity.info.applicationInfo.flags
8669                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8670                return null;
8671            }
8672            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8673            if (ps == null) {
8674                return null;
8675            }
8676            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8677                    ps.readUserState(userId), userId);
8678            if (ai == null) {
8679                return null;
8680            }
8681            final ResolveInfo res = new ResolveInfo();
8682            res.activityInfo = ai;
8683            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8684                res.filter = info;
8685            }
8686            if (info != null) {
8687                res.handleAllWebDataURI = info.handleAllWebDataURI();
8688            }
8689            res.priority = info.getPriority();
8690            res.preferredOrder = activity.owner.mPreferredOrder;
8691            //System.out.println("Result: " + res.activityInfo.className +
8692            //                   " = " + res.priority);
8693            res.match = match;
8694            res.isDefault = info.hasDefault;
8695            res.labelRes = info.labelRes;
8696            res.nonLocalizedLabel = info.nonLocalizedLabel;
8697            if (userNeedsBadging(userId)) {
8698                res.noResourceId = true;
8699            } else {
8700                res.icon = info.icon;
8701            }
8702            res.iconResourceId = info.icon;
8703            res.system = res.activityInfo.applicationInfo.isSystemApp();
8704            return res;
8705        }
8706
8707        @Override
8708        protected void sortResults(List<ResolveInfo> results) {
8709            Collections.sort(results, mResolvePrioritySorter);
8710        }
8711
8712        @Override
8713        protected void dumpFilter(PrintWriter out, String prefix,
8714                PackageParser.ActivityIntentInfo filter) {
8715            out.print(prefix); out.print(
8716                    Integer.toHexString(System.identityHashCode(filter.activity)));
8717                    out.print(' ');
8718                    filter.activity.printComponentShortName(out);
8719                    out.print(" filter ");
8720                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8721        }
8722
8723        @Override
8724        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8725            return filter.activity;
8726        }
8727
8728        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8729            PackageParser.Activity activity = (PackageParser.Activity)label;
8730            out.print(prefix); out.print(
8731                    Integer.toHexString(System.identityHashCode(activity)));
8732                    out.print(' ');
8733                    activity.printComponentShortName(out);
8734            if (count > 1) {
8735                out.print(" ("); out.print(count); out.print(" filters)");
8736            }
8737            out.println();
8738        }
8739
8740//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8741//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8742//            final List<ResolveInfo> retList = Lists.newArrayList();
8743//            while (i.hasNext()) {
8744//                final ResolveInfo resolveInfo = i.next();
8745//                if (isEnabledLP(resolveInfo.activityInfo)) {
8746//                    retList.add(resolveInfo);
8747//                }
8748//            }
8749//            return retList;
8750//        }
8751
8752        // Keys are String (activity class name), values are Activity.
8753        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8754                = new ArrayMap<ComponentName, PackageParser.Activity>();
8755        private int mFlags;
8756    }
8757
8758    private final class ServiceIntentResolver
8759            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8760        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8761                boolean defaultOnly, int userId) {
8762            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8763            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8764        }
8765
8766        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8767                int userId) {
8768            if (!sUserManager.exists(userId)) return null;
8769            mFlags = flags;
8770            return super.queryIntent(intent, resolvedType,
8771                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8772        }
8773
8774        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8775                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8776            if (!sUserManager.exists(userId)) return null;
8777            if (packageServices == null) {
8778                return null;
8779            }
8780            mFlags = flags;
8781            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8782            final int N = packageServices.size();
8783            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8784                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8785
8786            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8787            for (int i = 0; i < N; ++i) {
8788                intentFilters = packageServices.get(i).intents;
8789                if (intentFilters != null && intentFilters.size() > 0) {
8790                    PackageParser.ServiceIntentInfo[] array =
8791                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8792                    intentFilters.toArray(array);
8793                    listCut.add(array);
8794                }
8795            }
8796            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8797        }
8798
8799        public final void addService(PackageParser.Service s) {
8800            mServices.put(s.getComponentName(), s);
8801            if (DEBUG_SHOW_INFO) {
8802                Log.v(TAG, "  "
8803                        + (s.info.nonLocalizedLabel != null
8804                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8805                Log.v(TAG, "    Class=" + s.info.name);
8806            }
8807            final int NI = s.intents.size();
8808            int j;
8809            for (j=0; j<NI; j++) {
8810                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8811                if (DEBUG_SHOW_INFO) {
8812                    Log.v(TAG, "    IntentFilter:");
8813                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8814                }
8815                if (!intent.debugCheck()) {
8816                    Log.w(TAG, "==> For Service " + s.info.name);
8817                }
8818                addFilter(intent);
8819            }
8820        }
8821
8822        public final void removeService(PackageParser.Service s) {
8823            mServices.remove(s.getComponentName());
8824            if (DEBUG_SHOW_INFO) {
8825                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8826                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8827                Log.v(TAG, "    Class=" + s.info.name);
8828            }
8829            final int NI = s.intents.size();
8830            int j;
8831            for (j=0; j<NI; j++) {
8832                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8833                if (DEBUG_SHOW_INFO) {
8834                    Log.v(TAG, "    IntentFilter:");
8835                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8836                }
8837                removeFilter(intent);
8838            }
8839        }
8840
8841        @Override
8842        protected boolean allowFilterResult(
8843                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8844            ServiceInfo filterSi = filter.service.info;
8845            for (int i=dest.size()-1; i>=0; i--) {
8846                ServiceInfo destAi = dest.get(i).serviceInfo;
8847                if (destAi.name == filterSi.name
8848                        && destAi.packageName == filterSi.packageName) {
8849                    return false;
8850                }
8851            }
8852            return true;
8853        }
8854
8855        @Override
8856        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8857            return new PackageParser.ServiceIntentInfo[size];
8858        }
8859
8860        @Override
8861        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8862            if (!sUserManager.exists(userId)) return true;
8863            PackageParser.Package p = filter.service.owner;
8864            if (p != null) {
8865                PackageSetting ps = (PackageSetting)p.mExtras;
8866                if (ps != null) {
8867                    // System apps are never considered stopped for purposes of
8868                    // filtering, because there may be no way for the user to
8869                    // actually re-launch them.
8870                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8871                            && ps.getStopped(userId);
8872                }
8873            }
8874            return false;
8875        }
8876
8877        @Override
8878        protected boolean isPackageForFilter(String packageName,
8879                PackageParser.ServiceIntentInfo info) {
8880            return packageName.equals(info.service.owner.packageName);
8881        }
8882
8883        @Override
8884        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8885                int match, int userId) {
8886            if (!sUserManager.exists(userId)) return null;
8887            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8888            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8889                return null;
8890            }
8891            final PackageParser.Service service = info.service;
8892            if (mSafeMode && (service.info.applicationInfo.flags
8893                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8894                return null;
8895            }
8896            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8897            if (ps == null) {
8898                return null;
8899            }
8900            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8901                    ps.readUserState(userId), userId);
8902            if (si == null) {
8903                return null;
8904            }
8905            final ResolveInfo res = new ResolveInfo();
8906            res.serviceInfo = si;
8907            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8908                res.filter = filter;
8909            }
8910            res.priority = info.getPriority();
8911            res.preferredOrder = service.owner.mPreferredOrder;
8912            res.match = match;
8913            res.isDefault = info.hasDefault;
8914            res.labelRes = info.labelRes;
8915            res.nonLocalizedLabel = info.nonLocalizedLabel;
8916            res.icon = info.icon;
8917            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8918            return res;
8919        }
8920
8921        @Override
8922        protected void sortResults(List<ResolveInfo> results) {
8923            Collections.sort(results, mResolvePrioritySorter);
8924        }
8925
8926        @Override
8927        protected void dumpFilter(PrintWriter out, String prefix,
8928                PackageParser.ServiceIntentInfo filter) {
8929            out.print(prefix); out.print(
8930                    Integer.toHexString(System.identityHashCode(filter.service)));
8931                    out.print(' ');
8932                    filter.service.printComponentShortName(out);
8933                    out.print(" filter ");
8934                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8935        }
8936
8937        @Override
8938        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8939            return filter.service;
8940        }
8941
8942        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8943            PackageParser.Service service = (PackageParser.Service)label;
8944            out.print(prefix); out.print(
8945                    Integer.toHexString(System.identityHashCode(service)));
8946                    out.print(' ');
8947                    service.printComponentShortName(out);
8948            if (count > 1) {
8949                out.print(" ("); out.print(count); out.print(" filters)");
8950            }
8951            out.println();
8952        }
8953
8954//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8955//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8956//            final List<ResolveInfo> retList = Lists.newArrayList();
8957//            while (i.hasNext()) {
8958//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8959//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8960//                    retList.add(resolveInfo);
8961//                }
8962//            }
8963//            return retList;
8964//        }
8965
8966        // Keys are String (activity class name), values are Activity.
8967        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8968                = new ArrayMap<ComponentName, PackageParser.Service>();
8969        private int mFlags;
8970    };
8971
8972    private final class ProviderIntentResolver
8973            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8974        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8975                boolean defaultOnly, int userId) {
8976            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8977            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8978        }
8979
8980        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8981                int userId) {
8982            if (!sUserManager.exists(userId))
8983                return null;
8984            mFlags = flags;
8985            return super.queryIntent(intent, resolvedType,
8986                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8987        }
8988
8989        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8990                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8991            if (!sUserManager.exists(userId))
8992                return null;
8993            if (packageProviders == null) {
8994                return null;
8995            }
8996            mFlags = flags;
8997            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8998            final int N = packageProviders.size();
8999            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9000                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9001
9002            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9003            for (int i = 0; i < N; ++i) {
9004                intentFilters = packageProviders.get(i).intents;
9005                if (intentFilters != null && intentFilters.size() > 0) {
9006                    PackageParser.ProviderIntentInfo[] array =
9007                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9008                    intentFilters.toArray(array);
9009                    listCut.add(array);
9010                }
9011            }
9012            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9013        }
9014
9015        public final void addProvider(PackageParser.Provider p) {
9016            if (mProviders.containsKey(p.getComponentName())) {
9017                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9018                return;
9019            }
9020
9021            mProviders.put(p.getComponentName(), p);
9022            if (DEBUG_SHOW_INFO) {
9023                Log.v(TAG, "  "
9024                        + (p.info.nonLocalizedLabel != null
9025                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9026                Log.v(TAG, "    Class=" + p.info.name);
9027            }
9028            final int NI = p.intents.size();
9029            int j;
9030            for (j = 0; j < NI; j++) {
9031                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9032                if (DEBUG_SHOW_INFO) {
9033                    Log.v(TAG, "    IntentFilter:");
9034                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9035                }
9036                if (!intent.debugCheck()) {
9037                    Log.w(TAG, "==> For Provider " + p.info.name);
9038                }
9039                addFilter(intent);
9040            }
9041        }
9042
9043        public final void removeProvider(PackageParser.Provider p) {
9044            mProviders.remove(p.getComponentName());
9045            if (DEBUG_SHOW_INFO) {
9046                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9047                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9048                Log.v(TAG, "    Class=" + p.info.name);
9049            }
9050            final int NI = p.intents.size();
9051            int j;
9052            for (j = 0; j < NI; j++) {
9053                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9054                if (DEBUG_SHOW_INFO) {
9055                    Log.v(TAG, "    IntentFilter:");
9056                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9057                }
9058                removeFilter(intent);
9059            }
9060        }
9061
9062        @Override
9063        protected boolean allowFilterResult(
9064                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9065            ProviderInfo filterPi = filter.provider.info;
9066            for (int i = dest.size() - 1; i >= 0; i--) {
9067                ProviderInfo destPi = dest.get(i).providerInfo;
9068                if (destPi.name == filterPi.name
9069                        && destPi.packageName == filterPi.packageName) {
9070                    return false;
9071                }
9072            }
9073            return true;
9074        }
9075
9076        @Override
9077        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9078            return new PackageParser.ProviderIntentInfo[size];
9079        }
9080
9081        @Override
9082        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9083            if (!sUserManager.exists(userId))
9084                return true;
9085            PackageParser.Package p = filter.provider.owner;
9086            if (p != null) {
9087                PackageSetting ps = (PackageSetting) p.mExtras;
9088                if (ps != null) {
9089                    // System apps are never considered stopped for purposes of
9090                    // filtering, because there may be no way for the user to
9091                    // actually re-launch them.
9092                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9093                            && ps.getStopped(userId);
9094                }
9095            }
9096            return false;
9097        }
9098
9099        @Override
9100        protected boolean isPackageForFilter(String packageName,
9101                PackageParser.ProviderIntentInfo info) {
9102            return packageName.equals(info.provider.owner.packageName);
9103        }
9104
9105        @Override
9106        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9107                int match, int userId) {
9108            if (!sUserManager.exists(userId))
9109                return null;
9110            final PackageParser.ProviderIntentInfo info = filter;
9111            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9112                return null;
9113            }
9114            final PackageParser.Provider provider = info.provider;
9115            if (mSafeMode && (provider.info.applicationInfo.flags
9116                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9117                return null;
9118            }
9119            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9120            if (ps == null) {
9121                return null;
9122            }
9123            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9124                    ps.readUserState(userId), userId);
9125            if (pi == null) {
9126                return null;
9127            }
9128            final ResolveInfo res = new ResolveInfo();
9129            res.providerInfo = pi;
9130            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9131                res.filter = filter;
9132            }
9133            res.priority = info.getPriority();
9134            res.preferredOrder = provider.owner.mPreferredOrder;
9135            res.match = match;
9136            res.isDefault = info.hasDefault;
9137            res.labelRes = info.labelRes;
9138            res.nonLocalizedLabel = info.nonLocalizedLabel;
9139            res.icon = info.icon;
9140            res.system = res.providerInfo.applicationInfo.isSystemApp();
9141            return res;
9142        }
9143
9144        @Override
9145        protected void sortResults(List<ResolveInfo> results) {
9146            Collections.sort(results, mResolvePrioritySorter);
9147        }
9148
9149        @Override
9150        protected void dumpFilter(PrintWriter out, String prefix,
9151                PackageParser.ProviderIntentInfo filter) {
9152            out.print(prefix);
9153            out.print(
9154                    Integer.toHexString(System.identityHashCode(filter.provider)));
9155            out.print(' ');
9156            filter.provider.printComponentShortName(out);
9157            out.print(" filter ");
9158            out.println(Integer.toHexString(System.identityHashCode(filter)));
9159        }
9160
9161        @Override
9162        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9163            return filter.provider;
9164        }
9165
9166        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9167            PackageParser.Provider provider = (PackageParser.Provider)label;
9168            out.print(prefix); out.print(
9169                    Integer.toHexString(System.identityHashCode(provider)));
9170                    out.print(' ');
9171                    provider.printComponentShortName(out);
9172            if (count > 1) {
9173                out.print(" ("); out.print(count); out.print(" filters)");
9174            }
9175            out.println();
9176        }
9177
9178        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9179                = new ArrayMap<ComponentName, PackageParser.Provider>();
9180        private int mFlags;
9181    };
9182
9183    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9184            new Comparator<ResolveInfo>() {
9185        public int compare(ResolveInfo r1, ResolveInfo r2) {
9186            int v1 = r1.priority;
9187            int v2 = r2.priority;
9188            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9189            if (v1 != v2) {
9190                return (v1 > v2) ? -1 : 1;
9191            }
9192            v1 = r1.preferredOrder;
9193            v2 = r2.preferredOrder;
9194            if (v1 != v2) {
9195                return (v1 > v2) ? -1 : 1;
9196            }
9197            if (r1.isDefault != r2.isDefault) {
9198                return r1.isDefault ? -1 : 1;
9199            }
9200            v1 = r1.match;
9201            v2 = r2.match;
9202            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9203            if (v1 != v2) {
9204                return (v1 > v2) ? -1 : 1;
9205            }
9206            if (r1.system != r2.system) {
9207                return r1.system ? -1 : 1;
9208            }
9209            return 0;
9210        }
9211    };
9212
9213    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9214            new Comparator<ProviderInfo>() {
9215        public int compare(ProviderInfo p1, ProviderInfo p2) {
9216            final int v1 = p1.initOrder;
9217            final int v2 = p2.initOrder;
9218            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9219        }
9220    };
9221
9222    final void sendPackageBroadcast(final String action, final String pkg,
9223            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9224            final int[] userIds) {
9225        mHandler.post(new Runnable() {
9226            @Override
9227            public void run() {
9228                try {
9229                    final IActivityManager am = ActivityManagerNative.getDefault();
9230                    if (am == null) return;
9231                    final int[] resolvedUserIds;
9232                    if (userIds == null) {
9233                        resolvedUserIds = am.getRunningUserIds();
9234                    } else {
9235                        resolvedUserIds = userIds;
9236                    }
9237                    for (int id : resolvedUserIds) {
9238                        final Intent intent = new Intent(action,
9239                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9240                        if (extras != null) {
9241                            intent.putExtras(extras);
9242                        }
9243                        if (targetPkg != null) {
9244                            intent.setPackage(targetPkg);
9245                        }
9246                        // Modify the UID when posting to other users
9247                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9248                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9249                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9250                            intent.putExtra(Intent.EXTRA_UID, uid);
9251                        }
9252                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9253                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9254                        if (DEBUG_BROADCASTS) {
9255                            RuntimeException here = new RuntimeException("here");
9256                            here.fillInStackTrace();
9257                            Slog.d(TAG, "Sending to user " + id + ": "
9258                                    + intent.toShortString(false, true, false, false)
9259                                    + " " + intent.getExtras(), here);
9260                        }
9261                        am.broadcastIntent(null, intent, null, finishedReceiver,
9262                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9263                                null, finishedReceiver != null, false, id);
9264                    }
9265                } catch (RemoteException ex) {
9266                }
9267            }
9268        });
9269    }
9270
9271    /**
9272     * Check if the external storage media is available. This is true if there
9273     * is a mounted external storage medium or if the external storage is
9274     * emulated.
9275     */
9276    private boolean isExternalMediaAvailable() {
9277        return mMediaMounted || Environment.isExternalStorageEmulated();
9278    }
9279
9280    @Override
9281    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9282        // writer
9283        synchronized (mPackages) {
9284            if (!isExternalMediaAvailable()) {
9285                // If the external storage is no longer mounted at this point,
9286                // the caller may not have been able to delete all of this
9287                // packages files and can not delete any more.  Bail.
9288                return null;
9289            }
9290            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9291            if (lastPackage != null) {
9292                pkgs.remove(lastPackage);
9293            }
9294            if (pkgs.size() > 0) {
9295                return pkgs.get(0);
9296            }
9297        }
9298        return null;
9299    }
9300
9301    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9302        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9303                userId, andCode ? 1 : 0, packageName);
9304        if (mSystemReady) {
9305            msg.sendToTarget();
9306        } else {
9307            if (mPostSystemReadyMessages == null) {
9308                mPostSystemReadyMessages = new ArrayList<>();
9309            }
9310            mPostSystemReadyMessages.add(msg);
9311        }
9312    }
9313
9314    void startCleaningPackages() {
9315        // reader
9316        synchronized (mPackages) {
9317            if (!isExternalMediaAvailable()) {
9318                return;
9319            }
9320            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9321                return;
9322            }
9323        }
9324        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9325        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9326        IActivityManager am = ActivityManagerNative.getDefault();
9327        if (am != null) {
9328            try {
9329                am.startService(null, intent, null, mContext.getOpPackageName(),
9330                        UserHandle.USER_OWNER);
9331            } catch (RemoteException e) {
9332            }
9333        }
9334    }
9335
9336    @Override
9337    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9338            int installFlags, String installerPackageName, VerificationParams verificationParams,
9339            String packageAbiOverride) {
9340        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9341                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9342    }
9343
9344    @Override
9345    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9346            int installFlags, String installerPackageName, VerificationParams verificationParams,
9347            String packageAbiOverride, int userId) {
9348        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9349
9350        final int callingUid = Binder.getCallingUid();
9351        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9352
9353        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9354            try {
9355                if (observer != null) {
9356                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9357                }
9358            } catch (RemoteException re) {
9359            }
9360            return;
9361        }
9362
9363        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9364            installFlags |= PackageManager.INSTALL_FROM_ADB;
9365
9366        } else {
9367            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9368            // about installerPackageName.
9369
9370            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9371            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9372        }
9373
9374        UserHandle user;
9375        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9376            user = UserHandle.ALL;
9377        } else {
9378            user = new UserHandle(userId);
9379        }
9380
9381        // Only system components can circumvent runtime permissions when installing.
9382        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9383                && mContext.checkCallingOrSelfPermission(Manifest.permission
9384                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9385            throw new SecurityException("You need the "
9386                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9387                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9388        }
9389
9390        verificationParams.setInstallerUid(callingUid);
9391
9392        final File originFile = new File(originPath);
9393        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9394
9395        final Message msg = mHandler.obtainMessage(INIT_COPY);
9396        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9397                null, verificationParams, user, packageAbiOverride);
9398        mHandler.sendMessage(msg);
9399    }
9400
9401    void installStage(String packageName, File stagedDir, String stagedCid,
9402            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9403            String installerPackageName, int installerUid, UserHandle user) {
9404        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9405                params.referrerUri, installerUid, null);
9406        verifParams.setInstallerUid(installerUid);
9407
9408        final OriginInfo origin;
9409        if (stagedDir != null) {
9410            origin = OriginInfo.fromStagedFile(stagedDir);
9411        } else {
9412            origin = OriginInfo.fromStagedContainer(stagedCid);
9413        }
9414
9415        final Message msg = mHandler.obtainMessage(INIT_COPY);
9416        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9417                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9418        mHandler.sendMessage(msg);
9419    }
9420
9421    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9422        Bundle extras = new Bundle(1);
9423        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9424
9425        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9426                packageName, extras, null, null, new int[] {userId});
9427        try {
9428            IActivityManager am = ActivityManagerNative.getDefault();
9429            final boolean isSystem =
9430                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9431            if (isSystem && am.isUserRunning(userId, false)) {
9432                // The just-installed/enabled app is bundled on the system, so presumed
9433                // to be able to run automatically without needing an explicit launch.
9434                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9435                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9436                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9437                        .setPackage(packageName);
9438                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9439                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9440            }
9441        } catch (RemoteException e) {
9442            // shouldn't happen
9443            Slog.w(TAG, "Unable to bootstrap installed package", e);
9444        }
9445    }
9446
9447    @Override
9448    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9449            int userId) {
9450        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9451        PackageSetting pkgSetting;
9452        final int uid = Binder.getCallingUid();
9453        enforceCrossUserPermission(uid, userId, true, true,
9454                "setApplicationHiddenSetting for user " + userId);
9455
9456        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9457            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9458            return false;
9459        }
9460
9461        long callingId = Binder.clearCallingIdentity();
9462        try {
9463            boolean sendAdded = false;
9464            boolean sendRemoved = false;
9465            // writer
9466            synchronized (mPackages) {
9467                pkgSetting = mSettings.mPackages.get(packageName);
9468                if (pkgSetting == null) {
9469                    return false;
9470                }
9471                if (pkgSetting.getHidden(userId) != hidden) {
9472                    pkgSetting.setHidden(hidden, userId);
9473                    mSettings.writePackageRestrictionsLPr(userId);
9474                    if (hidden) {
9475                        sendRemoved = true;
9476                    } else {
9477                        sendAdded = true;
9478                    }
9479                }
9480            }
9481            if (sendAdded) {
9482                sendPackageAddedForUser(packageName, pkgSetting, userId);
9483                return true;
9484            }
9485            if (sendRemoved) {
9486                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9487                        "hiding pkg");
9488                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9489            }
9490        } finally {
9491            Binder.restoreCallingIdentity(callingId);
9492        }
9493        return false;
9494    }
9495
9496    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9497            int userId) {
9498        final PackageRemovedInfo info = new PackageRemovedInfo();
9499        info.removedPackage = packageName;
9500        info.removedUsers = new int[] {userId};
9501        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9502        info.sendBroadcast(false, false, false);
9503    }
9504
9505    /**
9506     * Returns true if application is not found or there was an error. Otherwise it returns
9507     * the hidden state of the package for the given user.
9508     */
9509    @Override
9510    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9511        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9512        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9513                false, "getApplicationHidden for user " + userId);
9514        PackageSetting pkgSetting;
9515        long callingId = Binder.clearCallingIdentity();
9516        try {
9517            // writer
9518            synchronized (mPackages) {
9519                pkgSetting = mSettings.mPackages.get(packageName);
9520                if (pkgSetting == null) {
9521                    return true;
9522                }
9523                return pkgSetting.getHidden(userId);
9524            }
9525        } finally {
9526            Binder.restoreCallingIdentity(callingId);
9527        }
9528    }
9529
9530    /**
9531     * @hide
9532     */
9533    @Override
9534    public int installExistingPackageAsUser(String packageName, int userId) {
9535        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9536                null);
9537        PackageSetting pkgSetting;
9538        final int uid = Binder.getCallingUid();
9539        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9540                + userId);
9541        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9542            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9543        }
9544
9545        long callingId = Binder.clearCallingIdentity();
9546        try {
9547            boolean sendAdded = false;
9548
9549            // writer
9550            synchronized (mPackages) {
9551                pkgSetting = mSettings.mPackages.get(packageName);
9552                if (pkgSetting == null) {
9553                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9554                }
9555                if (!pkgSetting.getInstalled(userId)) {
9556                    pkgSetting.setInstalled(true, userId);
9557                    pkgSetting.setHidden(false, userId);
9558                    mSettings.writePackageRestrictionsLPr(userId);
9559                    sendAdded = true;
9560                }
9561            }
9562
9563            if (sendAdded) {
9564                sendPackageAddedForUser(packageName, pkgSetting, userId);
9565            }
9566        } finally {
9567            Binder.restoreCallingIdentity(callingId);
9568        }
9569
9570        return PackageManager.INSTALL_SUCCEEDED;
9571    }
9572
9573    boolean isUserRestricted(int userId, String restrictionKey) {
9574        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9575        if (restrictions.getBoolean(restrictionKey, false)) {
9576            Log.w(TAG, "User is restricted: " + restrictionKey);
9577            return true;
9578        }
9579        return false;
9580    }
9581
9582    @Override
9583    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9584        mContext.enforceCallingOrSelfPermission(
9585                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9586                "Only package verification agents can verify applications");
9587
9588        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9589        final PackageVerificationResponse response = new PackageVerificationResponse(
9590                verificationCode, Binder.getCallingUid());
9591        msg.arg1 = id;
9592        msg.obj = response;
9593        mHandler.sendMessage(msg);
9594    }
9595
9596    @Override
9597    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9598            long millisecondsToDelay) {
9599        mContext.enforceCallingOrSelfPermission(
9600                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9601                "Only package verification agents can extend verification timeouts");
9602
9603        final PackageVerificationState state = mPendingVerification.get(id);
9604        final PackageVerificationResponse response = new PackageVerificationResponse(
9605                verificationCodeAtTimeout, Binder.getCallingUid());
9606
9607        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9608            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9609        }
9610        if (millisecondsToDelay < 0) {
9611            millisecondsToDelay = 0;
9612        }
9613        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9614                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9615            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9616        }
9617
9618        if ((state != null) && !state.timeoutExtended()) {
9619            state.extendTimeout();
9620
9621            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9622            msg.arg1 = id;
9623            msg.obj = response;
9624            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9625        }
9626    }
9627
9628    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9629            int verificationCode, UserHandle user) {
9630        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9631        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9632        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9633        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9634        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9635
9636        mContext.sendBroadcastAsUser(intent, user,
9637                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9638    }
9639
9640    private ComponentName matchComponentForVerifier(String packageName,
9641            List<ResolveInfo> receivers) {
9642        ActivityInfo targetReceiver = null;
9643
9644        final int NR = receivers.size();
9645        for (int i = 0; i < NR; i++) {
9646            final ResolveInfo info = receivers.get(i);
9647            if (info.activityInfo == null) {
9648                continue;
9649            }
9650
9651            if (packageName.equals(info.activityInfo.packageName)) {
9652                targetReceiver = info.activityInfo;
9653                break;
9654            }
9655        }
9656
9657        if (targetReceiver == null) {
9658            return null;
9659        }
9660
9661        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9662    }
9663
9664    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9665            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9666        if (pkgInfo.verifiers.length == 0) {
9667            return null;
9668        }
9669
9670        final int N = pkgInfo.verifiers.length;
9671        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9672        for (int i = 0; i < N; i++) {
9673            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9674
9675            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9676                    receivers);
9677            if (comp == null) {
9678                continue;
9679            }
9680
9681            final int verifierUid = getUidForVerifier(verifierInfo);
9682            if (verifierUid == -1) {
9683                continue;
9684            }
9685
9686            if (DEBUG_VERIFY) {
9687                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9688                        + " with the correct signature");
9689            }
9690            sufficientVerifiers.add(comp);
9691            verificationState.addSufficientVerifier(verifierUid);
9692        }
9693
9694        return sufficientVerifiers;
9695    }
9696
9697    private int getUidForVerifier(VerifierInfo verifierInfo) {
9698        synchronized (mPackages) {
9699            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9700            if (pkg == null) {
9701                return -1;
9702            } else if (pkg.mSignatures.length != 1) {
9703                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9704                        + " has more than one signature; ignoring");
9705                return -1;
9706            }
9707
9708            /*
9709             * If the public key of the package's signature does not match
9710             * our expected public key, then this is a different package and
9711             * we should skip.
9712             */
9713
9714            final byte[] expectedPublicKey;
9715            try {
9716                final Signature verifierSig = pkg.mSignatures[0];
9717                final PublicKey publicKey = verifierSig.getPublicKey();
9718                expectedPublicKey = publicKey.getEncoded();
9719            } catch (CertificateException e) {
9720                return -1;
9721            }
9722
9723            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9724
9725            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9726                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9727                        + " does not have the expected public key; ignoring");
9728                return -1;
9729            }
9730
9731            return pkg.applicationInfo.uid;
9732        }
9733    }
9734
9735    @Override
9736    public void finishPackageInstall(int token) {
9737        enforceSystemOrRoot("Only the system is allowed to finish installs");
9738
9739        if (DEBUG_INSTALL) {
9740            Slog.v(TAG, "BM finishing package install for " + token);
9741        }
9742
9743        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9744        mHandler.sendMessage(msg);
9745    }
9746
9747    /**
9748     * Get the verification agent timeout.
9749     *
9750     * @return verification timeout in milliseconds
9751     */
9752    private long getVerificationTimeout() {
9753        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9754                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9755                DEFAULT_VERIFICATION_TIMEOUT);
9756    }
9757
9758    /**
9759     * Get the default verification agent response code.
9760     *
9761     * @return default verification response code
9762     */
9763    private int getDefaultVerificationResponse() {
9764        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9765                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9766                DEFAULT_VERIFICATION_RESPONSE);
9767    }
9768
9769    /**
9770     * Check whether or not package verification has been enabled.
9771     *
9772     * @return true if verification should be performed
9773     */
9774    private boolean isVerificationEnabled(int userId, int installFlags) {
9775        if (!DEFAULT_VERIFY_ENABLE) {
9776            return false;
9777        }
9778
9779        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9780
9781        // Check if installing from ADB
9782        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9783            // Do not run verification in a test harness environment
9784            if (ActivityManager.isRunningInTestHarness()) {
9785                return false;
9786            }
9787            if (ensureVerifyAppsEnabled) {
9788                return true;
9789            }
9790            // Check if the developer does not want package verification for ADB installs
9791            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9792                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9793                return false;
9794            }
9795        }
9796
9797        if (ensureVerifyAppsEnabled) {
9798            return true;
9799        }
9800
9801        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9802                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9803    }
9804
9805    @Override
9806    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9807            throws RemoteException {
9808        mContext.enforceCallingOrSelfPermission(
9809                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9810                "Only intentfilter verification agents can verify applications");
9811
9812        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9813        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9814                Binder.getCallingUid(), verificationCode, failedDomains);
9815        msg.arg1 = id;
9816        msg.obj = response;
9817        mHandler.sendMessage(msg);
9818    }
9819
9820    @Override
9821    public int getIntentVerificationStatus(String packageName, int userId) {
9822        synchronized (mPackages) {
9823            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9824        }
9825    }
9826
9827    @Override
9828    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9829        mContext.enforceCallingOrSelfPermission(
9830                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9831
9832        boolean result = false;
9833        synchronized (mPackages) {
9834            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9835        }
9836        if (result) {
9837            scheduleWritePackageRestrictionsLocked(userId);
9838        }
9839        return result;
9840    }
9841
9842    @Override
9843    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9844        synchronized (mPackages) {
9845            return mSettings.getIntentFilterVerificationsLPr(packageName);
9846        }
9847    }
9848
9849    @Override
9850    public List<IntentFilter> getAllIntentFilters(String packageName) {
9851        if (TextUtils.isEmpty(packageName)) {
9852            return Collections.<IntentFilter>emptyList();
9853        }
9854        synchronized (mPackages) {
9855            PackageParser.Package pkg = mPackages.get(packageName);
9856            if (pkg == null || pkg.activities == null) {
9857                return Collections.<IntentFilter>emptyList();
9858            }
9859            final int count = pkg.activities.size();
9860            ArrayList<IntentFilter> result = new ArrayList<>();
9861            for (int n=0; n<count; n++) {
9862                PackageParser.Activity activity = pkg.activities.get(n);
9863                if (activity.intents != null || activity.intents.size() > 0) {
9864                    result.addAll(activity.intents);
9865                }
9866            }
9867            return result;
9868        }
9869    }
9870
9871    @Override
9872    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9873        mContext.enforceCallingOrSelfPermission(
9874                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9875
9876        synchronized (mPackages) {
9877            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9878            if (packageName != null) {
9879                result |= updateIntentVerificationStatus(packageName,
9880                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9881                        UserHandle.myUserId());
9882                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9883                        packageName, userId);
9884            }
9885            return result;
9886        }
9887    }
9888
9889    @Override
9890    public String getDefaultBrowserPackageName(int userId) {
9891        synchronized (mPackages) {
9892            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9893        }
9894    }
9895
9896    /**
9897     * Get the "allow unknown sources" setting.
9898     *
9899     * @return the current "allow unknown sources" setting
9900     */
9901    private int getUnknownSourcesSettings() {
9902        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9903                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9904                -1);
9905    }
9906
9907    @Override
9908    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9909        final int uid = Binder.getCallingUid();
9910        // writer
9911        synchronized (mPackages) {
9912            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9913            if (targetPackageSetting == null) {
9914                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9915            }
9916
9917            PackageSetting installerPackageSetting;
9918            if (installerPackageName != null) {
9919                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9920                if (installerPackageSetting == null) {
9921                    throw new IllegalArgumentException("Unknown installer package: "
9922                            + installerPackageName);
9923                }
9924            } else {
9925                installerPackageSetting = null;
9926            }
9927
9928            Signature[] callerSignature;
9929            Object obj = mSettings.getUserIdLPr(uid);
9930            if (obj != null) {
9931                if (obj instanceof SharedUserSetting) {
9932                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9933                } else if (obj instanceof PackageSetting) {
9934                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9935                } else {
9936                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9937                }
9938            } else {
9939                throw new SecurityException("Unknown calling uid " + uid);
9940            }
9941
9942            // Verify: can't set installerPackageName to a package that is
9943            // not signed with the same cert as the caller.
9944            if (installerPackageSetting != null) {
9945                if (compareSignatures(callerSignature,
9946                        installerPackageSetting.signatures.mSignatures)
9947                        != PackageManager.SIGNATURE_MATCH) {
9948                    throw new SecurityException(
9949                            "Caller does not have same cert as new installer package "
9950                            + installerPackageName);
9951                }
9952            }
9953
9954            // Verify: if target already has an installer package, it must
9955            // be signed with the same cert as the caller.
9956            if (targetPackageSetting.installerPackageName != null) {
9957                PackageSetting setting = mSettings.mPackages.get(
9958                        targetPackageSetting.installerPackageName);
9959                // If the currently set package isn't valid, then it's always
9960                // okay to change it.
9961                if (setting != null) {
9962                    if (compareSignatures(callerSignature,
9963                            setting.signatures.mSignatures)
9964                            != PackageManager.SIGNATURE_MATCH) {
9965                        throw new SecurityException(
9966                                "Caller does not have same cert as old installer package "
9967                                + targetPackageSetting.installerPackageName);
9968                    }
9969                }
9970            }
9971
9972            // Okay!
9973            targetPackageSetting.installerPackageName = installerPackageName;
9974            scheduleWriteSettingsLocked();
9975        }
9976    }
9977
9978    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9979        // Queue up an async operation since the package installation may take a little while.
9980        mHandler.post(new Runnable() {
9981            public void run() {
9982                mHandler.removeCallbacks(this);
9983                 // Result object to be returned
9984                PackageInstalledInfo res = new PackageInstalledInfo();
9985                res.returnCode = currentStatus;
9986                res.uid = -1;
9987                res.pkg = null;
9988                res.removedInfo = new PackageRemovedInfo();
9989                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9990                    args.doPreInstall(res.returnCode);
9991                    synchronized (mInstallLock) {
9992                        installPackageLI(args, res);
9993                    }
9994                    args.doPostInstall(res.returnCode, res.uid);
9995                }
9996
9997                // A restore should be performed at this point if (a) the install
9998                // succeeded, (b) the operation is not an update, and (c) the new
9999                // package has not opted out of backup participation.
10000                final boolean update = res.removedInfo.removedPackage != null;
10001                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10002                boolean doRestore = !update
10003                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10004
10005                // Set up the post-install work request bookkeeping.  This will be used
10006                // and cleaned up by the post-install event handling regardless of whether
10007                // there's a restore pass performed.  Token values are >= 1.
10008                int token;
10009                if (mNextInstallToken < 0) mNextInstallToken = 1;
10010                token = mNextInstallToken++;
10011
10012                PostInstallData data = new PostInstallData(args, res);
10013                mRunningInstalls.put(token, data);
10014                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10015
10016                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10017                    // Pass responsibility to the Backup Manager.  It will perform a
10018                    // restore if appropriate, then pass responsibility back to the
10019                    // Package Manager to run the post-install observer callbacks
10020                    // and broadcasts.
10021                    IBackupManager bm = IBackupManager.Stub.asInterface(
10022                            ServiceManager.getService(Context.BACKUP_SERVICE));
10023                    if (bm != null) {
10024                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10025                                + " to BM for possible restore");
10026                        try {
10027                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10028                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10029                            } else {
10030                                doRestore = false;
10031                            }
10032                        } catch (RemoteException e) {
10033                            // can't happen; the backup manager is local
10034                        } catch (Exception e) {
10035                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10036                            doRestore = false;
10037                        }
10038                    } else {
10039                        Slog.e(TAG, "Backup Manager not found!");
10040                        doRestore = false;
10041                    }
10042                }
10043
10044                if (!doRestore) {
10045                    // No restore possible, or the Backup Manager was mysteriously not
10046                    // available -- just fire the post-install work request directly.
10047                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10048                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10049                    mHandler.sendMessage(msg);
10050                }
10051            }
10052        });
10053    }
10054
10055    private abstract class HandlerParams {
10056        private static final int MAX_RETRIES = 4;
10057
10058        /**
10059         * Number of times startCopy() has been attempted and had a non-fatal
10060         * error.
10061         */
10062        private int mRetries = 0;
10063
10064        /** User handle for the user requesting the information or installation. */
10065        private final UserHandle mUser;
10066
10067        HandlerParams(UserHandle user) {
10068            mUser = user;
10069        }
10070
10071        UserHandle getUser() {
10072            return mUser;
10073        }
10074
10075        final boolean startCopy() {
10076            boolean res;
10077            try {
10078                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10079
10080                if (++mRetries > MAX_RETRIES) {
10081                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10082                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10083                    handleServiceError();
10084                    return false;
10085                } else {
10086                    handleStartCopy();
10087                    res = true;
10088                }
10089            } catch (RemoteException e) {
10090                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10091                mHandler.sendEmptyMessage(MCS_RECONNECT);
10092                res = false;
10093            }
10094            handleReturnCode();
10095            return res;
10096        }
10097
10098        final void serviceError() {
10099            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10100            handleServiceError();
10101            handleReturnCode();
10102        }
10103
10104        abstract void handleStartCopy() throws RemoteException;
10105        abstract void handleServiceError();
10106        abstract void handleReturnCode();
10107    }
10108
10109    class MeasureParams extends HandlerParams {
10110        private final PackageStats mStats;
10111        private boolean mSuccess;
10112
10113        private final IPackageStatsObserver mObserver;
10114
10115        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10116            super(new UserHandle(stats.userHandle));
10117            mObserver = observer;
10118            mStats = stats;
10119        }
10120
10121        @Override
10122        public String toString() {
10123            return "MeasureParams{"
10124                + Integer.toHexString(System.identityHashCode(this))
10125                + " " + mStats.packageName + "}";
10126        }
10127
10128        @Override
10129        void handleStartCopy() throws RemoteException {
10130            synchronized (mInstallLock) {
10131                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10132            }
10133
10134            if (mSuccess) {
10135                final boolean mounted;
10136                if (Environment.isExternalStorageEmulated()) {
10137                    mounted = true;
10138                } else {
10139                    final String status = Environment.getExternalStorageState();
10140                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10141                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10142                }
10143
10144                if (mounted) {
10145                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10146
10147                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10148                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10149
10150                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10151                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10152
10153                    // Always subtract cache size, since it's a subdirectory
10154                    mStats.externalDataSize -= mStats.externalCacheSize;
10155
10156                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10157                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10158
10159                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10160                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10161                }
10162            }
10163        }
10164
10165        @Override
10166        void handleReturnCode() {
10167            if (mObserver != null) {
10168                try {
10169                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10170                } catch (RemoteException e) {
10171                    Slog.i(TAG, "Observer no longer exists.");
10172                }
10173            }
10174        }
10175
10176        @Override
10177        void handleServiceError() {
10178            Slog.e(TAG, "Could not measure application " + mStats.packageName
10179                            + " external storage");
10180        }
10181    }
10182
10183    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10184            throws RemoteException {
10185        long result = 0;
10186        for (File path : paths) {
10187            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10188        }
10189        return result;
10190    }
10191
10192    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10193        for (File path : paths) {
10194            try {
10195                mcs.clearDirectory(path.getAbsolutePath());
10196            } catch (RemoteException e) {
10197            }
10198        }
10199    }
10200
10201    static class OriginInfo {
10202        /**
10203         * Location where install is coming from, before it has been
10204         * copied/renamed into place. This could be a single monolithic APK
10205         * file, or a cluster directory. This location may be untrusted.
10206         */
10207        final File file;
10208        final String cid;
10209
10210        /**
10211         * Flag indicating that {@link #file} or {@link #cid} has already been
10212         * staged, meaning downstream users don't need to defensively copy the
10213         * contents.
10214         */
10215        final boolean staged;
10216
10217        /**
10218         * Flag indicating that {@link #file} or {@link #cid} is an already
10219         * installed app that is being moved.
10220         */
10221        final boolean existing;
10222
10223        final String resolvedPath;
10224        final File resolvedFile;
10225
10226        static OriginInfo fromNothing() {
10227            return new OriginInfo(null, null, false, false);
10228        }
10229
10230        static OriginInfo fromUntrustedFile(File file) {
10231            return new OriginInfo(file, null, false, false);
10232        }
10233
10234        static OriginInfo fromExistingFile(File file) {
10235            return new OriginInfo(file, null, false, true);
10236        }
10237
10238        static OriginInfo fromStagedFile(File file) {
10239            return new OriginInfo(file, null, true, false);
10240        }
10241
10242        static OriginInfo fromStagedContainer(String cid) {
10243            return new OriginInfo(null, cid, true, false);
10244        }
10245
10246        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10247            this.file = file;
10248            this.cid = cid;
10249            this.staged = staged;
10250            this.existing = existing;
10251
10252            if (cid != null) {
10253                resolvedPath = PackageHelper.getSdDir(cid);
10254                resolvedFile = new File(resolvedPath);
10255            } else if (file != null) {
10256                resolvedPath = file.getAbsolutePath();
10257                resolvedFile = file;
10258            } else {
10259                resolvedPath = null;
10260                resolvedFile = null;
10261            }
10262        }
10263    }
10264
10265    class MoveInfo {
10266        final int moveId;
10267        final String fromUuid;
10268        final String toUuid;
10269        final String packageName;
10270        final String dataAppName;
10271        final int appId;
10272        final String seinfo;
10273
10274        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10275                String dataAppName, int appId, String seinfo) {
10276            this.moveId = moveId;
10277            this.fromUuid = fromUuid;
10278            this.toUuid = toUuid;
10279            this.packageName = packageName;
10280            this.dataAppName = dataAppName;
10281            this.appId = appId;
10282            this.seinfo = seinfo;
10283        }
10284    }
10285
10286    class InstallParams extends HandlerParams {
10287        final OriginInfo origin;
10288        final MoveInfo move;
10289        final IPackageInstallObserver2 observer;
10290        int installFlags;
10291        final String installerPackageName;
10292        final String volumeUuid;
10293        final VerificationParams verificationParams;
10294        private InstallArgs mArgs;
10295        private int mRet;
10296        final String packageAbiOverride;
10297
10298        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10299                int installFlags, String installerPackageName, String volumeUuid,
10300                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10301            super(user);
10302            this.origin = origin;
10303            this.move = move;
10304            this.observer = observer;
10305            this.installFlags = installFlags;
10306            this.installerPackageName = installerPackageName;
10307            this.volumeUuid = volumeUuid;
10308            this.verificationParams = verificationParams;
10309            this.packageAbiOverride = packageAbiOverride;
10310        }
10311
10312        @Override
10313        public String toString() {
10314            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10315                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10316        }
10317
10318        public ManifestDigest getManifestDigest() {
10319            if (verificationParams == null) {
10320                return null;
10321            }
10322            return verificationParams.getManifestDigest();
10323        }
10324
10325        private int installLocationPolicy(PackageInfoLite pkgLite) {
10326            String packageName = pkgLite.packageName;
10327            int installLocation = pkgLite.installLocation;
10328            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10329            // reader
10330            synchronized (mPackages) {
10331                PackageParser.Package pkg = mPackages.get(packageName);
10332                if (pkg != null) {
10333                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10334                        // Check for downgrading.
10335                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10336                            try {
10337                                checkDowngrade(pkg, pkgLite);
10338                            } catch (PackageManagerException e) {
10339                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10340                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10341                            }
10342                        }
10343                        // Check for updated system application.
10344                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10345                            if (onSd) {
10346                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10347                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10348                            }
10349                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10350                        } else {
10351                            if (onSd) {
10352                                // Install flag overrides everything.
10353                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10354                            }
10355                            // If current upgrade specifies particular preference
10356                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10357                                // Application explicitly specified internal.
10358                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10359                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10360                                // App explictly prefers external. Let policy decide
10361                            } else {
10362                                // Prefer previous location
10363                                if (isExternal(pkg)) {
10364                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10365                                }
10366                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10367                            }
10368                        }
10369                    } else {
10370                        // Invalid install. Return error code
10371                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10372                    }
10373                }
10374            }
10375            // All the special cases have been taken care of.
10376            // Return result based on recommended install location.
10377            if (onSd) {
10378                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10379            }
10380            return pkgLite.recommendedInstallLocation;
10381        }
10382
10383        /*
10384         * Invoke remote method to get package information and install
10385         * location values. Override install location based on default
10386         * policy if needed and then create install arguments based
10387         * on the install location.
10388         */
10389        public void handleStartCopy() throws RemoteException {
10390            int ret = PackageManager.INSTALL_SUCCEEDED;
10391
10392            // If we're already staged, we've firmly committed to an install location
10393            if (origin.staged) {
10394                if (origin.file != null) {
10395                    installFlags |= PackageManager.INSTALL_INTERNAL;
10396                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10397                } else if (origin.cid != null) {
10398                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10399                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10400                } else {
10401                    throw new IllegalStateException("Invalid stage location");
10402                }
10403            }
10404
10405            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10406            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10407
10408            PackageInfoLite pkgLite = null;
10409
10410            if (onInt && onSd) {
10411                // Check if both bits are set.
10412                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10413                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10414            } else {
10415                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10416                        packageAbiOverride);
10417
10418                /*
10419                 * If we have too little free space, try to free cache
10420                 * before giving up.
10421                 */
10422                if (!origin.staged && pkgLite.recommendedInstallLocation
10423                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10424                    // TODO: focus freeing disk space on the target device
10425                    final StorageManager storage = StorageManager.from(mContext);
10426                    final long lowThreshold = storage.getStorageLowBytes(
10427                            Environment.getDataDirectory());
10428
10429                    final long sizeBytes = mContainerService.calculateInstalledSize(
10430                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10431
10432                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10433                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10434                                installFlags, packageAbiOverride);
10435                    }
10436
10437                    /*
10438                     * The cache free must have deleted the file we
10439                     * downloaded to install.
10440                     *
10441                     * TODO: fix the "freeCache" call to not delete
10442                     *       the file we care about.
10443                     */
10444                    if (pkgLite.recommendedInstallLocation
10445                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10446                        pkgLite.recommendedInstallLocation
10447                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10448                    }
10449                }
10450            }
10451
10452            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10453                int loc = pkgLite.recommendedInstallLocation;
10454                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10455                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10456                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10457                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10458                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10459                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10460                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10461                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10462                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10463                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10464                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10465                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10466                } else {
10467                    // Override with defaults if needed.
10468                    loc = installLocationPolicy(pkgLite);
10469                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10470                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10471                    } else if (!onSd && !onInt) {
10472                        // Override install location with flags
10473                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10474                            // Set the flag to install on external media.
10475                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10476                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10477                        } else {
10478                            // Make sure the flag for installing on external
10479                            // media is unset
10480                            installFlags |= PackageManager.INSTALL_INTERNAL;
10481                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10482                        }
10483                    }
10484                }
10485            }
10486
10487            final InstallArgs args = createInstallArgs(this);
10488            mArgs = args;
10489
10490            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10491                 /*
10492                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10493                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10494                 */
10495                int userIdentifier = getUser().getIdentifier();
10496                if (userIdentifier == UserHandle.USER_ALL
10497                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10498                    userIdentifier = UserHandle.USER_OWNER;
10499                }
10500
10501                /*
10502                 * Determine if we have any installed package verifiers. If we
10503                 * do, then we'll defer to them to verify the packages.
10504                 */
10505                final int requiredUid = mRequiredVerifierPackage == null ? -1
10506                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10507                if (!origin.existing && requiredUid != -1
10508                        && isVerificationEnabled(userIdentifier, installFlags)) {
10509                    final Intent verification = new Intent(
10510                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10511                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10512                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10513                            PACKAGE_MIME_TYPE);
10514                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10515
10516                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10517                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10518                            0 /* TODO: Which userId? */);
10519
10520                    if (DEBUG_VERIFY) {
10521                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10522                                + verification.toString() + " with " + pkgLite.verifiers.length
10523                                + " optional verifiers");
10524                    }
10525
10526                    final int verificationId = mPendingVerificationToken++;
10527
10528                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10529
10530                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10531                            installerPackageName);
10532
10533                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10534                            installFlags);
10535
10536                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10537                            pkgLite.packageName);
10538
10539                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10540                            pkgLite.versionCode);
10541
10542                    if (verificationParams != null) {
10543                        if (verificationParams.getVerificationURI() != null) {
10544                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10545                                 verificationParams.getVerificationURI());
10546                        }
10547                        if (verificationParams.getOriginatingURI() != null) {
10548                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10549                                  verificationParams.getOriginatingURI());
10550                        }
10551                        if (verificationParams.getReferrer() != null) {
10552                            verification.putExtra(Intent.EXTRA_REFERRER,
10553                                  verificationParams.getReferrer());
10554                        }
10555                        if (verificationParams.getOriginatingUid() >= 0) {
10556                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10557                                  verificationParams.getOriginatingUid());
10558                        }
10559                        if (verificationParams.getInstallerUid() >= 0) {
10560                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10561                                  verificationParams.getInstallerUid());
10562                        }
10563                    }
10564
10565                    final PackageVerificationState verificationState = new PackageVerificationState(
10566                            requiredUid, args);
10567
10568                    mPendingVerification.append(verificationId, verificationState);
10569
10570                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10571                            receivers, verificationState);
10572
10573                    /*
10574                     * If any sufficient verifiers were listed in the package
10575                     * manifest, attempt to ask them.
10576                     */
10577                    if (sufficientVerifiers != null) {
10578                        final int N = sufficientVerifiers.size();
10579                        if (N == 0) {
10580                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10581                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10582                        } else {
10583                            for (int i = 0; i < N; i++) {
10584                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10585
10586                                final Intent sufficientIntent = new Intent(verification);
10587                                sufficientIntent.setComponent(verifierComponent);
10588
10589                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10590                            }
10591                        }
10592                    }
10593
10594                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10595                            mRequiredVerifierPackage, receivers);
10596                    if (ret == PackageManager.INSTALL_SUCCEEDED
10597                            && mRequiredVerifierPackage != null) {
10598                        /*
10599                         * Send the intent to the required verification agent,
10600                         * but only start the verification timeout after the
10601                         * target BroadcastReceivers have run.
10602                         */
10603                        verification.setComponent(requiredVerifierComponent);
10604                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10605                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10606                                new BroadcastReceiver() {
10607                                    @Override
10608                                    public void onReceive(Context context, Intent intent) {
10609                                        final Message msg = mHandler
10610                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10611                                        msg.arg1 = verificationId;
10612                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10613                                    }
10614                                }, null, 0, null, null);
10615
10616                        /*
10617                         * We don't want the copy to proceed until verification
10618                         * succeeds, so null out this field.
10619                         */
10620                        mArgs = null;
10621                    }
10622                } else {
10623                    /*
10624                     * No package verification is enabled, so immediately start
10625                     * the remote call to initiate copy using temporary file.
10626                     */
10627                    ret = args.copyApk(mContainerService, true);
10628                }
10629            }
10630
10631            mRet = ret;
10632        }
10633
10634        @Override
10635        void handleReturnCode() {
10636            // If mArgs is null, then MCS couldn't be reached. When it
10637            // reconnects, it will try again to install. At that point, this
10638            // will succeed.
10639            if (mArgs != null) {
10640                processPendingInstall(mArgs, mRet);
10641            }
10642        }
10643
10644        @Override
10645        void handleServiceError() {
10646            mArgs = createInstallArgs(this);
10647            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10648        }
10649
10650        public boolean isForwardLocked() {
10651            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10652        }
10653    }
10654
10655    /**
10656     * Used during creation of InstallArgs
10657     *
10658     * @param installFlags package installation flags
10659     * @return true if should be installed on external storage
10660     */
10661    private static boolean installOnExternalAsec(int installFlags) {
10662        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10663            return false;
10664        }
10665        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10666            return true;
10667        }
10668        return false;
10669    }
10670
10671    /**
10672     * Used during creation of InstallArgs
10673     *
10674     * @param installFlags package installation flags
10675     * @return true if should be installed as forward locked
10676     */
10677    private static boolean installForwardLocked(int installFlags) {
10678        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10679    }
10680
10681    private InstallArgs createInstallArgs(InstallParams params) {
10682        if (params.move != null) {
10683            return new MoveInstallArgs(params);
10684        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10685            return new AsecInstallArgs(params);
10686        } else {
10687            return new FileInstallArgs(params);
10688        }
10689    }
10690
10691    /**
10692     * Create args that describe an existing installed package. Typically used
10693     * when cleaning up old installs, or used as a move source.
10694     */
10695    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10696            String resourcePath, String[] instructionSets) {
10697        final boolean isInAsec;
10698        if (installOnExternalAsec(installFlags)) {
10699            /* Apps on SD card are always in ASEC containers. */
10700            isInAsec = true;
10701        } else if (installForwardLocked(installFlags)
10702                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10703            /*
10704             * Forward-locked apps are only in ASEC containers if they're the
10705             * new style
10706             */
10707            isInAsec = true;
10708        } else {
10709            isInAsec = false;
10710        }
10711
10712        if (isInAsec) {
10713            return new AsecInstallArgs(codePath, instructionSets,
10714                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10715        } else {
10716            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10717        }
10718    }
10719
10720    static abstract class InstallArgs {
10721        /** @see InstallParams#origin */
10722        final OriginInfo origin;
10723        /** @see InstallParams#move */
10724        final MoveInfo move;
10725
10726        final IPackageInstallObserver2 observer;
10727        // Always refers to PackageManager flags only
10728        final int installFlags;
10729        final String installerPackageName;
10730        final String volumeUuid;
10731        final ManifestDigest manifestDigest;
10732        final UserHandle user;
10733        final String abiOverride;
10734
10735        // The list of instruction sets supported by this app. This is currently
10736        // only used during the rmdex() phase to clean up resources. We can get rid of this
10737        // if we move dex files under the common app path.
10738        /* nullable */ String[] instructionSets;
10739
10740        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10741                int installFlags, String installerPackageName, String volumeUuid,
10742                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10743                String abiOverride) {
10744            this.origin = origin;
10745            this.move = move;
10746            this.installFlags = installFlags;
10747            this.observer = observer;
10748            this.installerPackageName = installerPackageName;
10749            this.volumeUuid = volumeUuid;
10750            this.manifestDigest = manifestDigest;
10751            this.user = user;
10752            this.instructionSets = instructionSets;
10753            this.abiOverride = abiOverride;
10754        }
10755
10756        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10757        abstract int doPreInstall(int status);
10758
10759        /**
10760         * Rename package into final resting place. All paths on the given
10761         * scanned package should be updated to reflect the rename.
10762         */
10763        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10764        abstract int doPostInstall(int status, int uid);
10765
10766        /** @see PackageSettingBase#codePathString */
10767        abstract String getCodePath();
10768        /** @see PackageSettingBase#resourcePathString */
10769        abstract String getResourcePath();
10770
10771        // Need installer lock especially for dex file removal.
10772        abstract void cleanUpResourcesLI();
10773        abstract boolean doPostDeleteLI(boolean delete);
10774
10775        /**
10776         * Called before the source arguments are copied. This is used mostly
10777         * for MoveParams when it needs to read the source file to put it in the
10778         * destination.
10779         */
10780        int doPreCopy() {
10781            return PackageManager.INSTALL_SUCCEEDED;
10782        }
10783
10784        /**
10785         * Called after the source arguments are copied. This is used mostly for
10786         * MoveParams when it needs to read the source file to put it in the
10787         * destination.
10788         *
10789         * @return
10790         */
10791        int doPostCopy(int uid) {
10792            return PackageManager.INSTALL_SUCCEEDED;
10793        }
10794
10795        protected boolean isFwdLocked() {
10796            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10797        }
10798
10799        protected boolean isExternalAsec() {
10800            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10801        }
10802
10803        UserHandle getUser() {
10804            return user;
10805        }
10806    }
10807
10808    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10809        if (!allCodePaths.isEmpty()) {
10810            if (instructionSets == null) {
10811                throw new IllegalStateException("instructionSet == null");
10812            }
10813            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10814            for (String codePath : allCodePaths) {
10815                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10816                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10817                    if (retCode < 0) {
10818                        Slog.w(TAG, "Couldn't remove dex file for package: "
10819                                + " at location " + codePath + ", retcode=" + retCode);
10820                        // we don't consider this to be a failure of the core package deletion
10821                    }
10822                }
10823            }
10824        }
10825    }
10826
10827    /**
10828     * Logic to handle installation of non-ASEC applications, including copying
10829     * and renaming logic.
10830     */
10831    class FileInstallArgs extends InstallArgs {
10832        private File codeFile;
10833        private File resourceFile;
10834
10835        // Example topology:
10836        // /data/app/com.example/base.apk
10837        // /data/app/com.example/split_foo.apk
10838        // /data/app/com.example/lib/arm/libfoo.so
10839        // /data/app/com.example/lib/arm64/libfoo.so
10840        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10841
10842        /** New install */
10843        FileInstallArgs(InstallParams params) {
10844            super(params.origin, params.move, params.observer, params.installFlags,
10845                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10846                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10847            if (isFwdLocked()) {
10848                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10849            }
10850        }
10851
10852        /** Existing install */
10853        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10854            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10855                    null);
10856            this.codeFile = (codePath != null) ? new File(codePath) : null;
10857            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10858        }
10859
10860        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10861            if (origin.staged) {
10862                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10863                codeFile = origin.file;
10864                resourceFile = origin.file;
10865                return PackageManager.INSTALL_SUCCEEDED;
10866            }
10867
10868            try {
10869                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10870                codeFile = tempDir;
10871                resourceFile = tempDir;
10872            } catch (IOException e) {
10873                Slog.w(TAG, "Failed to create copy file: " + e);
10874                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10875            }
10876
10877            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10878                @Override
10879                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10880                    if (!FileUtils.isValidExtFilename(name)) {
10881                        throw new IllegalArgumentException("Invalid filename: " + name);
10882                    }
10883                    try {
10884                        final File file = new File(codeFile, name);
10885                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10886                                O_RDWR | O_CREAT, 0644);
10887                        Os.chmod(file.getAbsolutePath(), 0644);
10888                        return new ParcelFileDescriptor(fd);
10889                    } catch (ErrnoException e) {
10890                        throw new RemoteException("Failed to open: " + e.getMessage());
10891                    }
10892                }
10893            };
10894
10895            int ret = PackageManager.INSTALL_SUCCEEDED;
10896            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10897            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10898                Slog.e(TAG, "Failed to copy package");
10899                return ret;
10900            }
10901
10902            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10903            NativeLibraryHelper.Handle handle = null;
10904            try {
10905                handle = NativeLibraryHelper.Handle.create(codeFile);
10906                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10907                        abiOverride);
10908            } catch (IOException e) {
10909                Slog.e(TAG, "Copying native libraries failed", e);
10910                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10911            } finally {
10912                IoUtils.closeQuietly(handle);
10913            }
10914
10915            return ret;
10916        }
10917
10918        int doPreInstall(int status) {
10919            if (status != PackageManager.INSTALL_SUCCEEDED) {
10920                cleanUp();
10921            }
10922            return status;
10923        }
10924
10925        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10926            if (status != PackageManager.INSTALL_SUCCEEDED) {
10927                cleanUp();
10928                return false;
10929            }
10930
10931            final File targetDir = codeFile.getParentFile();
10932            final File beforeCodeFile = codeFile;
10933            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10934
10935            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10936            try {
10937                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10938            } catch (ErrnoException e) {
10939                Slog.w(TAG, "Failed to rename", e);
10940                return false;
10941            }
10942
10943            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10944                Slog.w(TAG, "Failed to restorecon");
10945                return false;
10946            }
10947
10948            // Reflect the rename internally
10949            codeFile = afterCodeFile;
10950            resourceFile = afterCodeFile;
10951
10952            // Reflect the rename in scanned details
10953            pkg.codePath = afterCodeFile.getAbsolutePath();
10954            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10955                    pkg.baseCodePath);
10956            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10957                    pkg.splitCodePaths);
10958
10959            // Reflect the rename in app info
10960            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10961            pkg.applicationInfo.setCodePath(pkg.codePath);
10962            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10963            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10964            pkg.applicationInfo.setResourcePath(pkg.codePath);
10965            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10966            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10967
10968            return true;
10969        }
10970
10971        int doPostInstall(int status, int uid) {
10972            if (status != PackageManager.INSTALL_SUCCEEDED) {
10973                cleanUp();
10974            }
10975            return status;
10976        }
10977
10978        @Override
10979        String getCodePath() {
10980            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10981        }
10982
10983        @Override
10984        String getResourcePath() {
10985            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10986        }
10987
10988        private boolean cleanUp() {
10989            if (codeFile == null || !codeFile.exists()) {
10990                return false;
10991            }
10992
10993            if (codeFile.isDirectory()) {
10994                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10995            } else {
10996                codeFile.delete();
10997            }
10998
10999            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11000                resourceFile.delete();
11001            }
11002
11003            return true;
11004        }
11005
11006        void cleanUpResourcesLI() {
11007            // Try enumerating all code paths before deleting
11008            List<String> allCodePaths = Collections.EMPTY_LIST;
11009            if (codeFile != null && codeFile.exists()) {
11010                try {
11011                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11012                    allCodePaths = pkg.getAllCodePaths();
11013                } catch (PackageParserException e) {
11014                    // Ignored; we tried our best
11015                }
11016            }
11017
11018            cleanUp();
11019            removeDexFiles(allCodePaths, instructionSets);
11020        }
11021
11022        boolean doPostDeleteLI(boolean delete) {
11023            // XXX err, shouldn't we respect the delete flag?
11024            cleanUpResourcesLI();
11025            return true;
11026        }
11027    }
11028
11029    private boolean isAsecExternal(String cid) {
11030        final String asecPath = PackageHelper.getSdFilesystem(cid);
11031        return !asecPath.startsWith(mAsecInternalPath);
11032    }
11033
11034    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11035            PackageManagerException {
11036        if (copyRet < 0) {
11037            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11038                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11039                throw new PackageManagerException(copyRet, message);
11040            }
11041        }
11042    }
11043
11044    /**
11045     * Extract the MountService "container ID" from the full code path of an
11046     * .apk.
11047     */
11048    static String cidFromCodePath(String fullCodePath) {
11049        int eidx = fullCodePath.lastIndexOf("/");
11050        String subStr1 = fullCodePath.substring(0, eidx);
11051        int sidx = subStr1.lastIndexOf("/");
11052        return subStr1.substring(sidx+1, eidx);
11053    }
11054
11055    /**
11056     * Logic to handle installation of ASEC applications, including copying and
11057     * renaming logic.
11058     */
11059    class AsecInstallArgs extends InstallArgs {
11060        static final String RES_FILE_NAME = "pkg.apk";
11061        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11062
11063        String cid;
11064        String packagePath;
11065        String resourcePath;
11066
11067        /** New install */
11068        AsecInstallArgs(InstallParams params) {
11069            super(params.origin, params.move, params.observer, params.installFlags,
11070                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11071                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11072        }
11073
11074        /** Existing install */
11075        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11076                        boolean isExternal, boolean isForwardLocked) {
11077            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11078                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11079                    instructionSets, null);
11080            // Hackily pretend we're still looking at a full code path
11081            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11082                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11083            }
11084
11085            // Extract cid from fullCodePath
11086            int eidx = fullCodePath.lastIndexOf("/");
11087            String subStr1 = fullCodePath.substring(0, eidx);
11088            int sidx = subStr1.lastIndexOf("/");
11089            cid = subStr1.substring(sidx+1, eidx);
11090            setMountPath(subStr1);
11091        }
11092
11093        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11094            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11095                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11096                    instructionSets, null);
11097            this.cid = cid;
11098            setMountPath(PackageHelper.getSdDir(cid));
11099        }
11100
11101        void createCopyFile() {
11102            cid = mInstallerService.allocateExternalStageCidLegacy();
11103        }
11104
11105        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11106            if (origin.staged) {
11107                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11108                cid = origin.cid;
11109                setMountPath(PackageHelper.getSdDir(cid));
11110                return PackageManager.INSTALL_SUCCEEDED;
11111            }
11112
11113            if (temp) {
11114                createCopyFile();
11115            } else {
11116                /*
11117                 * Pre-emptively destroy the container since it's destroyed if
11118                 * copying fails due to it existing anyway.
11119                 */
11120                PackageHelper.destroySdDir(cid);
11121            }
11122
11123            final String newMountPath = imcs.copyPackageToContainer(
11124                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11125                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11126
11127            if (newMountPath != null) {
11128                setMountPath(newMountPath);
11129                return PackageManager.INSTALL_SUCCEEDED;
11130            } else {
11131                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11132            }
11133        }
11134
11135        @Override
11136        String getCodePath() {
11137            return packagePath;
11138        }
11139
11140        @Override
11141        String getResourcePath() {
11142            return resourcePath;
11143        }
11144
11145        int doPreInstall(int status) {
11146            if (status != PackageManager.INSTALL_SUCCEEDED) {
11147                // Destroy container
11148                PackageHelper.destroySdDir(cid);
11149            } else {
11150                boolean mounted = PackageHelper.isContainerMounted(cid);
11151                if (!mounted) {
11152                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11153                            Process.SYSTEM_UID);
11154                    if (newMountPath != null) {
11155                        setMountPath(newMountPath);
11156                    } else {
11157                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11158                    }
11159                }
11160            }
11161            return status;
11162        }
11163
11164        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11165            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11166            String newMountPath = null;
11167            if (PackageHelper.isContainerMounted(cid)) {
11168                // Unmount the container
11169                if (!PackageHelper.unMountSdDir(cid)) {
11170                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11171                    return false;
11172                }
11173            }
11174            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11175                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11176                        " which might be stale. Will try to clean up.");
11177                // Clean up the stale container and proceed to recreate.
11178                if (!PackageHelper.destroySdDir(newCacheId)) {
11179                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11180                    return false;
11181                }
11182                // Successfully cleaned up stale container. Try to rename again.
11183                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11184                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11185                            + " inspite of cleaning it up.");
11186                    return false;
11187                }
11188            }
11189            if (!PackageHelper.isContainerMounted(newCacheId)) {
11190                Slog.w(TAG, "Mounting container " + newCacheId);
11191                newMountPath = PackageHelper.mountSdDir(newCacheId,
11192                        getEncryptKey(), Process.SYSTEM_UID);
11193            } else {
11194                newMountPath = PackageHelper.getSdDir(newCacheId);
11195            }
11196            if (newMountPath == null) {
11197                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11198                return false;
11199            }
11200            Log.i(TAG, "Succesfully renamed " + cid +
11201                    " to " + newCacheId +
11202                    " at new path: " + newMountPath);
11203            cid = newCacheId;
11204
11205            final File beforeCodeFile = new File(packagePath);
11206            setMountPath(newMountPath);
11207            final File afterCodeFile = new File(packagePath);
11208
11209            // Reflect the rename in scanned details
11210            pkg.codePath = afterCodeFile.getAbsolutePath();
11211            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11212                    pkg.baseCodePath);
11213            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11214                    pkg.splitCodePaths);
11215
11216            // Reflect the rename in app info
11217            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11218            pkg.applicationInfo.setCodePath(pkg.codePath);
11219            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11220            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11221            pkg.applicationInfo.setResourcePath(pkg.codePath);
11222            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11223            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11224
11225            return true;
11226        }
11227
11228        private void setMountPath(String mountPath) {
11229            final File mountFile = new File(mountPath);
11230
11231            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11232            if (monolithicFile.exists()) {
11233                packagePath = monolithicFile.getAbsolutePath();
11234                if (isFwdLocked()) {
11235                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11236                } else {
11237                    resourcePath = packagePath;
11238                }
11239            } else {
11240                packagePath = mountFile.getAbsolutePath();
11241                resourcePath = packagePath;
11242            }
11243        }
11244
11245        int doPostInstall(int status, int uid) {
11246            if (status != PackageManager.INSTALL_SUCCEEDED) {
11247                cleanUp();
11248            } else {
11249                final int groupOwner;
11250                final String protectedFile;
11251                if (isFwdLocked()) {
11252                    groupOwner = UserHandle.getSharedAppGid(uid);
11253                    protectedFile = RES_FILE_NAME;
11254                } else {
11255                    groupOwner = -1;
11256                    protectedFile = null;
11257                }
11258
11259                if (uid < Process.FIRST_APPLICATION_UID
11260                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11261                    Slog.e(TAG, "Failed to finalize " + cid);
11262                    PackageHelper.destroySdDir(cid);
11263                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11264                }
11265
11266                boolean mounted = PackageHelper.isContainerMounted(cid);
11267                if (!mounted) {
11268                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11269                }
11270            }
11271            return status;
11272        }
11273
11274        private void cleanUp() {
11275            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11276
11277            // Destroy secure container
11278            PackageHelper.destroySdDir(cid);
11279        }
11280
11281        private List<String> getAllCodePaths() {
11282            final File codeFile = new File(getCodePath());
11283            if (codeFile != null && codeFile.exists()) {
11284                try {
11285                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11286                    return pkg.getAllCodePaths();
11287                } catch (PackageParserException e) {
11288                    // Ignored; we tried our best
11289                }
11290            }
11291            return Collections.EMPTY_LIST;
11292        }
11293
11294        void cleanUpResourcesLI() {
11295            // Enumerate all code paths before deleting
11296            cleanUpResourcesLI(getAllCodePaths());
11297        }
11298
11299        private void cleanUpResourcesLI(List<String> allCodePaths) {
11300            cleanUp();
11301            removeDexFiles(allCodePaths, instructionSets);
11302        }
11303
11304        String getPackageName() {
11305            return getAsecPackageName(cid);
11306        }
11307
11308        boolean doPostDeleteLI(boolean delete) {
11309            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11310            final List<String> allCodePaths = getAllCodePaths();
11311            boolean mounted = PackageHelper.isContainerMounted(cid);
11312            if (mounted) {
11313                // Unmount first
11314                if (PackageHelper.unMountSdDir(cid)) {
11315                    mounted = false;
11316                }
11317            }
11318            if (!mounted && delete) {
11319                cleanUpResourcesLI(allCodePaths);
11320            }
11321            return !mounted;
11322        }
11323
11324        @Override
11325        int doPreCopy() {
11326            if (isFwdLocked()) {
11327                if (!PackageHelper.fixSdPermissions(cid,
11328                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11329                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11330                }
11331            }
11332
11333            return PackageManager.INSTALL_SUCCEEDED;
11334        }
11335
11336        @Override
11337        int doPostCopy(int uid) {
11338            if (isFwdLocked()) {
11339                if (uid < Process.FIRST_APPLICATION_UID
11340                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11341                                RES_FILE_NAME)) {
11342                    Slog.e(TAG, "Failed to finalize " + cid);
11343                    PackageHelper.destroySdDir(cid);
11344                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11345                }
11346            }
11347
11348            return PackageManager.INSTALL_SUCCEEDED;
11349        }
11350    }
11351
11352    /**
11353     * Logic to handle movement of existing installed applications.
11354     */
11355    class MoveInstallArgs extends InstallArgs {
11356        private File codeFile;
11357        private File resourceFile;
11358
11359        /** New install */
11360        MoveInstallArgs(InstallParams params) {
11361            super(params.origin, params.move, params.observer, params.installFlags,
11362                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11363                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11364        }
11365
11366        int copyApk(IMediaContainerService imcs, boolean temp) {
11367            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11368                    + move.fromUuid + " to " + move.toUuid);
11369            synchronized (mInstaller) {
11370                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11371                        move.dataAppName, move.appId, move.seinfo) != 0) {
11372                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11373                }
11374            }
11375
11376            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11377            resourceFile = codeFile;
11378            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11379
11380            return PackageManager.INSTALL_SUCCEEDED;
11381        }
11382
11383        int doPreInstall(int status) {
11384            if (status != PackageManager.INSTALL_SUCCEEDED) {
11385                cleanUp(move.toUuid);
11386            }
11387            return status;
11388        }
11389
11390        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11391            if (status != PackageManager.INSTALL_SUCCEEDED) {
11392                cleanUp(move.toUuid);
11393                return false;
11394            }
11395
11396            // Reflect the move in app info
11397            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11398            pkg.applicationInfo.setCodePath(pkg.codePath);
11399            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11400            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11401            pkg.applicationInfo.setResourcePath(pkg.codePath);
11402            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11403            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11404
11405            return true;
11406        }
11407
11408        int doPostInstall(int status, int uid) {
11409            if (status == PackageManager.INSTALL_SUCCEEDED) {
11410                cleanUp(move.fromUuid);
11411            } else {
11412                cleanUp(move.toUuid);
11413            }
11414            return status;
11415        }
11416
11417        @Override
11418        String getCodePath() {
11419            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11420        }
11421
11422        @Override
11423        String getResourcePath() {
11424            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11425        }
11426
11427        private boolean cleanUp(String volumeUuid) {
11428            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11429                    move.dataAppName);
11430            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11431            synchronized (mInstallLock) {
11432                // Clean up both app data and code
11433                removeDataDirsLI(volumeUuid, move.packageName);
11434                if (codeFile.isDirectory()) {
11435                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11436                } else {
11437                    codeFile.delete();
11438                }
11439            }
11440            return true;
11441        }
11442
11443        void cleanUpResourcesLI() {
11444            throw new UnsupportedOperationException();
11445        }
11446
11447        boolean doPostDeleteLI(boolean delete) {
11448            throw new UnsupportedOperationException();
11449        }
11450    }
11451
11452    static String getAsecPackageName(String packageCid) {
11453        int idx = packageCid.lastIndexOf("-");
11454        if (idx == -1) {
11455            return packageCid;
11456        }
11457        return packageCid.substring(0, idx);
11458    }
11459
11460    // Utility method used to create code paths based on package name and available index.
11461    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11462        String idxStr = "";
11463        int idx = 1;
11464        // Fall back to default value of idx=1 if prefix is not
11465        // part of oldCodePath
11466        if (oldCodePath != null) {
11467            String subStr = oldCodePath;
11468            // Drop the suffix right away
11469            if (suffix != null && subStr.endsWith(suffix)) {
11470                subStr = subStr.substring(0, subStr.length() - suffix.length());
11471            }
11472            // If oldCodePath already contains prefix find out the
11473            // ending index to either increment or decrement.
11474            int sidx = subStr.lastIndexOf(prefix);
11475            if (sidx != -1) {
11476                subStr = subStr.substring(sidx + prefix.length());
11477                if (subStr != null) {
11478                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11479                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11480                    }
11481                    try {
11482                        idx = Integer.parseInt(subStr);
11483                        if (idx <= 1) {
11484                            idx++;
11485                        } else {
11486                            idx--;
11487                        }
11488                    } catch(NumberFormatException e) {
11489                    }
11490                }
11491            }
11492        }
11493        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11494        return prefix + idxStr;
11495    }
11496
11497    private File getNextCodePath(File targetDir, String packageName) {
11498        int suffix = 1;
11499        File result;
11500        do {
11501            result = new File(targetDir, packageName + "-" + suffix);
11502            suffix++;
11503        } while (result.exists());
11504        return result;
11505    }
11506
11507    // Utility method that returns the relative package path with respect
11508    // to the installation directory. Like say for /data/data/com.test-1.apk
11509    // string com.test-1 is returned.
11510    static String deriveCodePathName(String codePath) {
11511        if (codePath == null) {
11512            return null;
11513        }
11514        final File codeFile = new File(codePath);
11515        final String name = codeFile.getName();
11516        if (codeFile.isDirectory()) {
11517            return name;
11518        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11519            final int lastDot = name.lastIndexOf('.');
11520            return name.substring(0, lastDot);
11521        } else {
11522            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11523            return null;
11524        }
11525    }
11526
11527    class PackageInstalledInfo {
11528        String name;
11529        int uid;
11530        // The set of users that originally had this package installed.
11531        int[] origUsers;
11532        // The set of users that now have this package installed.
11533        int[] newUsers;
11534        PackageParser.Package pkg;
11535        int returnCode;
11536        String returnMsg;
11537        PackageRemovedInfo removedInfo;
11538
11539        public void setError(int code, String msg) {
11540            returnCode = code;
11541            returnMsg = msg;
11542            Slog.w(TAG, msg);
11543        }
11544
11545        public void setError(String msg, PackageParserException e) {
11546            returnCode = e.error;
11547            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11548            Slog.w(TAG, msg, e);
11549        }
11550
11551        public void setError(String msg, PackageManagerException e) {
11552            returnCode = e.error;
11553            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11554            Slog.w(TAG, msg, e);
11555        }
11556
11557        // In some error cases we want to convey more info back to the observer
11558        String origPackage;
11559        String origPermission;
11560    }
11561
11562    /*
11563     * Install a non-existing package.
11564     */
11565    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11566            UserHandle user, String installerPackageName, String volumeUuid,
11567            PackageInstalledInfo res) {
11568        // Remember this for later, in case we need to rollback this install
11569        String pkgName = pkg.packageName;
11570
11571        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11572        final boolean dataDirExists = Environment
11573                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11574        synchronized(mPackages) {
11575            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11576                // A package with the same name is already installed, though
11577                // it has been renamed to an older name.  The package we
11578                // are trying to install should be installed as an update to
11579                // the existing one, but that has not been requested, so bail.
11580                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11581                        + " without first uninstalling package running as "
11582                        + mSettings.mRenamedPackages.get(pkgName));
11583                return;
11584            }
11585            if (mPackages.containsKey(pkgName)) {
11586                // Don't allow installation over an existing package with the same name.
11587                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11588                        + " without first uninstalling.");
11589                return;
11590            }
11591        }
11592
11593        try {
11594            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11595                    System.currentTimeMillis(), user);
11596
11597            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11598            // delete the partially installed application. the data directory will have to be
11599            // restored if it was already existing
11600            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11601                // remove package from internal structures.  Note that we want deletePackageX to
11602                // delete the package data and cache directories that it created in
11603                // scanPackageLocked, unless those directories existed before we even tried to
11604                // install.
11605                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11606                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11607                                res.removedInfo, true);
11608            }
11609
11610        } catch (PackageManagerException e) {
11611            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11612        }
11613    }
11614
11615    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11616        // Can't rotate keys during boot or if sharedUser.
11617        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11618                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11619            return false;
11620        }
11621        // app is using upgradeKeySets; make sure all are valid
11622        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11623        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11624        for (int i = 0; i < upgradeKeySets.length; i++) {
11625            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11626                Slog.wtf(TAG, "Package "
11627                         + (oldPs.name != null ? oldPs.name : "<null>")
11628                         + " contains upgrade-key-set reference to unknown key-set: "
11629                         + upgradeKeySets[i]
11630                         + " reverting to signatures check.");
11631                return false;
11632            }
11633        }
11634        return true;
11635    }
11636
11637    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11638        // Upgrade keysets are being used.  Determine if new package has a superset of the
11639        // required keys.
11640        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11641        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11642        for (int i = 0; i < upgradeKeySets.length; i++) {
11643            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11644            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11645                return true;
11646            }
11647        }
11648        return false;
11649    }
11650
11651    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11652            UserHandle user, String installerPackageName, String volumeUuid,
11653            PackageInstalledInfo res) {
11654        final PackageParser.Package oldPackage;
11655        final String pkgName = pkg.packageName;
11656        final int[] allUsers;
11657        final boolean[] perUserInstalled;
11658        final boolean weFroze;
11659
11660        // First find the old package info and check signatures
11661        synchronized(mPackages) {
11662            oldPackage = mPackages.get(pkgName);
11663            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11664            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11665            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11666                if(!checkUpgradeKeySetLP(ps, pkg)) {
11667                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11668                            "New package not signed by keys specified by upgrade-keysets: "
11669                            + pkgName);
11670                    return;
11671                }
11672            } else {
11673                // default to original signature matching
11674                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11675                    != PackageManager.SIGNATURE_MATCH) {
11676                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11677                            "New package has a different signature: " + pkgName);
11678                    return;
11679                }
11680            }
11681
11682            // In case of rollback, remember per-user/profile install state
11683            allUsers = sUserManager.getUserIds();
11684            perUserInstalled = new boolean[allUsers.length];
11685            for (int i = 0; i < allUsers.length; i++) {
11686                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11687            }
11688
11689            // Mark the app as frozen to prevent launching during the upgrade
11690            // process, and then kill all running instances
11691            if (!ps.frozen) {
11692                ps.frozen = true;
11693                weFroze = true;
11694            } else {
11695                weFroze = false;
11696            }
11697        }
11698
11699        // Now that we're guarded by frozen state, kill app during upgrade
11700        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11701
11702        try {
11703            boolean sysPkg = (isSystemApp(oldPackage));
11704            if (sysPkg) {
11705                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11706                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11707            } else {
11708                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11709                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11710            }
11711        } finally {
11712            // Regardless of success or failure of upgrade steps above, always
11713            // unfreeze the package if we froze it
11714            if (weFroze) {
11715                unfreezePackage(pkgName);
11716            }
11717        }
11718    }
11719
11720    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11721            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11722            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11723            String volumeUuid, PackageInstalledInfo res) {
11724        String pkgName = deletedPackage.packageName;
11725        boolean deletedPkg = true;
11726        boolean updatedSettings = false;
11727
11728        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11729                + deletedPackage);
11730        long origUpdateTime;
11731        if (pkg.mExtras != null) {
11732            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11733        } else {
11734            origUpdateTime = 0;
11735        }
11736
11737        // First delete the existing package while retaining the data directory
11738        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11739                res.removedInfo, true)) {
11740            // If the existing package wasn't successfully deleted
11741            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11742            deletedPkg = false;
11743        } else {
11744            // Successfully deleted the old package; proceed with replace.
11745
11746            // If deleted package lived in a container, give users a chance to
11747            // relinquish resources before killing.
11748            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11749                if (DEBUG_INSTALL) {
11750                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11751                }
11752                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11753                final ArrayList<String> pkgList = new ArrayList<String>(1);
11754                pkgList.add(deletedPackage.applicationInfo.packageName);
11755                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11756            }
11757
11758            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11759            try {
11760                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11761                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11762                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11763                        perUserInstalled, res, user);
11764                updatedSettings = true;
11765            } catch (PackageManagerException e) {
11766                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11767            }
11768        }
11769
11770        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11771            // remove package from internal structures.  Note that we want deletePackageX to
11772            // delete the package data and cache directories that it created in
11773            // scanPackageLocked, unless those directories existed before we even tried to
11774            // install.
11775            if(updatedSettings) {
11776                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11777                deletePackageLI(
11778                        pkgName, null, true, allUsers, perUserInstalled,
11779                        PackageManager.DELETE_KEEP_DATA,
11780                                res.removedInfo, true);
11781            }
11782            // Since we failed to install the new package we need to restore the old
11783            // package that we deleted.
11784            if (deletedPkg) {
11785                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11786                File restoreFile = new File(deletedPackage.codePath);
11787                // Parse old package
11788                boolean oldExternal = isExternal(deletedPackage);
11789                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11790                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11791                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11792                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11793                try {
11794                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11795                } catch (PackageManagerException e) {
11796                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11797                            + e.getMessage());
11798                    return;
11799                }
11800                // Restore of old package succeeded. Update permissions.
11801                // writer
11802                synchronized (mPackages) {
11803                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11804                            UPDATE_PERMISSIONS_ALL);
11805                    // can downgrade to reader
11806                    mSettings.writeLPr();
11807                }
11808                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11809            }
11810        }
11811    }
11812
11813    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11814            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11815            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11816            String volumeUuid, PackageInstalledInfo res) {
11817        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11818                + ", old=" + deletedPackage);
11819        boolean disabledSystem = false;
11820        boolean updatedSettings = false;
11821        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11822        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11823                != 0) {
11824            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11825        }
11826        String packageName = deletedPackage.packageName;
11827        if (packageName == null) {
11828            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11829                    "Attempt to delete null packageName.");
11830            return;
11831        }
11832        PackageParser.Package oldPkg;
11833        PackageSetting oldPkgSetting;
11834        // reader
11835        synchronized (mPackages) {
11836            oldPkg = mPackages.get(packageName);
11837            oldPkgSetting = mSettings.mPackages.get(packageName);
11838            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11839                    (oldPkgSetting == null)) {
11840                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11841                        "Couldn't find package:" + packageName + " information");
11842                return;
11843            }
11844        }
11845
11846        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11847        res.removedInfo.removedPackage = packageName;
11848        // Remove existing system package
11849        removePackageLI(oldPkgSetting, true);
11850        // writer
11851        synchronized (mPackages) {
11852            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11853            if (!disabledSystem && deletedPackage != null) {
11854                // We didn't need to disable the .apk as a current system package,
11855                // which means we are replacing another update that is already
11856                // installed.  We need to make sure to delete the older one's .apk.
11857                res.removedInfo.args = createInstallArgsForExisting(0,
11858                        deletedPackage.applicationInfo.getCodePath(),
11859                        deletedPackage.applicationInfo.getResourcePath(),
11860                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11861            } else {
11862                res.removedInfo.args = null;
11863            }
11864        }
11865
11866        // Successfully disabled the old package. Now proceed with re-installation
11867        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11868
11869        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11870        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11871
11872        PackageParser.Package newPackage = null;
11873        try {
11874            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11875            if (newPackage.mExtras != null) {
11876                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11877                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11878                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11879
11880                // is the update attempting to change shared user? that isn't going to work...
11881                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11882                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11883                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11884                            + " to " + newPkgSetting.sharedUser);
11885                    updatedSettings = true;
11886                }
11887            }
11888
11889            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11890                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11891                        perUserInstalled, res, user);
11892                updatedSettings = true;
11893            }
11894
11895        } catch (PackageManagerException e) {
11896            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11897        }
11898
11899        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11900            // Re installation failed. Restore old information
11901            // Remove new pkg information
11902            if (newPackage != null) {
11903                removeInstalledPackageLI(newPackage, true);
11904            }
11905            // Add back the old system package
11906            try {
11907                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11908            } catch (PackageManagerException e) {
11909                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11910            }
11911            // Restore the old system information in Settings
11912            synchronized (mPackages) {
11913                if (disabledSystem) {
11914                    mSettings.enableSystemPackageLPw(packageName);
11915                }
11916                if (updatedSettings) {
11917                    mSettings.setInstallerPackageName(packageName,
11918                            oldPkgSetting.installerPackageName);
11919                }
11920                mSettings.writeLPr();
11921            }
11922        }
11923    }
11924
11925    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11926            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11927            UserHandle user) {
11928        String pkgName = newPackage.packageName;
11929        synchronized (mPackages) {
11930            //write settings. the installStatus will be incomplete at this stage.
11931            //note that the new package setting would have already been
11932            //added to mPackages. It hasn't been persisted yet.
11933            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11934            mSettings.writeLPr();
11935        }
11936
11937        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11938
11939        synchronized (mPackages) {
11940            updatePermissionsLPw(newPackage.packageName, newPackage,
11941                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11942                            ? UPDATE_PERMISSIONS_ALL : 0));
11943            // For system-bundled packages, we assume that installing an upgraded version
11944            // of the package implies that the user actually wants to run that new code,
11945            // so we enable the package.
11946            PackageSetting ps = mSettings.mPackages.get(pkgName);
11947            if (ps != null) {
11948                if (isSystemApp(newPackage)) {
11949                    // NB: implicit assumption that system package upgrades apply to all users
11950                    if (DEBUG_INSTALL) {
11951                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11952                    }
11953                    if (res.origUsers != null) {
11954                        for (int userHandle : res.origUsers) {
11955                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11956                                    userHandle, installerPackageName);
11957                        }
11958                    }
11959                    // Also convey the prior install/uninstall state
11960                    if (allUsers != null && perUserInstalled != null) {
11961                        for (int i = 0; i < allUsers.length; i++) {
11962                            if (DEBUG_INSTALL) {
11963                                Slog.d(TAG, "    user " + allUsers[i]
11964                                        + " => " + perUserInstalled[i]);
11965                            }
11966                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11967                        }
11968                        // these install state changes will be persisted in the
11969                        // upcoming call to mSettings.writeLPr().
11970                    }
11971                }
11972                // It's implied that when a user requests installation, they want the app to be
11973                // installed and enabled.
11974                int userId = user.getIdentifier();
11975                if (userId != UserHandle.USER_ALL) {
11976                    ps.setInstalled(true, userId);
11977                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11978                }
11979            }
11980            res.name = pkgName;
11981            res.uid = newPackage.applicationInfo.uid;
11982            res.pkg = newPackage;
11983            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11984            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11985            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11986            //to update install status
11987            mSettings.writeLPr();
11988        }
11989    }
11990
11991    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11992        final int installFlags = args.installFlags;
11993        final String installerPackageName = args.installerPackageName;
11994        final String volumeUuid = args.volumeUuid;
11995        final File tmpPackageFile = new File(args.getCodePath());
11996        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11997        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11998                || (args.volumeUuid != null));
11999        boolean replace = false;
12000        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12001        if (args.move != null) {
12002            // moving a complete application; perfom an initial scan on the new install location
12003            scanFlags |= SCAN_INITIAL;
12004        }
12005        // Result object to be returned
12006        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12007
12008        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12009        // Retrieve PackageSettings and parse package
12010        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12011                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12012                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12013        PackageParser pp = new PackageParser();
12014        pp.setSeparateProcesses(mSeparateProcesses);
12015        pp.setDisplayMetrics(mMetrics);
12016
12017        final PackageParser.Package pkg;
12018        try {
12019            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12020        } catch (PackageParserException e) {
12021            res.setError("Failed parse during installPackageLI", e);
12022            return;
12023        }
12024
12025        // Mark that we have an install time CPU ABI override.
12026        pkg.cpuAbiOverride = args.abiOverride;
12027
12028        String pkgName = res.name = pkg.packageName;
12029        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12030            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12031                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12032                return;
12033            }
12034        }
12035
12036        try {
12037            pp.collectCertificates(pkg, parseFlags);
12038            pp.collectManifestDigest(pkg);
12039        } catch (PackageParserException e) {
12040            res.setError("Failed collect during installPackageLI", e);
12041            return;
12042        }
12043
12044        /* If the installer passed in a manifest digest, compare it now. */
12045        if (args.manifestDigest != null) {
12046            if (DEBUG_INSTALL) {
12047                final String parsedManifest = pkg.manifestDigest == null ? "null"
12048                        : pkg.manifestDigest.toString();
12049                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12050                        + parsedManifest);
12051            }
12052
12053            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12054                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12055                return;
12056            }
12057        } else if (DEBUG_INSTALL) {
12058            final String parsedManifest = pkg.manifestDigest == null
12059                    ? "null" : pkg.manifestDigest.toString();
12060            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12061        }
12062
12063        // Get rid of all references to package scan path via parser.
12064        pp = null;
12065        String oldCodePath = null;
12066        boolean systemApp = false;
12067        synchronized (mPackages) {
12068            // Check if installing already existing package
12069            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12070                String oldName = mSettings.mRenamedPackages.get(pkgName);
12071                if (pkg.mOriginalPackages != null
12072                        && pkg.mOriginalPackages.contains(oldName)
12073                        && mPackages.containsKey(oldName)) {
12074                    // This package is derived from an original package,
12075                    // and this device has been updating from that original
12076                    // name.  We must continue using the original name, so
12077                    // rename the new package here.
12078                    pkg.setPackageName(oldName);
12079                    pkgName = pkg.packageName;
12080                    replace = true;
12081                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12082                            + oldName + " pkgName=" + pkgName);
12083                } else if (mPackages.containsKey(pkgName)) {
12084                    // This package, under its official name, already exists
12085                    // on the device; we should replace it.
12086                    replace = true;
12087                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12088                }
12089
12090                // Prevent apps opting out from runtime permissions
12091                if (replace) {
12092                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12093                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12094                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12095                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12096                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12097                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12098                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12099                                        + " doesn't support runtime permissions but the old"
12100                                        + " target SDK " + oldTargetSdk + " does.");
12101                        return;
12102                    }
12103                }
12104            }
12105
12106            PackageSetting ps = mSettings.mPackages.get(pkgName);
12107            if (ps != null) {
12108                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12109
12110                // Quick sanity check that we're signed correctly if updating;
12111                // we'll check this again later when scanning, but we want to
12112                // bail early here before tripping over redefined permissions.
12113                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12114                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12115                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12116                                + pkg.packageName + " upgrade keys do not match the "
12117                                + "previously installed version");
12118                        return;
12119                    }
12120                } else {
12121                    try {
12122                        verifySignaturesLP(ps, pkg);
12123                    } catch (PackageManagerException e) {
12124                        res.setError(e.error, e.getMessage());
12125                        return;
12126                    }
12127                }
12128
12129                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12130                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12131                    systemApp = (ps.pkg.applicationInfo.flags &
12132                            ApplicationInfo.FLAG_SYSTEM) != 0;
12133                }
12134                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12135            }
12136
12137            // Check whether the newly-scanned package wants to define an already-defined perm
12138            int N = pkg.permissions.size();
12139            for (int i = N-1; i >= 0; i--) {
12140                PackageParser.Permission perm = pkg.permissions.get(i);
12141                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12142                if (bp != null) {
12143                    // If the defining package is signed with our cert, it's okay.  This
12144                    // also includes the "updating the same package" case, of course.
12145                    // "updating same package" could also involve key-rotation.
12146                    final boolean sigsOk;
12147                    if (bp.sourcePackage.equals(pkg.packageName)
12148                            && (bp.packageSetting instanceof PackageSetting)
12149                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12150                                    scanFlags))) {
12151                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12152                    } else {
12153                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12154                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12155                    }
12156                    if (!sigsOk) {
12157                        // If the owning package is the system itself, we log but allow
12158                        // install to proceed; we fail the install on all other permission
12159                        // redefinitions.
12160                        if (!bp.sourcePackage.equals("android")) {
12161                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12162                                    + pkg.packageName + " attempting to redeclare permission "
12163                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12164                            res.origPermission = perm.info.name;
12165                            res.origPackage = bp.sourcePackage;
12166                            return;
12167                        } else {
12168                            Slog.w(TAG, "Package " + pkg.packageName
12169                                    + " attempting to redeclare system permission "
12170                                    + perm.info.name + "; ignoring new declaration");
12171                            pkg.permissions.remove(i);
12172                        }
12173                    }
12174                }
12175            }
12176
12177        }
12178
12179        if (systemApp && onExternal) {
12180            // Disable updates to system apps on sdcard
12181            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12182                    "Cannot install updates to system apps on sdcard");
12183            return;
12184        }
12185
12186        if (args.move != null) {
12187            // We did an in-place move, so dex is ready to roll
12188            scanFlags |= SCAN_NO_DEX;
12189            scanFlags |= SCAN_MOVE;
12190        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12191            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12192            scanFlags |= SCAN_NO_DEX;
12193
12194            try {
12195                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12196                        true /* extract libs */);
12197            } catch (PackageManagerException pme) {
12198                Slog.e(TAG, "Error deriving application ABI", pme);
12199                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12200                return;
12201            }
12202
12203            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12204            int result = mPackageDexOptimizer
12205                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12206                            false /* defer */, false /* inclDependencies */);
12207            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12208                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12209                return;
12210            }
12211        }
12212
12213        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12214            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12215            return;
12216        }
12217
12218        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12219
12220        if (replace) {
12221            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12222                    installerPackageName, volumeUuid, res);
12223        } else {
12224            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12225                    args.user, installerPackageName, volumeUuid, res);
12226        }
12227        synchronized (mPackages) {
12228            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12229            if (ps != null) {
12230                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12231            }
12232        }
12233    }
12234
12235    private void startIntentFilterVerifications(int userId, boolean replacing,
12236            PackageParser.Package pkg) {
12237        if (mIntentFilterVerifierComponent == null) {
12238            Slog.w(TAG, "No IntentFilter verification will not be done as "
12239                    + "there is no IntentFilterVerifier available!");
12240            return;
12241        }
12242
12243        final int verifierUid = getPackageUid(
12244                mIntentFilterVerifierComponent.getPackageName(),
12245                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12246
12247        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12248        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12249        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12250        mHandler.sendMessage(msg);
12251    }
12252
12253    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12254            PackageParser.Package pkg) {
12255        int size = pkg.activities.size();
12256        if (size == 0) {
12257            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12258                    "No activity, so no need to verify any IntentFilter!");
12259            return;
12260        }
12261
12262        final boolean hasDomainURLs = hasDomainURLs(pkg);
12263        if (!hasDomainURLs) {
12264            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12265                    "No domain URLs, so no need to verify any IntentFilter!");
12266            return;
12267        }
12268
12269        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12270                + " if any IntentFilter from the " + size
12271                + " Activities needs verification ...");
12272
12273        int count = 0;
12274        final String packageName = pkg.packageName;
12275
12276        synchronized (mPackages) {
12277            // If this is a new install and we see that we've already run verification for this
12278            // package, we have nothing to do: it means the state was restored from backup.
12279            if (!replacing) {
12280                IntentFilterVerificationInfo ivi =
12281                        mSettings.getIntentFilterVerificationLPr(packageName);
12282                if (ivi != null) {
12283                    if (DEBUG_DOMAIN_VERIFICATION) {
12284                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12285                                + ivi.getStatusString());
12286                    }
12287                    return;
12288                }
12289            }
12290
12291            // If any filters need to be verified, then all need to be.
12292            boolean needToVerify = false;
12293            for (PackageParser.Activity a : pkg.activities) {
12294                for (ActivityIntentInfo filter : a.intents) {
12295                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12296                        if (DEBUG_DOMAIN_VERIFICATION) {
12297                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12298                        }
12299                        needToVerify = true;
12300                        break;
12301                    }
12302                }
12303            }
12304
12305            if (needToVerify) {
12306                final int verificationId = mIntentFilterVerificationToken++;
12307                for (PackageParser.Activity a : pkg.activities) {
12308                    for (ActivityIntentInfo filter : a.intents) {
12309                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12310                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12311                                    "Verification needed for IntentFilter:" + filter.toString());
12312                            mIntentFilterVerifier.addOneIntentFilterVerification(
12313                                    verifierUid, userId, verificationId, filter, packageName);
12314                            count++;
12315                        }
12316                    }
12317                }
12318            }
12319        }
12320
12321        if (count > 0) {
12322            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12323                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12324                    +  " for userId:" + userId);
12325            mIntentFilterVerifier.startVerifications(userId);
12326        } else {
12327            if (DEBUG_DOMAIN_VERIFICATION) {
12328                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12329            }
12330        }
12331    }
12332
12333    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12334        final ComponentName cn  = filter.activity.getComponentName();
12335        final String packageName = cn.getPackageName();
12336
12337        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12338                packageName);
12339        if (ivi == null) {
12340            return true;
12341        }
12342        int status = ivi.getStatus();
12343        switch (status) {
12344            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12345            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12346                return true;
12347
12348            default:
12349                // Nothing to do
12350                return false;
12351        }
12352    }
12353
12354    private static boolean isMultiArch(PackageSetting ps) {
12355        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12356    }
12357
12358    private static boolean isMultiArch(ApplicationInfo info) {
12359        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12360    }
12361
12362    private static boolean isExternal(PackageParser.Package pkg) {
12363        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12364    }
12365
12366    private static boolean isExternal(PackageSetting ps) {
12367        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12368    }
12369
12370    private static boolean isExternal(ApplicationInfo info) {
12371        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12372    }
12373
12374    private static boolean isSystemApp(PackageParser.Package pkg) {
12375        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12376    }
12377
12378    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12379        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12380    }
12381
12382    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12383        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12384    }
12385
12386    private static boolean isSystemApp(PackageSetting ps) {
12387        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12388    }
12389
12390    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12391        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12392    }
12393
12394    private int packageFlagsToInstallFlags(PackageSetting ps) {
12395        int installFlags = 0;
12396        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12397            // This existing package was an external ASEC install when we have
12398            // the external flag without a UUID
12399            installFlags |= PackageManager.INSTALL_EXTERNAL;
12400        }
12401        if (ps.isForwardLocked()) {
12402            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12403        }
12404        return installFlags;
12405    }
12406
12407    private void deleteTempPackageFiles() {
12408        final FilenameFilter filter = new FilenameFilter() {
12409            public boolean accept(File dir, String name) {
12410                return name.startsWith("vmdl") && name.endsWith(".tmp");
12411            }
12412        };
12413        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12414            file.delete();
12415        }
12416    }
12417
12418    @Override
12419    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12420            int flags) {
12421        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12422                flags);
12423    }
12424
12425    @Override
12426    public void deletePackage(final String packageName,
12427            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12428        mContext.enforceCallingOrSelfPermission(
12429                android.Manifest.permission.DELETE_PACKAGES, null);
12430        Preconditions.checkNotNull(packageName);
12431        Preconditions.checkNotNull(observer);
12432        final int uid = Binder.getCallingUid();
12433        if (UserHandle.getUserId(uid) != userId) {
12434            mContext.enforceCallingPermission(
12435                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12436                    "deletePackage for user " + userId);
12437        }
12438        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12439            try {
12440                observer.onPackageDeleted(packageName,
12441                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12442            } catch (RemoteException re) {
12443            }
12444            return;
12445        }
12446
12447        boolean uninstallBlocked = false;
12448        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12449            int[] users = sUserManager.getUserIds();
12450            for (int i = 0; i < users.length; ++i) {
12451                if (getBlockUninstallForUser(packageName, users[i])) {
12452                    uninstallBlocked = true;
12453                    break;
12454                }
12455            }
12456        } else {
12457            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12458        }
12459        if (uninstallBlocked) {
12460            try {
12461                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12462                        null);
12463            } catch (RemoteException re) {
12464            }
12465            return;
12466        }
12467
12468        if (DEBUG_REMOVE) {
12469            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12470        }
12471        // Queue up an async operation since the package deletion may take a little while.
12472        mHandler.post(new Runnable() {
12473            public void run() {
12474                mHandler.removeCallbacks(this);
12475                final int returnCode = deletePackageX(packageName, userId, flags);
12476                if (observer != null) {
12477                    try {
12478                        observer.onPackageDeleted(packageName, returnCode, null);
12479                    } catch (RemoteException e) {
12480                        Log.i(TAG, "Observer no longer exists.");
12481                    } //end catch
12482                } //end if
12483            } //end run
12484        });
12485    }
12486
12487    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12488        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12489                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12490        try {
12491            if (dpm != null) {
12492                if (dpm.isDeviceOwner(packageName)) {
12493                    return true;
12494                }
12495                int[] users;
12496                if (userId == UserHandle.USER_ALL) {
12497                    users = sUserManager.getUserIds();
12498                } else {
12499                    users = new int[]{userId};
12500                }
12501                for (int i = 0; i < users.length; ++i) {
12502                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12503                        return true;
12504                    }
12505                }
12506            }
12507        } catch (RemoteException e) {
12508        }
12509        return false;
12510    }
12511
12512    /**
12513     *  This method is an internal method that could be get invoked either
12514     *  to delete an installed package or to clean up a failed installation.
12515     *  After deleting an installed package, a broadcast is sent to notify any
12516     *  listeners that the package has been installed. For cleaning up a failed
12517     *  installation, the broadcast is not necessary since the package's
12518     *  installation wouldn't have sent the initial broadcast either
12519     *  The key steps in deleting a package are
12520     *  deleting the package information in internal structures like mPackages,
12521     *  deleting the packages base directories through installd
12522     *  updating mSettings to reflect current status
12523     *  persisting settings for later use
12524     *  sending a broadcast if necessary
12525     */
12526    private int deletePackageX(String packageName, int userId, int flags) {
12527        final PackageRemovedInfo info = new PackageRemovedInfo();
12528        final boolean res;
12529
12530        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12531                ? UserHandle.ALL : new UserHandle(userId);
12532
12533        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12534            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12535            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12536        }
12537
12538        boolean removedForAllUsers = false;
12539        boolean systemUpdate = false;
12540
12541        // for the uninstall-updates case and restricted profiles, remember the per-
12542        // userhandle installed state
12543        int[] allUsers;
12544        boolean[] perUserInstalled;
12545        synchronized (mPackages) {
12546            PackageSetting ps = mSettings.mPackages.get(packageName);
12547            allUsers = sUserManager.getUserIds();
12548            perUserInstalled = new boolean[allUsers.length];
12549            for (int i = 0; i < allUsers.length; i++) {
12550                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12551            }
12552        }
12553
12554        synchronized (mInstallLock) {
12555            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12556            res = deletePackageLI(packageName, removeForUser,
12557                    true, allUsers, perUserInstalled,
12558                    flags | REMOVE_CHATTY, info, true);
12559            systemUpdate = info.isRemovedPackageSystemUpdate;
12560            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12561                removedForAllUsers = true;
12562            }
12563            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12564                    + " removedForAllUsers=" + removedForAllUsers);
12565        }
12566
12567        if (res) {
12568            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12569
12570            // If the removed package was a system update, the old system package
12571            // was re-enabled; we need to broadcast this information
12572            if (systemUpdate) {
12573                Bundle extras = new Bundle(1);
12574                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12575                        ? info.removedAppId : info.uid);
12576                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12577
12578                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12579                        extras, null, null, null);
12580                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12581                        extras, null, null, null);
12582                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12583                        null, packageName, null, null);
12584            }
12585        }
12586        // Force a gc here.
12587        Runtime.getRuntime().gc();
12588        // Delete the resources here after sending the broadcast to let
12589        // other processes clean up before deleting resources.
12590        if (info.args != null) {
12591            synchronized (mInstallLock) {
12592                info.args.doPostDeleteLI(true);
12593            }
12594        }
12595
12596        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12597    }
12598
12599    class PackageRemovedInfo {
12600        String removedPackage;
12601        int uid = -1;
12602        int removedAppId = -1;
12603        int[] removedUsers = null;
12604        boolean isRemovedPackageSystemUpdate = false;
12605        // Clean up resources deleted packages.
12606        InstallArgs args = null;
12607
12608        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12609            Bundle extras = new Bundle(1);
12610            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12611            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12612            if (replacing) {
12613                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12614            }
12615            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12616            if (removedPackage != null) {
12617                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12618                        extras, null, null, removedUsers);
12619                if (fullRemove && !replacing) {
12620                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12621                            extras, null, null, removedUsers);
12622                }
12623            }
12624            if (removedAppId >= 0) {
12625                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12626                        removedUsers);
12627            }
12628        }
12629    }
12630
12631    /*
12632     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12633     * flag is not set, the data directory is removed as well.
12634     * make sure this flag is set for partially installed apps. If not its meaningless to
12635     * delete a partially installed application.
12636     */
12637    private void removePackageDataLI(PackageSetting ps,
12638            int[] allUserHandles, boolean[] perUserInstalled,
12639            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12640        String packageName = ps.name;
12641        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12642        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12643        // Retrieve object to delete permissions for shared user later on
12644        final PackageSetting deletedPs;
12645        // reader
12646        synchronized (mPackages) {
12647            deletedPs = mSettings.mPackages.get(packageName);
12648            if (outInfo != null) {
12649                outInfo.removedPackage = packageName;
12650                outInfo.removedUsers = deletedPs != null
12651                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12652                        : null;
12653            }
12654        }
12655        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12656            removeDataDirsLI(ps.volumeUuid, packageName);
12657            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12658        }
12659        // writer
12660        synchronized (mPackages) {
12661            if (deletedPs != null) {
12662                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12663                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12664                    clearDefaultBrowserIfNeeded(packageName);
12665                    if (outInfo != null) {
12666                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12667                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12668                    }
12669                    updatePermissionsLPw(deletedPs.name, null, 0);
12670                    if (deletedPs.sharedUser != null) {
12671                        // Remove permissions associated with package. Since runtime
12672                        // permissions are per user we have to kill the removed package
12673                        // or packages running under the shared user of the removed
12674                        // package if revoking the permissions requested only by the removed
12675                        // package is successful and this causes a change in gids.
12676                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12677                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12678                                    userId);
12679                            if (userIdToKill == UserHandle.USER_ALL
12680                                    || userIdToKill >= UserHandle.USER_OWNER) {
12681                                // If gids changed for this user, kill all affected packages.
12682                                mHandler.post(new Runnable() {
12683                                    @Override
12684                                    public void run() {
12685                                        // This has to happen with no lock held.
12686                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12687                                                KILL_APP_REASON_GIDS_CHANGED);
12688                                    }
12689                                });
12690                            break;
12691                            }
12692                        }
12693                    }
12694                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12695                }
12696                // make sure to preserve per-user disabled state if this removal was just
12697                // a downgrade of a system app to the factory package
12698                if (allUserHandles != null && perUserInstalled != null) {
12699                    if (DEBUG_REMOVE) {
12700                        Slog.d(TAG, "Propagating install state across downgrade");
12701                    }
12702                    for (int i = 0; i < allUserHandles.length; i++) {
12703                        if (DEBUG_REMOVE) {
12704                            Slog.d(TAG, "    user " + allUserHandles[i]
12705                                    + " => " + perUserInstalled[i]);
12706                        }
12707                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12708                    }
12709                }
12710            }
12711            // can downgrade to reader
12712            if (writeSettings) {
12713                // Save settings now
12714                mSettings.writeLPr();
12715            }
12716        }
12717        if (outInfo != null) {
12718            // A user ID was deleted here. Go through all users and remove it
12719            // from KeyStore.
12720            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12721        }
12722    }
12723
12724    static boolean locationIsPrivileged(File path) {
12725        try {
12726            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12727                    .getCanonicalPath();
12728            return path.getCanonicalPath().startsWith(privilegedAppDir);
12729        } catch (IOException e) {
12730            Slog.e(TAG, "Unable to access code path " + path);
12731        }
12732        return false;
12733    }
12734
12735    /*
12736     * Tries to delete system package.
12737     */
12738    private boolean deleteSystemPackageLI(PackageSetting newPs,
12739            int[] allUserHandles, boolean[] perUserInstalled,
12740            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12741        final boolean applyUserRestrictions
12742                = (allUserHandles != null) && (perUserInstalled != null);
12743        PackageSetting disabledPs = null;
12744        // Confirm if the system package has been updated
12745        // An updated system app can be deleted. This will also have to restore
12746        // the system pkg from system partition
12747        // reader
12748        synchronized (mPackages) {
12749            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12750        }
12751        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12752                + " disabledPs=" + disabledPs);
12753        if (disabledPs == null) {
12754            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12755            return false;
12756        } else if (DEBUG_REMOVE) {
12757            Slog.d(TAG, "Deleting system pkg from data partition");
12758        }
12759        if (DEBUG_REMOVE) {
12760            if (applyUserRestrictions) {
12761                Slog.d(TAG, "Remembering install states:");
12762                for (int i = 0; i < allUserHandles.length; i++) {
12763                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12764                }
12765            }
12766        }
12767        // Delete the updated package
12768        outInfo.isRemovedPackageSystemUpdate = true;
12769        if (disabledPs.versionCode < newPs.versionCode) {
12770            // Delete data for downgrades
12771            flags &= ~PackageManager.DELETE_KEEP_DATA;
12772        } else {
12773            // Preserve data by setting flag
12774            flags |= PackageManager.DELETE_KEEP_DATA;
12775        }
12776        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12777                allUserHandles, perUserInstalled, outInfo, writeSettings);
12778        if (!ret) {
12779            return false;
12780        }
12781        // writer
12782        synchronized (mPackages) {
12783            // Reinstate the old system package
12784            mSettings.enableSystemPackageLPw(newPs.name);
12785            // Remove any native libraries from the upgraded package.
12786            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12787        }
12788        // Install the system package
12789        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12790        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12791        if (locationIsPrivileged(disabledPs.codePath)) {
12792            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12793        }
12794
12795        final PackageParser.Package newPkg;
12796        try {
12797            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12798        } catch (PackageManagerException e) {
12799            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12800            return false;
12801        }
12802
12803        // writer
12804        synchronized (mPackages) {
12805            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12806            updatePermissionsLPw(newPkg.packageName, newPkg,
12807                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12808            if (applyUserRestrictions) {
12809                if (DEBUG_REMOVE) {
12810                    Slog.d(TAG, "Propagating install state across reinstall");
12811                }
12812                for (int i = 0; i < allUserHandles.length; i++) {
12813                    if (DEBUG_REMOVE) {
12814                        Slog.d(TAG, "    user " + allUserHandles[i]
12815                                + " => " + perUserInstalled[i]);
12816                    }
12817                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12818                }
12819                // Regardless of writeSettings we need to ensure that this restriction
12820                // state propagation is persisted
12821                mSettings.writeAllUsersPackageRestrictionsLPr();
12822            }
12823            // can downgrade to reader here
12824            if (writeSettings) {
12825                mSettings.writeLPr();
12826            }
12827        }
12828        return true;
12829    }
12830
12831    private boolean deleteInstalledPackageLI(PackageSetting ps,
12832            boolean deleteCodeAndResources, int flags,
12833            int[] allUserHandles, boolean[] perUserInstalled,
12834            PackageRemovedInfo outInfo, boolean writeSettings) {
12835        if (outInfo != null) {
12836            outInfo.uid = ps.appId;
12837        }
12838
12839        // Delete package data from internal structures and also remove data if flag is set
12840        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12841
12842        // Delete application code and resources
12843        if (deleteCodeAndResources && (outInfo != null)) {
12844            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12845                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12846            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12847        }
12848        return true;
12849    }
12850
12851    @Override
12852    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12853            int userId) {
12854        mContext.enforceCallingOrSelfPermission(
12855                android.Manifest.permission.DELETE_PACKAGES, null);
12856        synchronized (mPackages) {
12857            PackageSetting ps = mSettings.mPackages.get(packageName);
12858            if (ps == null) {
12859                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12860                return false;
12861            }
12862            if (!ps.getInstalled(userId)) {
12863                // Can't block uninstall for an app that is not installed or enabled.
12864                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12865                return false;
12866            }
12867            ps.setBlockUninstall(blockUninstall, userId);
12868            mSettings.writePackageRestrictionsLPr(userId);
12869        }
12870        return true;
12871    }
12872
12873    @Override
12874    public boolean getBlockUninstallForUser(String packageName, int userId) {
12875        synchronized (mPackages) {
12876            PackageSetting ps = mSettings.mPackages.get(packageName);
12877            if (ps == null) {
12878                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12879                return false;
12880            }
12881            return ps.getBlockUninstall(userId);
12882        }
12883    }
12884
12885    /*
12886     * This method handles package deletion in general
12887     */
12888    private boolean deletePackageLI(String packageName, UserHandle user,
12889            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12890            int flags, PackageRemovedInfo outInfo,
12891            boolean writeSettings) {
12892        if (packageName == null) {
12893            Slog.w(TAG, "Attempt to delete null packageName.");
12894            return false;
12895        }
12896        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12897        PackageSetting ps;
12898        boolean dataOnly = false;
12899        int removeUser = -1;
12900        int appId = -1;
12901        synchronized (mPackages) {
12902            ps = mSettings.mPackages.get(packageName);
12903            if (ps == null) {
12904                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12905                return false;
12906            }
12907            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12908                    && user.getIdentifier() != UserHandle.USER_ALL) {
12909                // The caller is asking that the package only be deleted for a single
12910                // user.  To do this, we just mark its uninstalled state and delete
12911                // its data.  If this is a system app, we only allow this to happen if
12912                // they have set the special DELETE_SYSTEM_APP which requests different
12913                // semantics than normal for uninstalling system apps.
12914                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12915                ps.setUserState(user.getIdentifier(),
12916                        COMPONENT_ENABLED_STATE_DEFAULT,
12917                        false, //installed
12918                        true,  //stopped
12919                        true,  //notLaunched
12920                        false, //hidden
12921                        null, null, null,
12922                        false, // blockUninstall
12923                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12924                if (!isSystemApp(ps)) {
12925                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12926                        // Other user still have this package installed, so all
12927                        // we need to do is clear this user's data and save that
12928                        // it is uninstalled.
12929                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12930                        removeUser = user.getIdentifier();
12931                        appId = ps.appId;
12932                        scheduleWritePackageRestrictionsLocked(removeUser);
12933                    } else {
12934                        // We need to set it back to 'installed' so the uninstall
12935                        // broadcasts will be sent correctly.
12936                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12937                        ps.setInstalled(true, user.getIdentifier());
12938                    }
12939                } else {
12940                    // This is a system app, so we assume that the
12941                    // other users still have this package installed, so all
12942                    // we need to do is clear this user's data and save that
12943                    // it is uninstalled.
12944                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12945                    removeUser = user.getIdentifier();
12946                    appId = ps.appId;
12947                    scheduleWritePackageRestrictionsLocked(removeUser);
12948                }
12949            }
12950        }
12951
12952        if (removeUser >= 0) {
12953            // From above, we determined that we are deleting this only
12954            // for a single user.  Continue the work here.
12955            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12956            if (outInfo != null) {
12957                outInfo.removedPackage = packageName;
12958                outInfo.removedAppId = appId;
12959                outInfo.removedUsers = new int[] {removeUser};
12960            }
12961            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12962            removeKeystoreDataIfNeeded(removeUser, appId);
12963            schedulePackageCleaning(packageName, removeUser, false);
12964            synchronized (mPackages) {
12965                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12966                    scheduleWritePackageRestrictionsLocked(removeUser);
12967                }
12968                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12969                        removeUser);
12970            }
12971            return true;
12972        }
12973
12974        if (dataOnly) {
12975            // Delete application data first
12976            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12977            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12978            return true;
12979        }
12980
12981        boolean ret = false;
12982        if (isSystemApp(ps)) {
12983            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12984            // When an updated system application is deleted we delete the existing resources as well and
12985            // fall back to existing code in system partition
12986            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12987                    flags, outInfo, writeSettings);
12988        } else {
12989            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12990            // Kill application pre-emptively especially for apps on sd.
12991            killApplication(packageName, ps.appId, "uninstall pkg");
12992            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12993                    allUserHandles, perUserInstalled,
12994                    outInfo, writeSettings);
12995        }
12996
12997        return ret;
12998    }
12999
13000    private final class ClearStorageConnection implements ServiceConnection {
13001        IMediaContainerService mContainerService;
13002
13003        @Override
13004        public void onServiceConnected(ComponentName name, IBinder service) {
13005            synchronized (this) {
13006                mContainerService = IMediaContainerService.Stub.asInterface(service);
13007                notifyAll();
13008            }
13009        }
13010
13011        @Override
13012        public void onServiceDisconnected(ComponentName name) {
13013        }
13014    }
13015
13016    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13017        final boolean mounted;
13018        if (Environment.isExternalStorageEmulated()) {
13019            mounted = true;
13020        } else {
13021            final String status = Environment.getExternalStorageState();
13022
13023            mounted = status.equals(Environment.MEDIA_MOUNTED)
13024                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13025        }
13026
13027        if (!mounted) {
13028            return;
13029        }
13030
13031        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13032        int[] users;
13033        if (userId == UserHandle.USER_ALL) {
13034            users = sUserManager.getUserIds();
13035        } else {
13036            users = new int[] { userId };
13037        }
13038        final ClearStorageConnection conn = new ClearStorageConnection();
13039        if (mContext.bindServiceAsUser(
13040                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13041            try {
13042                for (int curUser : users) {
13043                    long timeout = SystemClock.uptimeMillis() + 5000;
13044                    synchronized (conn) {
13045                        long now = SystemClock.uptimeMillis();
13046                        while (conn.mContainerService == null && now < timeout) {
13047                            try {
13048                                conn.wait(timeout - now);
13049                            } catch (InterruptedException e) {
13050                            }
13051                        }
13052                    }
13053                    if (conn.mContainerService == null) {
13054                        return;
13055                    }
13056
13057                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13058                    clearDirectory(conn.mContainerService,
13059                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13060                    if (allData) {
13061                        clearDirectory(conn.mContainerService,
13062                                userEnv.buildExternalStorageAppDataDirs(packageName));
13063                        clearDirectory(conn.mContainerService,
13064                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13065                    }
13066                }
13067            } finally {
13068                mContext.unbindService(conn);
13069            }
13070        }
13071    }
13072
13073    @Override
13074    public void clearApplicationUserData(final String packageName,
13075            final IPackageDataObserver observer, final int userId) {
13076        mContext.enforceCallingOrSelfPermission(
13077                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13078        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13079        // Queue up an async operation since the package deletion may take a little while.
13080        mHandler.post(new Runnable() {
13081            public void run() {
13082                mHandler.removeCallbacks(this);
13083                final boolean succeeded;
13084                synchronized (mInstallLock) {
13085                    succeeded = clearApplicationUserDataLI(packageName, userId);
13086                }
13087                clearExternalStorageDataSync(packageName, userId, true);
13088                if (succeeded) {
13089                    // invoke DeviceStorageMonitor's update method to clear any notifications
13090                    DeviceStorageMonitorInternal
13091                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13092                    if (dsm != null) {
13093                        dsm.checkMemory();
13094                    }
13095                }
13096                if(observer != null) {
13097                    try {
13098                        observer.onRemoveCompleted(packageName, succeeded);
13099                    } catch (RemoteException e) {
13100                        Log.i(TAG, "Observer no longer exists.");
13101                    }
13102                } //end if observer
13103            } //end run
13104        });
13105    }
13106
13107    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13108        if (packageName == null) {
13109            Slog.w(TAG, "Attempt to delete null packageName.");
13110            return false;
13111        }
13112
13113        // Try finding details about the requested package
13114        PackageParser.Package pkg;
13115        synchronized (mPackages) {
13116            pkg = mPackages.get(packageName);
13117            if (pkg == null) {
13118                final PackageSetting ps = mSettings.mPackages.get(packageName);
13119                if (ps != null) {
13120                    pkg = ps.pkg;
13121                }
13122            }
13123
13124            if (pkg == null) {
13125                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13126                return false;
13127            }
13128
13129            PackageSetting ps = (PackageSetting) pkg.mExtras;
13130            PermissionsState permissionsState = ps.getPermissionsState();
13131            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13132        }
13133
13134        // Always delete data directories for package, even if we found no other
13135        // record of app. This helps users recover from UID mismatches without
13136        // resorting to a full data wipe.
13137        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13138        if (retCode < 0) {
13139            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13140            return false;
13141        }
13142
13143        final int appId = pkg.applicationInfo.uid;
13144        removeKeystoreDataIfNeeded(userId, appId);
13145
13146        // Create a native library symlink only if we have native libraries
13147        // and if the native libraries are 32 bit libraries. We do not provide
13148        // this symlink for 64 bit libraries.
13149        if (pkg.applicationInfo.primaryCpuAbi != null &&
13150                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13151            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13152            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13153                    nativeLibPath, userId) < 0) {
13154                Slog.w(TAG, "Failed linking native library dir");
13155                return false;
13156            }
13157        }
13158
13159        return true;
13160    }
13161
13162
13163    /**
13164     * Revokes granted runtime permissions and clears resettable flags
13165     * which are flags that can be set by a user interaction.
13166     *
13167     * @param permissionsState The permission state to reset.
13168     * @param userId The device user for which to do a reset.
13169     */
13170    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13171            PermissionsState permissionsState, int userId) {
13172        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13173                | PackageManager.FLAG_PERMISSION_USER_FIXED
13174                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13175
13176        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13177    }
13178
13179    /**
13180     * Revokes granted runtime permissions and clears all flags.
13181     *
13182     * @param permissionsState The permission state to reset.
13183     * @param userId The device user for which to do a reset.
13184     */
13185    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13186            PermissionsState permissionsState, int userId) {
13187        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13188                PackageManager.MASK_PERMISSION_FLAGS);
13189    }
13190
13191    /**
13192     * Revokes granted runtime permissions and clears certain flags.
13193     *
13194     * @param permissionsState The permission state to reset.
13195     * @param userId The device user for which to do a reset.
13196     * @param flags The flags that is going to be reset.
13197     */
13198    private void revokeRuntimePermissionsAndClearFlagsLocked(
13199            PermissionsState permissionsState, final int userId, int flags) {
13200        boolean needsWrite = false;
13201
13202        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13203            BasePermission bp = mSettings.mPermissions.get(state.getName());
13204            if (bp != null) {
13205                permissionsState.revokeRuntimePermission(bp, userId);
13206                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13207                needsWrite = true;
13208            }
13209        }
13210
13211        // Ensure default permissions are never cleared.
13212        mHandler.post(new Runnable() {
13213            @Override
13214            public void run() {
13215                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13216            }
13217        });
13218
13219        if (needsWrite) {
13220            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13221        }
13222    }
13223
13224    /**
13225     * Remove entries from the keystore daemon. Will only remove it if the
13226     * {@code appId} is valid.
13227     */
13228    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13229        if (appId < 0) {
13230            return;
13231        }
13232
13233        final KeyStore keyStore = KeyStore.getInstance();
13234        if (keyStore != null) {
13235            if (userId == UserHandle.USER_ALL) {
13236                for (final int individual : sUserManager.getUserIds()) {
13237                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13238                }
13239            } else {
13240                keyStore.clearUid(UserHandle.getUid(userId, appId));
13241            }
13242        } else {
13243            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13244        }
13245    }
13246
13247    @Override
13248    public void deleteApplicationCacheFiles(final String packageName,
13249            final IPackageDataObserver observer) {
13250        mContext.enforceCallingOrSelfPermission(
13251                android.Manifest.permission.DELETE_CACHE_FILES, null);
13252        // Queue up an async operation since the package deletion may take a little while.
13253        final int userId = UserHandle.getCallingUserId();
13254        mHandler.post(new Runnable() {
13255            public void run() {
13256                mHandler.removeCallbacks(this);
13257                final boolean succeded;
13258                synchronized (mInstallLock) {
13259                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13260                }
13261                clearExternalStorageDataSync(packageName, userId, false);
13262                if (observer != null) {
13263                    try {
13264                        observer.onRemoveCompleted(packageName, succeded);
13265                    } catch (RemoteException e) {
13266                        Log.i(TAG, "Observer no longer exists.");
13267                    }
13268                } //end if observer
13269            } //end run
13270        });
13271    }
13272
13273    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13274        if (packageName == null) {
13275            Slog.w(TAG, "Attempt to delete null packageName.");
13276            return false;
13277        }
13278        PackageParser.Package p;
13279        synchronized (mPackages) {
13280            p = mPackages.get(packageName);
13281        }
13282        if (p == null) {
13283            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13284            return false;
13285        }
13286        final ApplicationInfo applicationInfo = p.applicationInfo;
13287        if (applicationInfo == null) {
13288            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13289            return false;
13290        }
13291        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13292        if (retCode < 0) {
13293            Slog.w(TAG, "Couldn't remove cache files for package: "
13294                       + packageName + " u" + userId);
13295            return false;
13296        }
13297        return true;
13298    }
13299
13300    @Override
13301    public void getPackageSizeInfo(final String packageName, int userHandle,
13302            final IPackageStatsObserver observer) {
13303        mContext.enforceCallingOrSelfPermission(
13304                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13305        if (packageName == null) {
13306            throw new IllegalArgumentException("Attempt to get size of null packageName");
13307        }
13308
13309        PackageStats stats = new PackageStats(packageName, userHandle);
13310
13311        /*
13312         * Queue up an async operation since the package measurement may take a
13313         * little while.
13314         */
13315        Message msg = mHandler.obtainMessage(INIT_COPY);
13316        msg.obj = new MeasureParams(stats, observer);
13317        mHandler.sendMessage(msg);
13318    }
13319
13320    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13321            PackageStats pStats) {
13322        if (packageName == null) {
13323            Slog.w(TAG, "Attempt to get size of null packageName.");
13324            return false;
13325        }
13326        PackageParser.Package p;
13327        boolean dataOnly = false;
13328        String libDirRoot = null;
13329        String asecPath = null;
13330        PackageSetting ps = null;
13331        synchronized (mPackages) {
13332            p = mPackages.get(packageName);
13333            ps = mSettings.mPackages.get(packageName);
13334            if(p == null) {
13335                dataOnly = true;
13336                if((ps == null) || (ps.pkg == null)) {
13337                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13338                    return false;
13339                }
13340                p = ps.pkg;
13341            }
13342            if (ps != null) {
13343                libDirRoot = ps.legacyNativeLibraryPathString;
13344            }
13345            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13346                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13347                if (secureContainerId != null) {
13348                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13349                }
13350            }
13351        }
13352        String publicSrcDir = null;
13353        if(!dataOnly) {
13354            final ApplicationInfo applicationInfo = p.applicationInfo;
13355            if (applicationInfo == null) {
13356                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13357                return false;
13358            }
13359            if (p.isForwardLocked()) {
13360                publicSrcDir = applicationInfo.getBaseResourcePath();
13361            }
13362        }
13363        // TODO: extend to measure size of split APKs
13364        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13365        // not just the first level.
13366        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13367        // just the primary.
13368        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13369        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13370                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13371        if (res < 0) {
13372            return false;
13373        }
13374
13375        // Fix-up for forward-locked applications in ASEC containers.
13376        if (!isExternal(p)) {
13377            pStats.codeSize += pStats.externalCodeSize;
13378            pStats.externalCodeSize = 0L;
13379        }
13380
13381        return true;
13382    }
13383
13384
13385    @Override
13386    public void addPackageToPreferred(String packageName) {
13387        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13388    }
13389
13390    @Override
13391    public void removePackageFromPreferred(String packageName) {
13392        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13393    }
13394
13395    @Override
13396    public List<PackageInfo> getPreferredPackages(int flags) {
13397        return new ArrayList<PackageInfo>();
13398    }
13399
13400    private int getUidTargetSdkVersionLockedLPr(int uid) {
13401        Object obj = mSettings.getUserIdLPr(uid);
13402        if (obj instanceof SharedUserSetting) {
13403            final SharedUserSetting sus = (SharedUserSetting) obj;
13404            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13405            final Iterator<PackageSetting> it = sus.packages.iterator();
13406            while (it.hasNext()) {
13407                final PackageSetting ps = it.next();
13408                if (ps.pkg != null) {
13409                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13410                    if (v < vers) vers = v;
13411                }
13412            }
13413            return vers;
13414        } else if (obj instanceof PackageSetting) {
13415            final PackageSetting ps = (PackageSetting) obj;
13416            if (ps.pkg != null) {
13417                return ps.pkg.applicationInfo.targetSdkVersion;
13418            }
13419        }
13420        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13421    }
13422
13423    @Override
13424    public void addPreferredActivity(IntentFilter filter, int match,
13425            ComponentName[] set, ComponentName activity, int userId) {
13426        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13427                "Adding preferred");
13428    }
13429
13430    private void addPreferredActivityInternal(IntentFilter filter, int match,
13431            ComponentName[] set, ComponentName activity, boolean always, int userId,
13432            String opname) {
13433        // writer
13434        int callingUid = Binder.getCallingUid();
13435        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13436        if (filter.countActions() == 0) {
13437            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13438            return;
13439        }
13440        synchronized (mPackages) {
13441            if (mContext.checkCallingOrSelfPermission(
13442                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13443                    != PackageManager.PERMISSION_GRANTED) {
13444                if (getUidTargetSdkVersionLockedLPr(callingUid)
13445                        < Build.VERSION_CODES.FROYO) {
13446                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13447                            + callingUid);
13448                    return;
13449                }
13450                mContext.enforceCallingOrSelfPermission(
13451                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13452            }
13453
13454            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13455            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13456                    + userId + ":");
13457            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13458            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13459            scheduleWritePackageRestrictionsLocked(userId);
13460        }
13461    }
13462
13463    @Override
13464    public void replacePreferredActivity(IntentFilter filter, int match,
13465            ComponentName[] set, ComponentName activity, int userId) {
13466        if (filter.countActions() != 1) {
13467            throw new IllegalArgumentException(
13468                    "replacePreferredActivity expects filter to have only 1 action.");
13469        }
13470        if (filter.countDataAuthorities() != 0
13471                || filter.countDataPaths() != 0
13472                || filter.countDataSchemes() > 1
13473                || filter.countDataTypes() != 0) {
13474            throw new IllegalArgumentException(
13475                    "replacePreferredActivity expects filter to have no data authorities, " +
13476                    "paths, or types; and at most one scheme.");
13477        }
13478
13479        final int callingUid = Binder.getCallingUid();
13480        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13481        synchronized (mPackages) {
13482            if (mContext.checkCallingOrSelfPermission(
13483                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13484                    != PackageManager.PERMISSION_GRANTED) {
13485                if (getUidTargetSdkVersionLockedLPr(callingUid)
13486                        < Build.VERSION_CODES.FROYO) {
13487                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13488                            + Binder.getCallingUid());
13489                    return;
13490                }
13491                mContext.enforceCallingOrSelfPermission(
13492                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13493            }
13494
13495            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13496            if (pir != null) {
13497                // Get all of the existing entries that exactly match this filter.
13498                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13499                if (existing != null && existing.size() == 1) {
13500                    PreferredActivity cur = existing.get(0);
13501                    if (DEBUG_PREFERRED) {
13502                        Slog.i(TAG, "Checking replace of preferred:");
13503                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13504                        if (!cur.mPref.mAlways) {
13505                            Slog.i(TAG, "  -- CUR; not mAlways!");
13506                        } else {
13507                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13508                            Slog.i(TAG, "  -- CUR: mSet="
13509                                    + Arrays.toString(cur.mPref.mSetComponents));
13510                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13511                            Slog.i(TAG, "  -- NEW: mMatch="
13512                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13513                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13514                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13515                        }
13516                    }
13517                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13518                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13519                            && cur.mPref.sameSet(set)) {
13520                        // Setting the preferred activity to what it happens to be already
13521                        if (DEBUG_PREFERRED) {
13522                            Slog.i(TAG, "Replacing with same preferred activity "
13523                                    + cur.mPref.mShortComponent + " for user "
13524                                    + userId + ":");
13525                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13526                        }
13527                        return;
13528                    }
13529                }
13530
13531                if (existing != null) {
13532                    if (DEBUG_PREFERRED) {
13533                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13534                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13535                    }
13536                    for (int i = 0; i < existing.size(); i++) {
13537                        PreferredActivity pa = existing.get(i);
13538                        if (DEBUG_PREFERRED) {
13539                            Slog.i(TAG, "Removing existing preferred activity "
13540                                    + pa.mPref.mComponent + ":");
13541                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13542                        }
13543                        pir.removeFilter(pa);
13544                    }
13545                }
13546            }
13547            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13548                    "Replacing preferred");
13549        }
13550    }
13551
13552    @Override
13553    public void clearPackagePreferredActivities(String packageName) {
13554        final int uid = Binder.getCallingUid();
13555        // writer
13556        synchronized (mPackages) {
13557            PackageParser.Package pkg = mPackages.get(packageName);
13558            if (pkg == null || pkg.applicationInfo.uid != uid) {
13559                if (mContext.checkCallingOrSelfPermission(
13560                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13561                        != PackageManager.PERMISSION_GRANTED) {
13562                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13563                            < Build.VERSION_CODES.FROYO) {
13564                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13565                                + Binder.getCallingUid());
13566                        return;
13567                    }
13568                    mContext.enforceCallingOrSelfPermission(
13569                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13570                }
13571            }
13572
13573            int user = UserHandle.getCallingUserId();
13574            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13575                scheduleWritePackageRestrictionsLocked(user);
13576            }
13577        }
13578    }
13579
13580    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13581    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13582        ArrayList<PreferredActivity> removed = null;
13583        boolean changed = false;
13584        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13585            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13586            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13587            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13588                continue;
13589            }
13590            Iterator<PreferredActivity> it = pir.filterIterator();
13591            while (it.hasNext()) {
13592                PreferredActivity pa = it.next();
13593                // Mark entry for removal only if it matches the package name
13594                // and the entry is of type "always".
13595                if (packageName == null ||
13596                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13597                                && pa.mPref.mAlways)) {
13598                    if (removed == null) {
13599                        removed = new ArrayList<PreferredActivity>();
13600                    }
13601                    removed.add(pa);
13602                }
13603            }
13604            if (removed != null) {
13605                for (int j=0; j<removed.size(); j++) {
13606                    PreferredActivity pa = removed.get(j);
13607                    pir.removeFilter(pa);
13608                }
13609                changed = true;
13610            }
13611        }
13612        return changed;
13613    }
13614
13615    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13616    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13617        if (userId == UserHandle.USER_ALL) {
13618            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13619                    sUserManager.getUserIds())) {
13620                for (int oneUserId : sUserManager.getUserIds()) {
13621                    scheduleWritePackageRestrictionsLocked(oneUserId);
13622                }
13623            }
13624        } else {
13625            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13626                scheduleWritePackageRestrictionsLocked(userId);
13627            }
13628        }
13629    }
13630
13631
13632    void clearDefaultBrowserIfNeeded(String packageName) {
13633        for (int oneUserId : sUserManager.getUserIds()) {
13634            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13635            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13636            if (packageName.equals(defaultBrowserPackageName)) {
13637                setDefaultBrowserPackageName(null, oneUserId);
13638            }
13639        }
13640    }
13641
13642    @Override
13643    public void resetPreferredActivities(int userId) {
13644        mContext.enforceCallingOrSelfPermission(
13645                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13646        // writer
13647        synchronized (mPackages) {
13648            clearPackagePreferredActivitiesLPw(null, userId);
13649            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13650            applyFactoryDefaultBrowserLPw(userId);
13651
13652            scheduleWritePackageRestrictionsLocked(userId);
13653        }
13654    }
13655
13656    @Override
13657    public int getPreferredActivities(List<IntentFilter> outFilters,
13658            List<ComponentName> outActivities, String packageName) {
13659
13660        int num = 0;
13661        final int userId = UserHandle.getCallingUserId();
13662        // reader
13663        synchronized (mPackages) {
13664            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13665            if (pir != null) {
13666                final Iterator<PreferredActivity> it = pir.filterIterator();
13667                while (it.hasNext()) {
13668                    final PreferredActivity pa = it.next();
13669                    if (packageName == null
13670                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13671                                    && pa.mPref.mAlways)) {
13672                        if (outFilters != null) {
13673                            outFilters.add(new IntentFilter(pa));
13674                        }
13675                        if (outActivities != null) {
13676                            outActivities.add(pa.mPref.mComponent);
13677                        }
13678                    }
13679                }
13680            }
13681        }
13682
13683        return num;
13684    }
13685
13686    @Override
13687    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13688            int userId) {
13689        int callingUid = Binder.getCallingUid();
13690        if (callingUid != Process.SYSTEM_UID) {
13691            throw new SecurityException(
13692                    "addPersistentPreferredActivity can only be run by the system");
13693        }
13694        if (filter.countActions() == 0) {
13695            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13696            return;
13697        }
13698        synchronized (mPackages) {
13699            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13700                    " :");
13701            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13702            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13703                    new PersistentPreferredActivity(filter, activity));
13704            scheduleWritePackageRestrictionsLocked(userId);
13705        }
13706    }
13707
13708    @Override
13709    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13710        int callingUid = Binder.getCallingUid();
13711        if (callingUid != Process.SYSTEM_UID) {
13712            throw new SecurityException(
13713                    "clearPackagePersistentPreferredActivities can only be run by the system");
13714        }
13715        ArrayList<PersistentPreferredActivity> removed = null;
13716        boolean changed = false;
13717        synchronized (mPackages) {
13718            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13719                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13720                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13721                        .valueAt(i);
13722                if (userId != thisUserId) {
13723                    continue;
13724                }
13725                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13726                while (it.hasNext()) {
13727                    PersistentPreferredActivity ppa = it.next();
13728                    // Mark entry for removal only if it matches the package name.
13729                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13730                        if (removed == null) {
13731                            removed = new ArrayList<PersistentPreferredActivity>();
13732                        }
13733                        removed.add(ppa);
13734                    }
13735                }
13736                if (removed != null) {
13737                    for (int j=0; j<removed.size(); j++) {
13738                        PersistentPreferredActivity ppa = removed.get(j);
13739                        ppir.removeFilter(ppa);
13740                    }
13741                    changed = true;
13742                }
13743            }
13744
13745            if (changed) {
13746                scheduleWritePackageRestrictionsLocked(userId);
13747            }
13748        }
13749    }
13750
13751    /**
13752     * Common machinery for picking apart a restored XML blob and passing
13753     * it to a caller-supplied functor to be applied to the running system.
13754     */
13755    private void restoreFromXml(XmlPullParser parser, int userId,
13756            String expectedStartTag, BlobXmlRestorer functor)
13757            throws IOException, XmlPullParserException {
13758        int type;
13759        while ((type = parser.next()) != XmlPullParser.START_TAG
13760                && type != XmlPullParser.END_DOCUMENT) {
13761        }
13762        if (type != XmlPullParser.START_TAG) {
13763            // oops didn't find a start tag?!
13764            if (DEBUG_BACKUP) {
13765                Slog.e(TAG, "Didn't find start tag during restore");
13766            }
13767            return;
13768        }
13769
13770        // this is supposed to be TAG_PREFERRED_BACKUP
13771        if (!expectedStartTag.equals(parser.getName())) {
13772            if (DEBUG_BACKUP) {
13773                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13774            }
13775            return;
13776        }
13777
13778        // skip interfering stuff, then we're aligned with the backing implementation
13779        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13780        functor.apply(parser, userId);
13781    }
13782
13783    private interface BlobXmlRestorer {
13784        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13785    }
13786
13787    /**
13788     * Non-Binder method, support for the backup/restore mechanism: write the
13789     * full set of preferred activities in its canonical XML format.  Returns the
13790     * XML output as a byte array, or null if there is none.
13791     */
13792    @Override
13793    public byte[] getPreferredActivityBackup(int userId) {
13794        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13795            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13796        }
13797
13798        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13799        try {
13800            final XmlSerializer serializer = new FastXmlSerializer();
13801            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13802            serializer.startDocument(null, true);
13803            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13804
13805            synchronized (mPackages) {
13806                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13807            }
13808
13809            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13810            serializer.endDocument();
13811            serializer.flush();
13812        } catch (Exception e) {
13813            if (DEBUG_BACKUP) {
13814                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13815            }
13816            return null;
13817        }
13818
13819        return dataStream.toByteArray();
13820    }
13821
13822    @Override
13823    public void restorePreferredActivities(byte[] backup, int userId) {
13824        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13825            throw new SecurityException("Only the system may call restorePreferredActivities()");
13826        }
13827
13828        try {
13829            final XmlPullParser parser = Xml.newPullParser();
13830            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13831            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13832                    new BlobXmlRestorer() {
13833                        @Override
13834                        public void apply(XmlPullParser parser, int userId)
13835                                throws XmlPullParserException, IOException {
13836                            synchronized (mPackages) {
13837                                mSettings.readPreferredActivitiesLPw(parser, userId);
13838                            }
13839                        }
13840                    } );
13841        } catch (Exception e) {
13842            if (DEBUG_BACKUP) {
13843                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13844            }
13845        }
13846    }
13847
13848    /**
13849     * Non-Binder method, support for the backup/restore mechanism: write the
13850     * default browser (etc) settings in its canonical XML format.  Returns the default
13851     * browser XML representation as a byte array, or null if there is none.
13852     */
13853    @Override
13854    public byte[] getDefaultAppsBackup(int userId) {
13855        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13856            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13857        }
13858
13859        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13860        try {
13861            final XmlSerializer serializer = new FastXmlSerializer();
13862            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13863            serializer.startDocument(null, true);
13864            serializer.startTag(null, TAG_DEFAULT_APPS);
13865
13866            synchronized (mPackages) {
13867                mSettings.writeDefaultAppsLPr(serializer, userId);
13868            }
13869
13870            serializer.endTag(null, TAG_DEFAULT_APPS);
13871            serializer.endDocument();
13872            serializer.flush();
13873        } catch (Exception e) {
13874            if (DEBUG_BACKUP) {
13875                Slog.e(TAG, "Unable to write default apps for backup", e);
13876            }
13877            return null;
13878        }
13879
13880        return dataStream.toByteArray();
13881    }
13882
13883    @Override
13884    public void restoreDefaultApps(byte[] backup, int userId) {
13885        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13886            throw new SecurityException("Only the system may call restoreDefaultApps()");
13887        }
13888
13889        try {
13890            final XmlPullParser parser = Xml.newPullParser();
13891            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13892            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13893                    new BlobXmlRestorer() {
13894                        @Override
13895                        public void apply(XmlPullParser parser, int userId)
13896                                throws XmlPullParserException, IOException {
13897                            synchronized (mPackages) {
13898                                mSettings.readDefaultAppsLPw(parser, userId);
13899                            }
13900                        }
13901                    } );
13902        } catch (Exception e) {
13903            if (DEBUG_BACKUP) {
13904                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13905            }
13906        }
13907    }
13908
13909    @Override
13910    public byte[] getIntentFilterVerificationBackup(int userId) {
13911        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13912            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13913        }
13914
13915        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13916        try {
13917            final XmlSerializer serializer = new FastXmlSerializer();
13918            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13919            serializer.startDocument(null, true);
13920            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13921
13922            synchronized (mPackages) {
13923                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13924            }
13925
13926            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13927            serializer.endDocument();
13928            serializer.flush();
13929        } catch (Exception e) {
13930            if (DEBUG_BACKUP) {
13931                Slog.e(TAG, "Unable to write default apps for backup", e);
13932            }
13933            return null;
13934        }
13935
13936        return dataStream.toByteArray();
13937    }
13938
13939    @Override
13940    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13941        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13942            throw new SecurityException("Only the system may call restorePreferredActivities()");
13943        }
13944
13945        try {
13946            final XmlPullParser parser = Xml.newPullParser();
13947            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13948            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13949                    new BlobXmlRestorer() {
13950                        @Override
13951                        public void apply(XmlPullParser parser, int userId)
13952                                throws XmlPullParserException, IOException {
13953                            synchronized (mPackages) {
13954                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13955                                mSettings.writeLPr();
13956                            }
13957                        }
13958                    } );
13959        } catch (Exception e) {
13960            if (DEBUG_BACKUP) {
13961                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13962            }
13963        }
13964    }
13965
13966    @Override
13967    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13968            int sourceUserId, int targetUserId, int flags) {
13969        mContext.enforceCallingOrSelfPermission(
13970                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13971        int callingUid = Binder.getCallingUid();
13972        enforceOwnerRights(ownerPackage, callingUid);
13973        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13974        if (intentFilter.countActions() == 0) {
13975            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13976            return;
13977        }
13978        synchronized (mPackages) {
13979            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13980                    ownerPackage, targetUserId, flags);
13981            CrossProfileIntentResolver resolver =
13982                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13983            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13984            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13985            if (existing != null) {
13986                int size = existing.size();
13987                for (int i = 0; i < size; i++) {
13988                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13989                        return;
13990                    }
13991                }
13992            }
13993            resolver.addFilter(newFilter);
13994            scheduleWritePackageRestrictionsLocked(sourceUserId);
13995        }
13996    }
13997
13998    @Override
13999    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14000        mContext.enforceCallingOrSelfPermission(
14001                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14002        int callingUid = Binder.getCallingUid();
14003        enforceOwnerRights(ownerPackage, callingUid);
14004        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14005        synchronized (mPackages) {
14006            CrossProfileIntentResolver resolver =
14007                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14008            ArraySet<CrossProfileIntentFilter> set =
14009                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14010            for (CrossProfileIntentFilter filter : set) {
14011                if (filter.getOwnerPackage().equals(ownerPackage)) {
14012                    resolver.removeFilter(filter);
14013                }
14014            }
14015            scheduleWritePackageRestrictionsLocked(sourceUserId);
14016        }
14017    }
14018
14019    // Enforcing that callingUid is owning pkg on userId
14020    private void enforceOwnerRights(String pkg, int callingUid) {
14021        // The system owns everything.
14022        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14023            return;
14024        }
14025        int callingUserId = UserHandle.getUserId(callingUid);
14026        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14027        if (pi == null) {
14028            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14029                    + callingUserId);
14030        }
14031        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14032            throw new SecurityException("Calling uid " + callingUid
14033                    + " does not own package " + pkg);
14034        }
14035    }
14036
14037    @Override
14038    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14039        Intent intent = new Intent(Intent.ACTION_MAIN);
14040        intent.addCategory(Intent.CATEGORY_HOME);
14041
14042        final int callingUserId = UserHandle.getCallingUserId();
14043        List<ResolveInfo> list = queryIntentActivities(intent, null,
14044                PackageManager.GET_META_DATA, callingUserId);
14045        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14046                true, false, false, callingUserId);
14047
14048        allHomeCandidates.clear();
14049        if (list != null) {
14050            for (ResolveInfo ri : list) {
14051                allHomeCandidates.add(ri);
14052            }
14053        }
14054        return (preferred == null || preferred.activityInfo == null)
14055                ? null
14056                : new ComponentName(preferred.activityInfo.packageName,
14057                        preferred.activityInfo.name);
14058    }
14059
14060    @Override
14061    public void setApplicationEnabledSetting(String appPackageName,
14062            int newState, int flags, int userId, String callingPackage) {
14063        if (!sUserManager.exists(userId)) return;
14064        if (callingPackage == null) {
14065            callingPackage = Integer.toString(Binder.getCallingUid());
14066        }
14067        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14068    }
14069
14070    @Override
14071    public void setComponentEnabledSetting(ComponentName componentName,
14072            int newState, int flags, int userId) {
14073        if (!sUserManager.exists(userId)) return;
14074        setEnabledSetting(componentName.getPackageName(),
14075                componentName.getClassName(), newState, flags, userId, null);
14076    }
14077
14078    private void setEnabledSetting(final String packageName, String className, int newState,
14079            final int flags, int userId, String callingPackage) {
14080        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14081              || newState == COMPONENT_ENABLED_STATE_ENABLED
14082              || newState == COMPONENT_ENABLED_STATE_DISABLED
14083              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14084              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14085            throw new IllegalArgumentException("Invalid new component state: "
14086                    + newState);
14087        }
14088        PackageSetting pkgSetting;
14089        final int uid = Binder.getCallingUid();
14090        final int permission = mContext.checkCallingOrSelfPermission(
14091                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14092        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14093        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14094        boolean sendNow = false;
14095        boolean isApp = (className == null);
14096        String componentName = isApp ? packageName : className;
14097        int packageUid = -1;
14098        ArrayList<String> components;
14099
14100        // writer
14101        synchronized (mPackages) {
14102            pkgSetting = mSettings.mPackages.get(packageName);
14103            if (pkgSetting == null) {
14104                if (className == null) {
14105                    throw new IllegalArgumentException(
14106                            "Unknown package: " + packageName);
14107                }
14108                throw new IllegalArgumentException(
14109                        "Unknown component: " + packageName
14110                        + "/" + className);
14111            }
14112            // Allow root and verify that userId is not being specified by a different user
14113            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14114                throw new SecurityException(
14115                        "Permission Denial: attempt to change component state from pid="
14116                        + Binder.getCallingPid()
14117                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14118            }
14119            if (className == null) {
14120                // We're dealing with an application/package level state change
14121                if (pkgSetting.getEnabled(userId) == newState) {
14122                    // Nothing to do
14123                    return;
14124                }
14125                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14126                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14127                    // Don't care about who enables an app.
14128                    callingPackage = null;
14129                }
14130                pkgSetting.setEnabled(newState, userId, callingPackage);
14131                // pkgSetting.pkg.mSetEnabled = newState;
14132            } else {
14133                // We're dealing with a component level state change
14134                // First, verify that this is a valid class name.
14135                PackageParser.Package pkg = pkgSetting.pkg;
14136                if (pkg == null || !pkg.hasComponentClassName(className)) {
14137                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14138                        throw new IllegalArgumentException("Component class " + className
14139                                + " does not exist in " + packageName);
14140                    } else {
14141                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14142                                + className + " does not exist in " + packageName);
14143                    }
14144                }
14145                switch (newState) {
14146                case COMPONENT_ENABLED_STATE_ENABLED:
14147                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14148                        return;
14149                    }
14150                    break;
14151                case COMPONENT_ENABLED_STATE_DISABLED:
14152                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14153                        return;
14154                    }
14155                    break;
14156                case COMPONENT_ENABLED_STATE_DEFAULT:
14157                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14158                        return;
14159                    }
14160                    break;
14161                default:
14162                    Slog.e(TAG, "Invalid new component state: " + newState);
14163                    return;
14164                }
14165            }
14166            scheduleWritePackageRestrictionsLocked(userId);
14167            components = mPendingBroadcasts.get(userId, packageName);
14168            final boolean newPackage = components == null;
14169            if (newPackage) {
14170                components = new ArrayList<String>();
14171            }
14172            if (!components.contains(componentName)) {
14173                components.add(componentName);
14174            }
14175            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14176                sendNow = true;
14177                // Purge entry from pending broadcast list if another one exists already
14178                // since we are sending one right away.
14179                mPendingBroadcasts.remove(userId, packageName);
14180            } else {
14181                if (newPackage) {
14182                    mPendingBroadcasts.put(userId, packageName, components);
14183                }
14184                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14185                    // Schedule a message
14186                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14187                }
14188            }
14189        }
14190
14191        long callingId = Binder.clearCallingIdentity();
14192        try {
14193            if (sendNow) {
14194                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14195                sendPackageChangedBroadcast(packageName,
14196                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14197            }
14198        } finally {
14199            Binder.restoreCallingIdentity(callingId);
14200        }
14201    }
14202
14203    private void sendPackageChangedBroadcast(String packageName,
14204            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14205        if (DEBUG_INSTALL)
14206            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14207                    + componentNames);
14208        Bundle extras = new Bundle(4);
14209        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14210        String nameList[] = new String[componentNames.size()];
14211        componentNames.toArray(nameList);
14212        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14213        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14214        extras.putInt(Intent.EXTRA_UID, packageUid);
14215        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14216                new int[] {UserHandle.getUserId(packageUid)});
14217    }
14218
14219    @Override
14220    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14221        if (!sUserManager.exists(userId)) return;
14222        final int uid = Binder.getCallingUid();
14223        final int permission = mContext.checkCallingOrSelfPermission(
14224                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14225        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14226        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14227        // writer
14228        synchronized (mPackages) {
14229            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14230                    allowedByPermission, uid, userId)) {
14231                scheduleWritePackageRestrictionsLocked(userId);
14232            }
14233        }
14234    }
14235
14236    @Override
14237    public String getInstallerPackageName(String packageName) {
14238        // reader
14239        synchronized (mPackages) {
14240            return mSettings.getInstallerPackageNameLPr(packageName);
14241        }
14242    }
14243
14244    @Override
14245    public int getApplicationEnabledSetting(String packageName, int userId) {
14246        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14247        int uid = Binder.getCallingUid();
14248        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14249        // reader
14250        synchronized (mPackages) {
14251            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14252        }
14253    }
14254
14255    @Override
14256    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14257        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14258        int uid = Binder.getCallingUid();
14259        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14260        // reader
14261        synchronized (mPackages) {
14262            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14263        }
14264    }
14265
14266    @Override
14267    public void enterSafeMode() {
14268        enforceSystemOrRoot("Only the system can request entering safe mode");
14269
14270        if (!mSystemReady) {
14271            mSafeMode = true;
14272        }
14273    }
14274
14275    @Override
14276    public void systemReady() {
14277        mSystemReady = true;
14278
14279        // Read the compatibilty setting when the system is ready.
14280        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14281                mContext.getContentResolver(),
14282                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14283        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14284        if (DEBUG_SETTINGS) {
14285            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14286        }
14287
14288        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14289
14290        synchronized (mPackages) {
14291            // Verify that all of the preferred activity components actually
14292            // exist.  It is possible for applications to be updated and at
14293            // that point remove a previously declared activity component that
14294            // had been set as a preferred activity.  We try to clean this up
14295            // the next time we encounter that preferred activity, but it is
14296            // possible for the user flow to never be able to return to that
14297            // situation so here we do a sanity check to make sure we haven't
14298            // left any junk around.
14299            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14300            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14301                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14302                removed.clear();
14303                for (PreferredActivity pa : pir.filterSet()) {
14304                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14305                        removed.add(pa);
14306                    }
14307                }
14308                if (removed.size() > 0) {
14309                    for (int r=0; r<removed.size(); r++) {
14310                        PreferredActivity pa = removed.get(r);
14311                        Slog.w(TAG, "Removing dangling preferred activity: "
14312                                + pa.mPref.mComponent);
14313                        pir.removeFilter(pa);
14314                    }
14315                    mSettings.writePackageRestrictionsLPr(
14316                            mSettings.mPreferredActivities.keyAt(i));
14317                }
14318            }
14319
14320            for (int userId : UserManagerService.getInstance().getUserIds()) {
14321                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14322                    grantPermissionsUserIds = ArrayUtils.appendInt(
14323                            grantPermissionsUserIds, userId);
14324                }
14325            }
14326        }
14327        sUserManager.systemReady();
14328
14329        // If we upgraded grant all default permissions before kicking off.
14330        for (int userId : grantPermissionsUserIds) {
14331            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14332        }
14333
14334        // Kick off any messages waiting for system ready
14335        if (mPostSystemReadyMessages != null) {
14336            for (Message msg : mPostSystemReadyMessages) {
14337                msg.sendToTarget();
14338            }
14339            mPostSystemReadyMessages = null;
14340        }
14341
14342        // Watch for external volumes that come and go over time
14343        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14344        storage.registerListener(mStorageListener);
14345
14346        mInstallerService.systemReady();
14347        mPackageDexOptimizer.systemReady();
14348    }
14349
14350    @Override
14351    public boolean isSafeMode() {
14352        return mSafeMode;
14353    }
14354
14355    @Override
14356    public boolean hasSystemUidErrors() {
14357        return mHasSystemUidErrors;
14358    }
14359
14360    static String arrayToString(int[] array) {
14361        StringBuffer buf = new StringBuffer(128);
14362        buf.append('[');
14363        if (array != null) {
14364            for (int i=0; i<array.length; i++) {
14365                if (i > 0) buf.append(", ");
14366                buf.append(array[i]);
14367            }
14368        }
14369        buf.append(']');
14370        return buf.toString();
14371    }
14372
14373    static class DumpState {
14374        public static final int DUMP_LIBS = 1 << 0;
14375        public static final int DUMP_FEATURES = 1 << 1;
14376        public static final int DUMP_RESOLVERS = 1 << 2;
14377        public static final int DUMP_PERMISSIONS = 1 << 3;
14378        public static final int DUMP_PACKAGES = 1 << 4;
14379        public static final int DUMP_SHARED_USERS = 1 << 5;
14380        public static final int DUMP_MESSAGES = 1 << 6;
14381        public static final int DUMP_PROVIDERS = 1 << 7;
14382        public static final int DUMP_VERIFIERS = 1 << 8;
14383        public static final int DUMP_PREFERRED = 1 << 9;
14384        public static final int DUMP_PREFERRED_XML = 1 << 10;
14385        public static final int DUMP_KEYSETS = 1 << 11;
14386        public static final int DUMP_VERSION = 1 << 12;
14387        public static final int DUMP_INSTALLS = 1 << 13;
14388        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14389        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14390
14391        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14392
14393        private int mTypes;
14394
14395        private int mOptions;
14396
14397        private boolean mTitlePrinted;
14398
14399        private SharedUserSetting mSharedUser;
14400
14401        public boolean isDumping(int type) {
14402            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14403                return true;
14404            }
14405
14406            return (mTypes & type) != 0;
14407        }
14408
14409        public void setDump(int type) {
14410            mTypes |= type;
14411        }
14412
14413        public boolean isOptionEnabled(int option) {
14414            return (mOptions & option) != 0;
14415        }
14416
14417        public void setOptionEnabled(int option) {
14418            mOptions |= option;
14419        }
14420
14421        public boolean onTitlePrinted() {
14422            final boolean printed = mTitlePrinted;
14423            mTitlePrinted = true;
14424            return printed;
14425        }
14426
14427        public boolean getTitlePrinted() {
14428            return mTitlePrinted;
14429        }
14430
14431        public void setTitlePrinted(boolean enabled) {
14432            mTitlePrinted = enabled;
14433        }
14434
14435        public SharedUserSetting getSharedUser() {
14436            return mSharedUser;
14437        }
14438
14439        public void setSharedUser(SharedUserSetting user) {
14440            mSharedUser = user;
14441        }
14442    }
14443
14444    @Override
14445    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14446        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14447                != PackageManager.PERMISSION_GRANTED) {
14448            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14449                    + Binder.getCallingPid()
14450                    + ", uid=" + Binder.getCallingUid()
14451                    + " without permission "
14452                    + android.Manifest.permission.DUMP);
14453            return;
14454        }
14455
14456        DumpState dumpState = new DumpState();
14457        boolean fullPreferred = false;
14458        boolean checkin = false;
14459
14460        String packageName = null;
14461        ArraySet<String> permissionNames = null;
14462
14463        int opti = 0;
14464        while (opti < args.length) {
14465            String opt = args[opti];
14466            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14467                break;
14468            }
14469            opti++;
14470
14471            if ("-a".equals(opt)) {
14472                // Right now we only know how to print all.
14473            } else if ("-h".equals(opt)) {
14474                pw.println("Package manager dump options:");
14475                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14476                pw.println("    --checkin: dump for a checkin");
14477                pw.println("    -f: print details of intent filters");
14478                pw.println("    -h: print this help");
14479                pw.println("  cmd may be one of:");
14480                pw.println("    l[ibraries]: list known shared libraries");
14481                pw.println("    f[ibraries]: list device features");
14482                pw.println("    k[eysets]: print known keysets");
14483                pw.println("    r[esolvers]: dump intent resolvers");
14484                pw.println("    perm[issions]: dump permissions");
14485                pw.println("    permission [name ...]: dump declaration and use of given permission");
14486                pw.println("    pref[erred]: print preferred package settings");
14487                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14488                pw.println("    prov[iders]: dump content providers");
14489                pw.println("    p[ackages]: dump installed packages");
14490                pw.println("    s[hared-users]: dump shared user IDs");
14491                pw.println("    m[essages]: print collected runtime messages");
14492                pw.println("    v[erifiers]: print package verifier info");
14493                pw.println("    version: print database version info");
14494                pw.println("    write: write current settings now");
14495                pw.println("    <package.name>: info about given package");
14496                pw.println("    installs: details about install sessions");
14497                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14498                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14499                return;
14500            } else if ("--checkin".equals(opt)) {
14501                checkin = true;
14502            } else if ("-f".equals(opt)) {
14503                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14504            } else {
14505                pw.println("Unknown argument: " + opt + "; use -h for help");
14506            }
14507        }
14508
14509        // Is the caller requesting to dump a particular piece of data?
14510        if (opti < args.length) {
14511            String cmd = args[opti];
14512            opti++;
14513            // Is this a package name?
14514            if ("android".equals(cmd) || cmd.contains(".")) {
14515                packageName = cmd;
14516                // When dumping a single package, we always dump all of its
14517                // filter information since the amount of data will be reasonable.
14518                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14519            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14520                dumpState.setDump(DumpState.DUMP_LIBS);
14521            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14522                dumpState.setDump(DumpState.DUMP_FEATURES);
14523            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14524                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14525            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14526                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14527            } else if ("permission".equals(cmd)) {
14528                if (opti >= args.length) {
14529                    pw.println("Error: permission requires permission name");
14530                    return;
14531                }
14532                permissionNames = new ArraySet<>();
14533                while (opti < args.length) {
14534                    permissionNames.add(args[opti]);
14535                    opti++;
14536                }
14537                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14538                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14539            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14540                dumpState.setDump(DumpState.DUMP_PREFERRED);
14541            } else if ("preferred-xml".equals(cmd)) {
14542                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14543                if (opti < args.length && "--full".equals(args[opti])) {
14544                    fullPreferred = true;
14545                    opti++;
14546                }
14547            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14548                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14549            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14550                dumpState.setDump(DumpState.DUMP_PACKAGES);
14551            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14552                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14553            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14554                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14555            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14556                dumpState.setDump(DumpState.DUMP_MESSAGES);
14557            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14558                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14559            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14560                    || "intent-filter-verifiers".equals(cmd)) {
14561                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14562            } else if ("version".equals(cmd)) {
14563                dumpState.setDump(DumpState.DUMP_VERSION);
14564            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14565                dumpState.setDump(DumpState.DUMP_KEYSETS);
14566            } else if ("installs".equals(cmd)) {
14567                dumpState.setDump(DumpState.DUMP_INSTALLS);
14568            } else if ("write".equals(cmd)) {
14569                synchronized (mPackages) {
14570                    mSettings.writeLPr();
14571                    pw.println("Settings written.");
14572                    return;
14573                }
14574            }
14575        }
14576
14577        if (checkin) {
14578            pw.println("vers,1");
14579        }
14580
14581        // reader
14582        synchronized (mPackages) {
14583            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14584                if (!checkin) {
14585                    if (dumpState.onTitlePrinted())
14586                        pw.println();
14587                    pw.println("Database versions:");
14588                    pw.print("  SDK Version:");
14589                    pw.print(" internal=");
14590                    pw.print(mSettings.mInternalSdkPlatform);
14591                    pw.print(" external=");
14592                    pw.println(mSettings.mExternalSdkPlatform);
14593                    pw.print("  DB Version:");
14594                    pw.print(" internal=");
14595                    pw.print(mSettings.mInternalDatabaseVersion);
14596                    pw.print(" external=");
14597                    pw.println(mSettings.mExternalDatabaseVersion);
14598                }
14599            }
14600
14601            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14602                if (!checkin) {
14603                    if (dumpState.onTitlePrinted())
14604                        pw.println();
14605                    pw.println("Verifiers:");
14606                    pw.print("  Required: ");
14607                    pw.print(mRequiredVerifierPackage);
14608                    pw.print(" (uid=");
14609                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14610                    pw.println(")");
14611                } else if (mRequiredVerifierPackage != null) {
14612                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14613                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14614                }
14615            }
14616
14617            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14618                    packageName == null) {
14619                if (mIntentFilterVerifierComponent != null) {
14620                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14621                    if (!checkin) {
14622                        if (dumpState.onTitlePrinted())
14623                            pw.println();
14624                        pw.println("Intent Filter Verifier:");
14625                        pw.print("  Using: ");
14626                        pw.print(verifierPackageName);
14627                        pw.print(" (uid=");
14628                        pw.print(getPackageUid(verifierPackageName, 0));
14629                        pw.println(")");
14630                    } else if (verifierPackageName != null) {
14631                        pw.print("ifv,"); pw.print(verifierPackageName);
14632                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14633                    }
14634                } else {
14635                    pw.println();
14636                    pw.println("No Intent Filter Verifier available!");
14637                }
14638            }
14639
14640            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14641                boolean printedHeader = false;
14642                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14643                while (it.hasNext()) {
14644                    String name = it.next();
14645                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14646                    if (!checkin) {
14647                        if (!printedHeader) {
14648                            if (dumpState.onTitlePrinted())
14649                                pw.println();
14650                            pw.println("Libraries:");
14651                            printedHeader = true;
14652                        }
14653                        pw.print("  ");
14654                    } else {
14655                        pw.print("lib,");
14656                    }
14657                    pw.print(name);
14658                    if (!checkin) {
14659                        pw.print(" -> ");
14660                    }
14661                    if (ent.path != null) {
14662                        if (!checkin) {
14663                            pw.print("(jar) ");
14664                            pw.print(ent.path);
14665                        } else {
14666                            pw.print(",jar,");
14667                            pw.print(ent.path);
14668                        }
14669                    } else {
14670                        if (!checkin) {
14671                            pw.print("(apk) ");
14672                            pw.print(ent.apk);
14673                        } else {
14674                            pw.print(",apk,");
14675                            pw.print(ent.apk);
14676                        }
14677                    }
14678                    pw.println();
14679                }
14680            }
14681
14682            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14683                if (dumpState.onTitlePrinted())
14684                    pw.println();
14685                if (!checkin) {
14686                    pw.println("Features:");
14687                }
14688                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14689                while (it.hasNext()) {
14690                    String name = it.next();
14691                    if (!checkin) {
14692                        pw.print("  ");
14693                    } else {
14694                        pw.print("feat,");
14695                    }
14696                    pw.println(name);
14697                }
14698            }
14699
14700            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14701                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14702                        : "Activity Resolver Table:", "  ", packageName,
14703                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14704                    dumpState.setTitlePrinted(true);
14705                }
14706                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14707                        : "Receiver Resolver Table:", "  ", packageName,
14708                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14709                    dumpState.setTitlePrinted(true);
14710                }
14711                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14712                        : "Service Resolver Table:", "  ", packageName,
14713                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14714                    dumpState.setTitlePrinted(true);
14715                }
14716                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14717                        : "Provider Resolver Table:", "  ", packageName,
14718                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14719                    dumpState.setTitlePrinted(true);
14720                }
14721            }
14722
14723            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14724                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14725                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14726                    int user = mSettings.mPreferredActivities.keyAt(i);
14727                    if (pir.dump(pw,
14728                            dumpState.getTitlePrinted()
14729                                ? "\nPreferred Activities User " + user + ":"
14730                                : "Preferred Activities User " + user + ":", "  ",
14731                            packageName, true, false)) {
14732                        dumpState.setTitlePrinted(true);
14733                    }
14734                }
14735            }
14736
14737            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14738                pw.flush();
14739                FileOutputStream fout = new FileOutputStream(fd);
14740                BufferedOutputStream str = new BufferedOutputStream(fout);
14741                XmlSerializer serializer = new FastXmlSerializer();
14742                try {
14743                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14744                    serializer.startDocument(null, true);
14745                    serializer.setFeature(
14746                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14747                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14748                    serializer.endDocument();
14749                    serializer.flush();
14750                } catch (IllegalArgumentException e) {
14751                    pw.println("Failed writing: " + e);
14752                } catch (IllegalStateException e) {
14753                    pw.println("Failed writing: " + e);
14754                } catch (IOException e) {
14755                    pw.println("Failed writing: " + e);
14756                }
14757            }
14758
14759            if (!checkin
14760                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14761                    && packageName == null) {
14762                pw.println();
14763                int count = mSettings.mPackages.size();
14764                if (count == 0) {
14765                    pw.println("No domain preferred apps!");
14766                    pw.println();
14767                } else {
14768                    final String prefix = "  ";
14769                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14770                    if (allPackageSettings.size() == 0) {
14771                        pw.println("No domain preferred apps!");
14772                        pw.println();
14773                    } else {
14774                        pw.println("Domain preferred apps status:");
14775                        pw.println();
14776                        count = 0;
14777                        for (PackageSetting ps : allPackageSettings) {
14778                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14779                            if (ivi == null || ivi.getPackageName() == null) continue;
14780                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14781                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14782                            pw.println(prefix + "Status: " + ivi.getStatusString());
14783                            pw.println();
14784                            count++;
14785                        }
14786                        if (count == 0) {
14787                            pw.println(prefix + "No domain preferred app status!");
14788                            pw.println();
14789                        }
14790                        for (int userId : sUserManager.getUserIds()) {
14791                            pw.println("Domain preferred apps for User " + userId + ":");
14792                            pw.println();
14793                            count = 0;
14794                            for (PackageSetting ps : allPackageSettings) {
14795                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14796                                if (ivi == null || ivi.getPackageName() == null) {
14797                                    continue;
14798                                }
14799                                final int status = ps.getDomainVerificationStatusForUser(userId);
14800                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14801                                    continue;
14802                                }
14803                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14804                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14805                                String statusStr = IntentFilterVerificationInfo.
14806                                        getStatusStringFromValue(status);
14807                                pw.println(prefix + "Status: " + statusStr);
14808                                pw.println();
14809                                count++;
14810                            }
14811                            if (count == 0) {
14812                                pw.println(prefix + "No domain preferred apps!");
14813                                pw.println();
14814                            }
14815                        }
14816                    }
14817                }
14818            }
14819
14820            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14821                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14822                if (packageName == null && permissionNames == null) {
14823                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14824                        if (iperm == 0) {
14825                            if (dumpState.onTitlePrinted())
14826                                pw.println();
14827                            pw.println("AppOp Permissions:");
14828                        }
14829                        pw.print("  AppOp Permission ");
14830                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14831                        pw.println(":");
14832                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14833                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14834                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14835                        }
14836                    }
14837                }
14838            }
14839
14840            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14841                boolean printedSomething = false;
14842                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14843                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14844                        continue;
14845                    }
14846                    if (!printedSomething) {
14847                        if (dumpState.onTitlePrinted())
14848                            pw.println();
14849                        pw.println("Registered ContentProviders:");
14850                        printedSomething = true;
14851                    }
14852                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14853                    pw.print("    "); pw.println(p.toString());
14854                }
14855                printedSomething = false;
14856                for (Map.Entry<String, PackageParser.Provider> entry :
14857                        mProvidersByAuthority.entrySet()) {
14858                    PackageParser.Provider p = entry.getValue();
14859                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14860                        continue;
14861                    }
14862                    if (!printedSomething) {
14863                        if (dumpState.onTitlePrinted())
14864                            pw.println();
14865                        pw.println("ContentProvider Authorities:");
14866                        printedSomething = true;
14867                    }
14868                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14869                    pw.print("    "); pw.println(p.toString());
14870                    if (p.info != null && p.info.applicationInfo != null) {
14871                        final String appInfo = p.info.applicationInfo.toString();
14872                        pw.print("      applicationInfo="); pw.println(appInfo);
14873                    }
14874                }
14875            }
14876
14877            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14878                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14879            }
14880
14881            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14882                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14883            }
14884
14885            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14886                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14887            }
14888
14889            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14890                // XXX should handle packageName != null by dumping only install data that
14891                // the given package is involved with.
14892                if (dumpState.onTitlePrinted()) pw.println();
14893                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14894            }
14895
14896            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14897                if (dumpState.onTitlePrinted()) pw.println();
14898                mSettings.dumpReadMessagesLPr(pw, dumpState);
14899
14900                pw.println();
14901                pw.println("Package warning messages:");
14902                BufferedReader in = null;
14903                String line = null;
14904                try {
14905                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14906                    while ((line = in.readLine()) != null) {
14907                        if (line.contains("ignored: updated version")) continue;
14908                        pw.println(line);
14909                    }
14910                } catch (IOException ignored) {
14911                } finally {
14912                    IoUtils.closeQuietly(in);
14913                }
14914            }
14915
14916            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14917                BufferedReader in = null;
14918                String line = null;
14919                try {
14920                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14921                    while ((line = in.readLine()) != null) {
14922                        if (line.contains("ignored: updated version")) continue;
14923                        pw.print("msg,");
14924                        pw.println(line);
14925                    }
14926                } catch (IOException ignored) {
14927                } finally {
14928                    IoUtils.closeQuietly(in);
14929                }
14930            }
14931        }
14932    }
14933
14934    // ------- apps on sdcard specific code -------
14935    static final boolean DEBUG_SD_INSTALL = false;
14936
14937    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14938
14939    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14940
14941    private boolean mMediaMounted = false;
14942
14943    static String getEncryptKey() {
14944        try {
14945            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14946                    SD_ENCRYPTION_KEYSTORE_NAME);
14947            if (sdEncKey == null) {
14948                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14949                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14950                if (sdEncKey == null) {
14951                    Slog.e(TAG, "Failed to create encryption keys");
14952                    return null;
14953                }
14954            }
14955            return sdEncKey;
14956        } catch (NoSuchAlgorithmException nsae) {
14957            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14958            return null;
14959        } catch (IOException ioe) {
14960            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14961            return null;
14962        }
14963    }
14964
14965    /*
14966     * Update media status on PackageManager.
14967     */
14968    @Override
14969    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14970        int callingUid = Binder.getCallingUid();
14971        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14972            throw new SecurityException("Media status can only be updated by the system");
14973        }
14974        // reader; this apparently protects mMediaMounted, but should probably
14975        // be a different lock in that case.
14976        synchronized (mPackages) {
14977            Log.i(TAG, "Updating external media status from "
14978                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14979                    + (mediaStatus ? "mounted" : "unmounted"));
14980            if (DEBUG_SD_INSTALL)
14981                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14982                        + ", mMediaMounted=" + mMediaMounted);
14983            if (mediaStatus == mMediaMounted) {
14984                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14985                        : 0, -1);
14986                mHandler.sendMessage(msg);
14987                return;
14988            }
14989            mMediaMounted = mediaStatus;
14990        }
14991        // Queue up an async operation since the package installation may take a
14992        // little while.
14993        mHandler.post(new Runnable() {
14994            public void run() {
14995                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14996            }
14997        });
14998    }
14999
15000    /**
15001     * Called by MountService when the initial ASECs to scan are available.
15002     * Should block until all the ASEC containers are finished being scanned.
15003     */
15004    public void scanAvailableAsecs() {
15005        updateExternalMediaStatusInner(true, false, false);
15006        if (mShouldRestoreconData) {
15007            SELinuxMMAC.setRestoreconDone();
15008            mShouldRestoreconData = false;
15009        }
15010    }
15011
15012    /*
15013     * Collect information of applications on external media, map them against
15014     * existing containers and update information based on current mount status.
15015     * Please note that we always have to report status if reportStatus has been
15016     * set to true especially when unloading packages.
15017     */
15018    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15019            boolean externalStorage) {
15020        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15021        int[] uidArr = EmptyArray.INT;
15022
15023        final String[] list = PackageHelper.getSecureContainerList();
15024        if (ArrayUtils.isEmpty(list)) {
15025            Log.i(TAG, "No secure containers found");
15026        } else {
15027            // Process list of secure containers and categorize them
15028            // as active or stale based on their package internal state.
15029
15030            // reader
15031            synchronized (mPackages) {
15032                for (String cid : list) {
15033                    // Leave stages untouched for now; installer service owns them
15034                    if (PackageInstallerService.isStageName(cid)) continue;
15035
15036                    if (DEBUG_SD_INSTALL)
15037                        Log.i(TAG, "Processing container " + cid);
15038                    String pkgName = getAsecPackageName(cid);
15039                    if (pkgName == null) {
15040                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15041                        continue;
15042                    }
15043                    if (DEBUG_SD_INSTALL)
15044                        Log.i(TAG, "Looking for pkg : " + pkgName);
15045
15046                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15047                    if (ps == null) {
15048                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15049                        continue;
15050                    }
15051
15052                    /*
15053                     * Skip packages that are not external if we're unmounting
15054                     * external storage.
15055                     */
15056                    if (externalStorage && !isMounted && !isExternal(ps)) {
15057                        continue;
15058                    }
15059
15060                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15061                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15062                    // The package status is changed only if the code path
15063                    // matches between settings and the container id.
15064                    if (ps.codePathString != null
15065                            && ps.codePathString.startsWith(args.getCodePath())) {
15066                        if (DEBUG_SD_INSTALL) {
15067                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15068                                    + " at code path: " + ps.codePathString);
15069                        }
15070
15071                        // We do have a valid package installed on sdcard
15072                        processCids.put(args, ps.codePathString);
15073                        final int uid = ps.appId;
15074                        if (uid != -1) {
15075                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15076                        }
15077                    } else {
15078                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15079                                + ps.codePathString);
15080                    }
15081                }
15082            }
15083
15084            Arrays.sort(uidArr);
15085        }
15086
15087        // Process packages with valid entries.
15088        if (isMounted) {
15089            if (DEBUG_SD_INSTALL)
15090                Log.i(TAG, "Loading packages");
15091            loadMediaPackages(processCids, uidArr);
15092            startCleaningPackages();
15093            mInstallerService.onSecureContainersAvailable();
15094        } else {
15095            if (DEBUG_SD_INSTALL)
15096                Log.i(TAG, "Unloading packages");
15097            unloadMediaPackages(processCids, uidArr, reportStatus);
15098        }
15099    }
15100
15101    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15102            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15103        final int size = infos.size();
15104        final String[] packageNames = new String[size];
15105        final int[] packageUids = new int[size];
15106        for (int i = 0; i < size; i++) {
15107            final ApplicationInfo info = infos.get(i);
15108            packageNames[i] = info.packageName;
15109            packageUids[i] = info.uid;
15110        }
15111        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15112                finishedReceiver);
15113    }
15114
15115    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15116            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15117        sendResourcesChangedBroadcast(mediaStatus, replacing,
15118                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15119    }
15120
15121    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15122            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15123        int size = pkgList.length;
15124        if (size > 0) {
15125            // Send broadcasts here
15126            Bundle extras = new Bundle();
15127            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15128            if (uidArr != null) {
15129                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15130            }
15131            if (replacing) {
15132                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15133            }
15134            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15135                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15136            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15137        }
15138    }
15139
15140   /*
15141     * Look at potentially valid container ids from processCids If package
15142     * information doesn't match the one on record or package scanning fails,
15143     * the cid is added to list of removeCids. We currently don't delete stale
15144     * containers.
15145     */
15146    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15147        ArrayList<String> pkgList = new ArrayList<String>();
15148        Set<AsecInstallArgs> keys = processCids.keySet();
15149
15150        for (AsecInstallArgs args : keys) {
15151            String codePath = processCids.get(args);
15152            if (DEBUG_SD_INSTALL)
15153                Log.i(TAG, "Loading container : " + args.cid);
15154            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15155            try {
15156                // Make sure there are no container errors first.
15157                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15158                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15159                            + " when installing from sdcard");
15160                    continue;
15161                }
15162                // Check code path here.
15163                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15164                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15165                            + " does not match one in settings " + codePath);
15166                    continue;
15167                }
15168                // Parse package
15169                int parseFlags = mDefParseFlags;
15170                if (args.isExternalAsec()) {
15171                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15172                }
15173                if (args.isFwdLocked()) {
15174                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15175                }
15176
15177                synchronized (mInstallLock) {
15178                    PackageParser.Package pkg = null;
15179                    try {
15180                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15181                    } catch (PackageManagerException e) {
15182                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15183                    }
15184                    // Scan the package
15185                    if (pkg != null) {
15186                        /*
15187                         * TODO why is the lock being held? doPostInstall is
15188                         * called in other places without the lock. This needs
15189                         * to be straightened out.
15190                         */
15191                        // writer
15192                        synchronized (mPackages) {
15193                            retCode = PackageManager.INSTALL_SUCCEEDED;
15194                            pkgList.add(pkg.packageName);
15195                            // Post process args
15196                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15197                                    pkg.applicationInfo.uid);
15198                        }
15199                    } else {
15200                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15201                    }
15202                }
15203
15204            } finally {
15205                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15206                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15207                }
15208            }
15209        }
15210        // writer
15211        synchronized (mPackages) {
15212            // If the platform SDK has changed since the last time we booted,
15213            // we need to re-grant app permission to catch any new ones that
15214            // appear. This is really a hack, and means that apps can in some
15215            // cases get permissions that the user didn't initially explicitly
15216            // allow... it would be nice to have some better way to handle
15217            // this situation.
15218            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15219            if (regrantPermissions)
15220                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15221                        + mSdkVersion + "; regranting permissions for external storage");
15222            mSettings.mExternalSdkPlatform = mSdkVersion;
15223
15224            // Make sure group IDs have been assigned, and any permission
15225            // changes in other apps are accounted for
15226            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15227                    | (regrantPermissions
15228                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15229                            : 0));
15230
15231            mSettings.updateExternalDatabaseVersion();
15232
15233            // can downgrade to reader
15234            // Persist settings
15235            mSettings.writeLPr();
15236        }
15237        // Send a broadcast to let everyone know we are done processing
15238        if (pkgList.size() > 0) {
15239            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15240        }
15241    }
15242
15243   /*
15244     * Utility method to unload a list of specified containers
15245     */
15246    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15247        // Just unmount all valid containers.
15248        for (AsecInstallArgs arg : cidArgs) {
15249            synchronized (mInstallLock) {
15250                arg.doPostDeleteLI(false);
15251           }
15252       }
15253   }
15254
15255    /*
15256     * Unload packages mounted on external media. This involves deleting package
15257     * data from internal structures, sending broadcasts about diabled packages,
15258     * gc'ing to free up references, unmounting all secure containers
15259     * corresponding to packages on external media, and posting a
15260     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15261     * that we always have to post this message if status has been requested no
15262     * matter what.
15263     */
15264    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15265            final boolean reportStatus) {
15266        if (DEBUG_SD_INSTALL)
15267            Log.i(TAG, "unloading media packages");
15268        ArrayList<String> pkgList = new ArrayList<String>();
15269        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15270        final Set<AsecInstallArgs> keys = processCids.keySet();
15271        for (AsecInstallArgs args : keys) {
15272            String pkgName = args.getPackageName();
15273            if (DEBUG_SD_INSTALL)
15274                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15275            // Delete package internally
15276            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15277            synchronized (mInstallLock) {
15278                boolean res = deletePackageLI(pkgName, null, false, null, null,
15279                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15280                if (res) {
15281                    pkgList.add(pkgName);
15282                } else {
15283                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15284                    failedList.add(args);
15285                }
15286            }
15287        }
15288
15289        // reader
15290        synchronized (mPackages) {
15291            // We didn't update the settings after removing each package;
15292            // write them now for all packages.
15293            mSettings.writeLPr();
15294        }
15295
15296        // We have to absolutely send UPDATED_MEDIA_STATUS only
15297        // after confirming that all the receivers processed the ordered
15298        // broadcast when packages get disabled, force a gc to clean things up.
15299        // and unload all the containers.
15300        if (pkgList.size() > 0) {
15301            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15302                    new IIntentReceiver.Stub() {
15303                public void performReceive(Intent intent, int resultCode, String data,
15304                        Bundle extras, boolean ordered, boolean sticky,
15305                        int sendingUser) throws RemoteException {
15306                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15307                            reportStatus ? 1 : 0, 1, keys);
15308                    mHandler.sendMessage(msg);
15309                }
15310            });
15311        } else {
15312            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15313                    keys);
15314            mHandler.sendMessage(msg);
15315        }
15316    }
15317
15318    private void loadPrivatePackages(VolumeInfo vol) {
15319        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15320        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15321        synchronized (mInstallLock) {
15322        synchronized (mPackages) {
15323            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15324            for (PackageSetting ps : packages) {
15325                final PackageParser.Package pkg;
15326                try {
15327                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15328                    loaded.add(pkg.applicationInfo);
15329                } catch (PackageManagerException e) {
15330                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15331                }
15332            }
15333
15334            // TODO: regrant any permissions that changed based since original install
15335
15336            mSettings.writeLPr();
15337        }
15338        }
15339
15340        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15341        sendResourcesChangedBroadcast(true, false, loaded, null);
15342    }
15343
15344    private void unloadPrivatePackages(VolumeInfo vol) {
15345        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15346        synchronized (mInstallLock) {
15347        synchronized (mPackages) {
15348            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15349            for (PackageSetting ps : packages) {
15350                if (ps.pkg == null) continue;
15351
15352                final ApplicationInfo info = ps.pkg.applicationInfo;
15353                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15354                if (deletePackageLI(ps.name, null, false, null, null,
15355                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15356                    unloaded.add(info);
15357                } else {
15358                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15359                }
15360            }
15361
15362            mSettings.writeLPr();
15363        }
15364        }
15365
15366        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15367        sendResourcesChangedBroadcast(false, false, unloaded, null);
15368    }
15369
15370    /**
15371     * Examine all users present on given mounted volume, and destroy data
15372     * belonging to users that are no longer valid, or whose user ID has been
15373     * recycled.
15374     */
15375    private void reconcileUsers(String volumeUuid) {
15376        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15377        if (ArrayUtils.isEmpty(files)) {
15378            Slog.d(TAG, "No users found on " + volumeUuid);
15379            return;
15380        }
15381
15382        for (File file : files) {
15383            if (!file.isDirectory()) continue;
15384
15385            final int userId;
15386            final UserInfo info;
15387            try {
15388                userId = Integer.parseInt(file.getName());
15389                info = sUserManager.getUserInfo(userId);
15390            } catch (NumberFormatException e) {
15391                Slog.w(TAG, "Invalid user directory " + file);
15392                continue;
15393            }
15394
15395            boolean destroyUser = false;
15396            if (info == null) {
15397                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15398                        + " because no matching user was found");
15399                destroyUser = true;
15400            } else {
15401                try {
15402                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15403                } catch (IOException e) {
15404                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15405                            + " because we failed to enforce serial number: " + e);
15406                    destroyUser = true;
15407                }
15408            }
15409
15410            if (destroyUser) {
15411                synchronized (mInstallLock) {
15412                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15413                }
15414            }
15415        }
15416
15417        final UserManager um = mContext.getSystemService(UserManager.class);
15418        for (UserInfo user : um.getUsers()) {
15419            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15420            if (userDir.exists()) continue;
15421
15422            try {
15423                UserManagerService.prepareUserDirectory(userDir);
15424                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15425            } catch (IOException e) {
15426                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15427            }
15428        }
15429    }
15430
15431    /**
15432     * Examine all apps present on given mounted volume, and destroy apps that
15433     * aren't expected, either due to uninstallation or reinstallation on
15434     * another volume.
15435     */
15436    private void reconcileApps(String volumeUuid) {
15437        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15438        if (ArrayUtils.isEmpty(files)) {
15439            Slog.d(TAG, "No apps found on " + volumeUuid);
15440            return;
15441        }
15442
15443        for (File file : files) {
15444            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15445                    && !PackageInstallerService.isStageName(file.getName());
15446            if (!isPackage) {
15447                // Ignore entries which are not packages
15448                continue;
15449            }
15450
15451            boolean destroyApp = false;
15452            String packageName = null;
15453            try {
15454                final PackageLite pkg = PackageParser.parsePackageLite(file,
15455                        PackageParser.PARSE_MUST_BE_APK);
15456                packageName = pkg.packageName;
15457
15458                synchronized (mPackages) {
15459                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15460                    if (ps == null) {
15461                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15462                                + volumeUuid + " because we found no install record");
15463                        destroyApp = true;
15464                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15465                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15466                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15467                        destroyApp = true;
15468                    }
15469                }
15470
15471            } catch (PackageParserException e) {
15472                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15473                destroyApp = true;
15474            }
15475
15476            if (destroyApp) {
15477                synchronized (mInstallLock) {
15478                    if (packageName != null) {
15479                        removeDataDirsLI(volumeUuid, packageName);
15480                    }
15481                    if (file.isDirectory()) {
15482                        mInstaller.rmPackageDir(file.getAbsolutePath());
15483                    } else {
15484                        file.delete();
15485                    }
15486                }
15487            }
15488        }
15489    }
15490
15491    private void unfreezePackage(String packageName) {
15492        synchronized (mPackages) {
15493            final PackageSetting ps = mSettings.mPackages.get(packageName);
15494            if (ps != null) {
15495                ps.frozen = false;
15496            }
15497        }
15498    }
15499
15500    @Override
15501    public int movePackage(final String packageName, final String volumeUuid) {
15502        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15503
15504        final int moveId = mNextMoveId.getAndIncrement();
15505        try {
15506            movePackageInternal(packageName, volumeUuid, moveId);
15507        } catch (PackageManagerException e) {
15508            Slog.w(TAG, "Failed to move " + packageName, e);
15509            mMoveCallbacks.notifyStatusChanged(moveId,
15510                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15511        }
15512        return moveId;
15513    }
15514
15515    private void movePackageInternal(final String packageName, final String volumeUuid,
15516            final int moveId) throws PackageManagerException {
15517        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15518        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15519        final PackageManager pm = mContext.getPackageManager();
15520
15521        final boolean currentAsec;
15522        final String currentVolumeUuid;
15523        final File codeFile;
15524        final String installerPackageName;
15525        final String packageAbiOverride;
15526        final int appId;
15527        final String seinfo;
15528        final String label;
15529
15530        // reader
15531        synchronized (mPackages) {
15532            final PackageParser.Package pkg = mPackages.get(packageName);
15533            final PackageSetting ps = mSettings.mPackages.get(packageName);
15534            if (pkg == null || ps == null) {
15535                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15536            }
15537
15538            if (pkg.applicationInfo.isSystemApp()) {
15539                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15540                        "Cannot move system application");
15541            }
15542
15543            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15544                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15545                        "Package already moved to " + volumeUuid);
15546            }
15547
15548            final File probe = new File(pkg.codePath);
15549            final File probeOat = new File(probe, "oat");
15550            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15551                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15552                        "Move only supported for modern cluster style installs");
15553            }
15554
15555            if (ps.frozen) {
15556                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15557                        "Failed to move already frozen package");
15558            }
15559            ps.frozen = true;
15560
15561            currentAsec = pkg.applicationInfo.isForwardLocked()
15562                    || pkg.applicationInfo.isExternalAsec();
15563            currentVolumeUuid = ps.volumeUuid;
15564            codeFile = new File(pkg.codePath);
15565            installerPackageName = ps.installerPackageName;
15566            packageAbiOverride = ps.cpuAbiOverrideString;
15567            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15568            seinfo = pkg.applicationInfo.seinfo;
15569            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15570        }
15571
15572        // Now that we're guarded by frozen state, kill app during move
15573        killApplication(packageName, appId, "move pkg");
15574
15575        final Bundle extras = new Bundle();
15576        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15577        extras.putString(Intent.EXTRA_TITLE, label);
15578        mMoveCallbacks.notifyCreated(moveId, extras);
15579
15580        int installFlags;
15581        final boolean moveCompleteApp;
15582        final File measurePath;
15583
15584        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15585            installFlags = INSTALL_INTERNAL;
15586            moveCompleteApp = !currentAsec;
15587            measurePath = Environment.getDataAppDirectory(volumeUuid);
15588        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15589            installFlags = INSTALL_EXTERNAL;
15590            moveCompleteApp = false;
15591            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15592        } else {
15593            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15594            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15595                    || !volume.isMountedWritable()) {
15596                unfreezePackage(packageName);
15597                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15598                        "Move location not mounted private volume");
15599            }
15600
15601            Preconditions.checkState(!currentAsec);
15602
15603            installFlags = INSTALL_INTERNAL;
15604            moveCompleteApp = true;
15605            measurePath = Environment.getDataAppDirectory(volumeUuid);
15606        }
15607
15608        final PackageStats stats = new PackageStats(null, -1);
15609        synchronized (mInstaller) {
15610            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15611                unfreezePackage(packageName);
15612                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15613                        "Failed to measure package size");
15614            }
15615        }
15616
15617        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15618                + stats.dataSize);
15619
15620        final long startFreeBytes = measurePath.getFreeSpace();
15621        final long sizeBytes;
15622        if (moveCompleteApp) {
15623            sizeBytes = stats.codeSize + stats.dataSize;
15624        } else {
15625            sizeBytes = stats.codeSize;
15626        }
15627
15628        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15629            unfreezePackage(packageName);
15630            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15631                    "Not enough free space to move");
15632        }
15633
15634        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15635
15636        final CountDownLatch installedLatch = new CountDownLatch(1);
15637        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15638            @Override
15639            public void onUserActionRequired(Intent intent) throws RemoteException {
15640                throw new IllegalStateException();
15641            }
15642
15643            @Override
15644            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15645                    Bundle extras) throws RemoteException {
15646                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15647                        + PackageManager.installStatusToString(returnCode, msg));
15648
15649                installedLatch.countDown();
15650
15651                // Regardless of success or failure of the move operation,
15652                // always unfreeze the package
15653                unfreezePackage(packageName);
15654
15655                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15656                switch (status) {
15657                    case PackageInstaller.STATUS_SUCCESS:
15658                        mMoveCallbacks.notifyStatusChanged(moveId,
15659                                PackageManager.MOVE_SUCCEEDED);
15660                        break;
15661                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15662                        mMoveCallbacks.notifyStatusChanged(moveId,
15663                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15664                        break;
15665                    default:
15666                        mMoveCallbacks.notifyStatusChanged(moveId,
15667                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15668                        break;
15669                }
15670            }
15671        };
15672
15673        final MoveInfo move;
15674        if (moveCompleteApp) {
15675            // Kick off a thread to report progress estimates
15676            new Thread() {
15677                @Override
15678                public void run() {
15679                    while (true) {
15680                        try {
15681                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15682                                break;
15683                            }
15684                        } catch (InterruptedException ignored) {
15685                        }
15686
15687                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15688                        final int progress = 10 + (int) MathUtils.constrain(
15689                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15690                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15691                    }
15692                }
15693            }.start();
15694
15695            final String dataAppName = codeFile.getName();
15696            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15697                    dataAppName, appId, seinfo);
15698        } else {
15699            move = null;
15700        }
15701
15702        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15703
15704        final Message msg = mHandler.obtainMessage(INIT_COPY);
15705        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15706        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15707                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15708        mHandler.sendMessage(msg);
15709    }
15710
15711    @Override
15712    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15713        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15714
15715        final int realMoveId = mNextMoveId.getAndIncrement();
15716        final Bundle extras = new Bundle();
15717        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15718        mMoveCallbacks.notifyCreated(realMoveId, extras);
15719
15720        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15721            @Override
15722            public void onCreated(int moveId, Bundle extras) {
15723                // Ignored
15724            }
15725
15726            @Override
15727            public void onStatusChanged(int moveId, int status, long estMillis) {
15728                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15729            }
15730        };
15731
15732        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15733        storage.setPrimaryStorageUuid(volumeUuid, callback);
15734        return realMoveId;
15735    }
15736
15737    @Override
15738    public int getMoveStatus(int moveId) {
15739        mContext.enforceCallingOrSelfPermission(
15740                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15741        return mMoveCallbacks.mLastStatus.get(moveId);
15742    }
15743
15744    @Override
15745    public void registerMoveCallback(IPackageMoveObserver callback) {
15746        mContext.enforceCallingOrSelfPermission(
15747                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15748        mMoveCallbacks.register(callback);
15749    }
15750
15751    @Override
15752    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15753        mContext.enforceCallingOrSelfPermission(
15754                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15755        mMoveCallbacks.unregister(callback);
15756    }
15757
15758    @Override
15759    public boolean setInstallLocation(int loc) {
15760        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15761                null);
15762        if (getInstallLocation() == loc) {
15763            return true;
15764        }
15765        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15766                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15767            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15768                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15769            return true;
15770        }
15771        return false;
15772   }
15773
15774    @Override
15775    public int getInstallLocation() {
15776        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15777                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15778                PackageHelper.APP_INSTALL_AUTO);
15779    }
15780
15781    /** Called by UserManagerService */
15782    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15783        mDirtyUsers.remove(userHandle);
15784        mSettings.removeUserLPw(userHandle);
15785        mPendingBroadcasts.remove(userHandle);
15786        if (mInstaller != null) {
15787            // Technically, we shouldn't be doing this with the package lock
15788            // held.  However, this is very rare, and there is already so much
15789            // other disk I/O going on, that we'll let it slide for now.
15790            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15791            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15792                final String volumeUuid = vol.getFsUuid();
15793                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15794                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15795            }
15796        }
15797        mUserNeedsBadging.delete(userHandle);
15798        removeUnusedPackagesLILPw(userManager, userHandle);
15799    }
15800
15801    /**
15802     * We're removing userHandle and would like to remove any downloaded packages
15803     * that are no longer in use by any other user.
15804     * @param userHandle the user being removed
15805     */
15806    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15807        final boolean DEBUG_CLEAN_APKS = false;
15808        int [] users = userManager.getUserIdsLPr();
15809        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15810        while (psit.hasNext()) {
15811            PackageSetting ps = psit.next();
15812            if (ps.pkg == null) {
15813                continue;
15814            }
15815            final String packageName = ps.pkg.packageName;
15816            // Skip over if system app
15817            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15818                continue;
15819            }
15820            if (DEBUG_CLEAN_APKS) {
15821                Slog.i(TAG, "Checking package " + packageName);
15822            }
15823            boolean keep = false;
15824            for (int i = 0; i < users.length; i++) {
15825                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15826                    keep = true;
15827                    if (DEBUG_CLEAN_APKS) {
15828                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15829                                + users[i]);
15830                    }
15831                    break;
15832                }
15833            }
15834            if (!keep) {
15835                if (DEBUG_CLEAN_APKS) {
15836                    Slog.i(TAG, "  Removing package " + packageName);
15837                }
15838                mHandler.post(new Runnable() {
15839                    public void run() {
15840                        deletePackageX(packageName, userHandle, 0);
15841                    } //end run
15842                });
15843            }
15844        }
15845    }
15846
15847    /** Called by UserManagerService */
15848    void createNewUserLILPw(int userHandle) {
15849        if (mInstaller != null) {
15850            mInstaller.createUserConfig(userHandle);
15851            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15852            applyFactoryDefaultBrowserLPw(userHandle);
15853        }
15854    }
15855
15856    void newUserCreatedLILPw(final int userHandle) {
15857        // We cannot grant the default permissions with a lock held as
15858        // we query providers from other components for default handlers
15859        // such as enabled IMEs, etc.
15860        mHandler.post(new Runnable() {
15861            @Override
15862            public void run() {
15863                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15864            }
15865        });
15866    }
15867
15868    @Override
15869    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15870        mContext.enforceCallingOrSelfPermission(
15871                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15872                "Only package verification agents can read the verifier device identity");
15873
15874        synchronized (mPackages) {
15875            return mSettings.getVerifierDeviceIdentityLPw();
15876        }
15877    }
15878
15879    @Override
15880    public void setPermissionEnforced(String permission, boolean enforced) {
15881        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15882        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15883            synchronized (mPackages) {
15884                if (mSettings.mReadExternalStorageEnforced == null
15885                        || mSettings.mReadExternalStorageEnforced != enforced) {
15886                    mSettings.mReadExternalStorageEnforced = enforced;
15887                    mSettings.writeLPr();
15888                }
15889            }
15890            // kill any non-foreground processes so we restart them and
15891            // grant/revoke the GID.
15892            final IActivityManager am = ActivityManagerNative.getDefault();
15893            if (am != null) {
15894                final long token = Binder.clearCallingIdentity();
15895                try {
15896                    am.killProcessesBelowForeground("setPermissionEnforcement");
15897                } catch (RemoteException e) {
15898                } finally {
15899                    Binder.restoreCallingIdentity(token);
15900                }
15901            }
15902        } else {
15903            throw new IllegalArgumentException("No selective enforcement for " + permission);
15904        }
15905    }
15906
15907    @Override
15908    @Deprecated
15909    public boolean isPermissionEnforced(String permission) {
15910        return true;
15911    }
15912
15913    @Override
15914    public boolean isStorageLow() {
15915        final long token = Binder.clearCallingIdentity();
15916        try {
15917            final DeviceStorageMonitorInternal
15918                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15919            if (dsm != null) {
15920                return dsm.isMemoryLow();
15921            } else {
15922                return false;
15923            }
15924        } finally {
15925            Binder.restoreCallingIdentity(token);
15926        }
15927    }
15928
15929    @Override
15930    public IPackageInstaller getPackageInstaller() {
15931        return mInstallerService;
15932    }
15933
15934    private boolean userNeedsBadging(int userId) {
15935        int index = mUserNeedsBadging.indexOfKey(userId);
15936        if (index < 0) {
15937            final UserInfo userInfo;
15938            final long token = Binder.clearCallingIdentity();
15939            try {
15940                userInfo = sUserManager.getUserInfo(userId);
15941            } finally {
15942                Binder.restoreCallingIdentity(token);
15943            }
15944            final boolean b;
15945            if (userInfo != null && userInfo.isManagedProfile()) {
15946                b = true;
15947            } else {
15948                b = false;
15949            }
15950            mUserNeedsBadging.put(userId, b);
15951            return b;
15952        }
15953        return mUserNeedsBadging.valueAt(index);
15954    }
15955
15956    @Override
15957    public KeySet getKeySetByAlias(String packageName, String alias) {
15958        if (packageName == null || alias == null) {
15959            return null;
15960        }
15961        synchronized(mPackages) {
15962            final PackageParser.Package pkg = mPackages.get(packageName);
15963            if (pkg == null) {
15964                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15965                throw new IllegalArgumentException("Unknown package: " + packageName);
15966            }
15967            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15968            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15969        }
15970    }
15971
15972    @Override
15973    public KeySet getSigningKeySet(String packageName) {
15974        if (packageName == null) {
15975            return null;
15976        }
15977        synchronized(mPackages) {
15978            final PackageParser.Package pkg = mPackages.get(packageName);
15979            if (pkg == null) {
15980                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15981                throw new IllegalArgumentException("Unknown package: " + packageName);
15982            }
15983            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15984                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15985                throw new SecurityException("May not access signing KeySet of other apps.");
15986            }
15987            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15988            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15989        }
15990    }
15991
15992    @Override
15993    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15994        if (packageName == null || ks == null) {
15995            return false;
15996        }
15997        synchronized(mPackages) {
15998            final PackageParser.Package pkg = mPackages.get(packageName);
15999            if (pkg == null) {
16000                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16001                throw new IllegalArgumentException("Unknown package: " + packageName);
16002            }
16003            IBinder ksh = ks.getToken();
16004            if (ksh instanceof KeySetHandle) {
16005                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16006                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16007            }
16008            return false;
16009        }
16010    }
16011
16012    @Override
16013    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16014        if (packageName == null || ks == null) {
16015            return false;
16016        }
16017        synchronized(mPackages) {
16018            final PackageParser.Package pkg = mPackages.get(packageName);
16019            if (pkg == null) {
16020                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16021                throw new IllegalArgumentException("Unknown package: " + packageName);
16022            }
16023            IBinder ksh = ks.getToken();
16024            if (ksh instanceof KeySetHandle) {
16025                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16026                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16027            }
16028            return false;
16029        }
16030    }
16031
16032    public void getUsageStatsIfNoPackageUsageInfo() {
16033        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16034            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16035            if (usm == null) {
16036                throw new IllegalStateException("UsageStatsManager must be initialized");
16037            }
16038            long now = System.currentTimeMillis();
16039            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16040            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16041                String packageName = entry.getKey();
16042                PackageParser.Package pkg = mPackages.get(packageName);
16043                if (pkg == null) {
16044                    continue;
16045                }
16046                UsageStats usage = entry.getValue();
16047                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16048                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16049            }
16050        }
16051    }
16052
16053    /**
16054     * Check and throw if the given before/after packages would be considered a
16055     * downgrade.
16056     */
16057    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16058            throws PackageManagerException {
16059        if (after.versionCode < before.mVersionCode) {
16060            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16061                    "Update version code " + after.versionCode + " is older than current "
16062                    + before.mVersionCode);
16063        } else if (after.versionCode == before.mVersionCode) {
16064            if (after.baseRevisionCode < before.baseRevisionCode) {
16065                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16066                        "Update base revision code " + after.baseRevisionCode
16067                        + " is older than current " + before.baseRevisionCode);
16068            }
16069
16070            if (!ArrayUtils.isEmpty(after.splitNames)) {
16071                for (int i = 0; i < after.splitNames.length; i++) {
16072                    final String splitName = after.splitNames[i];
16073                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16074                    if (j != -1) {
16075                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16076                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16077                                    "Update split " + splitName + " revision code "
16078                                    + after.splitRevisionCodes[i] + " is older than current "
16079                                    + before.splitRevisionCodes[j]);
16080                        }
16081                    }
16082                }
16083            }
16084        }
16085    }
16086
16087    private static class MoveCallbacks extends Handler {
16088        private static final int MSG_CREATED = 1;
16089        private static final int MSG_STATUS_CHANGED = 2;
16090
16091        private final RemoteCallbackList<IPackageMoveObserver>
16092                mCallbacks = new RemoteCallbackList<>();
16093
16094        private final SparseIntArray mLastStatus = new SparseIntArray();
16095
16096        public MoveCallbacks(Looper looper) {
16097            super(looper);
16098        }
16099
16100        public void register(IPackageMoveObserver callback) {
16101            mCallbacks.register(callback);
16102        }
16103
16104        public void unregister(IPackageMoveObserver callback) {
16105            mCallbacks.unregister(callback);
16106        }
16107
16108        @Override
16109        public void handleMessage(Message msg) {
16110            final SomeArgs args = (SomeArgs) msg.obj;
16111            final int n = mCallbacks.beginBroadcast();
16112            for (int i = 0; i < n; i++) {
16113                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16114                try {
16115                    invokeCallback(callback, msg.what, args);
16116                } catch (RemoteException ignored) {
16117                }
16118            }
16119            mCallbacks.finishBroadcast();
16120            args.recycle();
16121        }
16122
16123        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16124                throws RemoteException {
16125            switch (what) {
16126                case MSG_CREATED: {
16127                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16128                    break;
16129                }
16130                case MSG_STATUS_CHANGED: {
16131                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16132                    break;
16133                }
16134            }
16135        }
16136
16137        private void notifyCreated(int moveId, Bundle extras) {
16138            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16139
16140            final SomeArgs args = SomeArgs.obtain();
16141            args.argi1 = moveId;
16142            args.arg2 = extras;
16143            obtainMessage(MSG_CREATED, args).sendToTarget();
16144        }
16145
16146        private void notifyStatusChanged(int moveId, int status) {
16147            notifyStatusChanged(moveId, status, -1);
16148        }
16149
16150        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16151            Slog.v(TAG, "Move " + moveId + " status " + status);
16152
16153            final SomeArgs args = SomeArgs.obtain();
16154            args.argi1 = moveId;
16155            args.argi2 = status;
16156            args.arg3 = estMillis;
16157            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16158
16159            synchronized (mLastStatus) {
16160                mLastStatus.put(moveId, status);
16161            }
16162        }
16163    }
16164
16165    private final class OnPermissionChangeListeners extends Handler {
16166        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16167
16168        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16169                new RemoteCallbackList<>();
16170
16171        public OnPermissionChangeListeners(Looper looper) {
16172            super(looper);
16173        }
16174
16175        @Override
16176        public void handleMessage(Message msg) {
16177            switch (msg.what) {
16178                case MSG_ON_PERMISSIONS_CHANGED: {
16179                    final int uid = msg.arg1;
16180                    handleOnPermissionsChanged(uid);
16181                } break;
16182            }
16183        }
16184
16185        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16186            mPermissionListeners.register(listener);
16187
16188        }
16189
16190        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16191            mPermissionListeners.unregister(listener);
16192        }
16193
16194        public void onPermissionsChanged(int uid) {
16195            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16196                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16197            }
16198        }
16199
16200        private void handleOnPermissionsChanged(int uid) {
16201            final int count = mPermissionListeners.beginBroadcast();
16202            try {
16203                for (int i = 0; i < count; i++) {
16204                    IOnPermissionsChangeListener callback = mPermissionListeners
16205                            .getBroadcastItem(i);
16206                    try {
16207                        callback.onPermissionsChanged(uid);
16208                    } catch (RemoteException e) {
16209                        Log.e(TAG, "Permission listener is dead", e);
16210                    }
16211                }
16212            } finally {
16213                mPermissionListeners.finishBroadcast();
16214            }
16215        }
16216    }
16217
16218    private class PackageManagerInternalImpl extends PackageManagerInternal {
16219        @Override
16220        public void setLocationPackagesProvider(PackagesProvider provider) {
16221            synchronized (mPackages) {
16222                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16223            }
16224        }
16225
16226        @Override
16227        public void setImePackagesProvider(PackagesProvider provider) {
16228            synchronized (mPackages) {
16229                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16230            }
16231        }
16232
16233        @Override
16234        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16235            synchronized (mPackages) {
16236                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16237            }
16238        }
16239
16240        @Override
16241        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16242            synchronized (mPackages) {
16243                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16244            }
16245        }
16246
16247        @Override
16248        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16249            synchronized (mPackages) {
16250                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16251            }
16252        }
16253
16254        @Override
16255        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16256            synchronized (mPackages) {
16257                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16258            }
16259        }
16260
16261        @Override
16262        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16263            synchronized (mPackages) {
16264                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16265                        packageName, userId);
16266            }
16267        }
16268
16269        @Override
16270        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16271            synchronized (mPackages) {
16272                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16273                        packageName, userId);
16274            }
16275        }
16276    }
16277
16278    @Override
16279    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16280        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16281        synchronized (mPackages) {
16282            final long identity = Binder.clearCallingIdentity();
16283            try {
16284                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16285                        packageNames, userId);
16286            } finally {
16287                Binder.restoreCallingIdentity(identity);
16288            }
16289        }
16290    }
16291
16292    private static void enforceSystemOrPhoneCaller(String tag) {
16293        int callingUid = Binder.getCallingUid();
16294        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16295            throw new SecurityException(
16296                    "Cannot call " + tag + " from UID " + callingUid);
16297        }
16298    }
16299}
16300