PackageManagerService.java revision 3f4c7e3f7ed4f2a3077993ebf545c2790ace246c
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.AppGlobals;
77import android.app.IActivityManager;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.app.usage.UsageStats;
81import android.app.usage.UsageStatsManager;
82import android.content.BroadcastReceiver;
83import android.content.ComponentName;
84import android.content.Context;
85import android.content.IIntentReceiver;
86import android.content.Intent;
87import android.content.IntentFilter;
88import android.content.IntentSender;
89import android.content.IntentSender.SendIntentException;
90import android.content.ServiceConnection;
91import android.content.pm.ActivityInfo;
92import android.content.pm.ApplicationInfo;
93import android.content.pm.FeatureInfo;
94import android.content.pm.IOnPermissionsChangeListener;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageManagerInternal;
114import android.content.pm.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlPullParserException;
216import org.xmlpull.v1.XmlSerializer;
217
218import java.io.BufferedInputStream;
219import java.io.BufferedOutputStream;
220import java.io.BufferedReader;
221import java.io.ByteArrayInputStream;
222import java.io.ByteArrayOutputStream;
223import java.io.File;
224import java.io.FileDescriptor;
225import java.io.FileNotFoundException;
226import java.io.FileOutputStream;
227import java.io.FileReader;
228import java.io.FilenameFilter;
229import java.io.IOException;
230import java.io.InputStream;
231import java.io.PrintWriter;
232import java.nio.charset.StandardCharsets;
233import java.security.NoSuchAlgorithmException;
234import java.security.PublicKey;
235import java.security.cert.CertificateEncodingException;
236import java.security.cert.CertificateException;
237import java.text.SimpleDateFormat;
238import java.util.ArrayList;
239import java.util.Arrays;
240import java.util.Collection;
241import java.util.Collections;
242import java.util.Comparator;
243import java.util.Date;
244import java.util.Iterator;
245import java.util.List;
246import java.util.Map;
247import java.util.Objects;
248import java.util.Set;
249import java.util.concurrent.CountDownLatch;
250import java.util.concurrent.TimeUnit;
251import java.util.concurrent.atomic.AtomicBoolean;
252import java.util.concurrent.atomic.AtomicInteger;
253import java.util.concurrent.atomic.AtomicLong;
254
255/**
256 * Keep track of all those .apks everywhere.
257 *
258 * This is very central to the platform's security; please run the unit
259 * tests whenever making modifications here:
260 *
261mmm frameworks/base/tests/AndroidTests
262adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
263adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
264 *
265 * {@hide}
266 */
267public class PackageManagerService extends IPackageManager.Stub {
268    static final String TAG = "PackageManager";
269    static final boolean DEBUG_SETTINGS = false;
270    static final boolean DEBUG_PREFERRED = false;
271    static final boolean DEBUG_UPGRADE = false;
272    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
273    private static final boolean DEBUG_BACKUP = true;
274    private static final boolean DEBUG_INSTALL = false;
275    private static final boolean DEBUG_REMOVE = false;
276    private static final boolean DEBUG_BROADCASTS = false;
277    private static final boolean DEBUG_SHOW_INFO = false;
278    private static final boolean DEBUG_PACKAGE_INFO = false;
279    private static final boolean DEBUG_INTENT_MATCHING = false;
280    private static final boolean DEBUG_PACKAGE_SCANNING = false;
281    private static final boolean DEBUG_VERIFY = false;
282    private static final boolean DEBUG_DEXOPT = false;
283    private static final boolean DEBUG_ABI_SELECTION = false;
284
285    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
286
287    private static final int RADIO_UID = Process.PHONE_UID;
288    private static final int LOG_UID = Process.LOG_UID;
289    private static final int NFC_UID = Process.NFC_UID;
290    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
291    private static final int SHELL_UID = Process.SHELL_UID;
292
293    // Cap the size of permission trees that 3rd party apps can define
294    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
295
296    // Suffix used during package installation when copying/moving
297    // package apks to install directory.
298    private static final String INSTALL_PACKAGE_SUFFIX = "-";
299
300    static final int SCAN_NO_DEX = 1<<1;
301    static final int SCAN_FORCE_DEX = 1<<2;
302    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
303    static final int SCAN_NEW_INSTALL = 1<<4;
304    static final int SCAN_NO_PATHS = 1<<5;
305    static final int SCAN_UPDATE_TIME = 1<<6;
306    static final int SCAN_DEFER_DEX = 1<<7;
307    static final int SCAN_BOOTING = 1<<8;
308    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
309    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
310    static final int SCAN_REQUIRE_KNOWN = 1<<12;
311    static final int SCAN_MOVE = 1<<13;
312
313    static final int REMOVE_CHATTY = 1<<16;
314
315    private static final int[] EMPTY_INT_ARRAY = new int[0];
316
317    /**
318     * Timeout (in milliseconds) after which the watchdog should declare that
319     * our handler thread is wedged.  The usual default for such things is one
320     * minute but we sometimes do very lengthy I/O operations on this thread,
321     * such as installing multi-gigabyte applications, so ours needs to be longer.
322     */
323    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
324
325    /**
326     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
327     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
328     * settings entry if available, otherwise we use the hardcoded default.  If it's been
329     * more than this long since the last fstrim, we force one during the boot sequence.
330     *
331     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
332     * one gets run at the next available charging+idle time.  This final mandatory
333     * no-fstrim check kicks in only of the other scheduling criteria is never met.
334     */
335    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
336
337    /**
338     * Whether verification is enabled by default.
339     */
340    private static final boolean DEFAULT_VERIFY_ENABLE = true;
341
342    /**
343     * The default maximum time to wait for the verification agent to return in
344     * milliseconds.
345     */
346    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
347
348    /**
349     * The default response for package verification timeout.
350     *
351     * This can be either PackageManager.VERIFICATION_ALLOW or
352     * PackageManager.VERIFICATION_REJECT.
353     */
354    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
355
356    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
357
358    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
359            DEFAULT_CONTAINER_PACKAGE,
360            "com.android.defcontainer.DefaultContainerService");
361
362    private static final String KILL_APP_REASON_GIDS_CHANGED =
363            "permission grant or revoke changed gids";
364
365    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
366            "permissions revoked";
367
368    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
369
370    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
371
372    /** Permission grant: not grant the permission. */
373    private static final int GRANT_DENIED = 1;
374
375    /** Permission grant: grant the permission as an install permission. */
376    private static final int GRANT_INSTALL = 2;
377
378    /** Permission grant: grant the permission as an install permission for a legacy app. */
379    private static final int GRANT_INSTALL_LEGACY = 3;
380
381    /** Permission grant: grant the permission as a runtime one. */
382    private static final int GRANT_RUNTIME = 4;
383
384    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
385    private static final int GRANT_UPGRADE = 5;
386
387    final ServiceThread mHandlerThread;
388
389    final PackageHandler mHandler;
390
391    /**
392     * Messages for {@link #mHandler} that need to wait for system ready before
393     * being dispatched.
394     */
395    private ArrayList<Message> mPostSystemReadyMessages;
396
397    final int mSdkVersion = Build.VERSION.SDK_INT;
398
399    final Context mContext;
400    final boolean mFactoryTest;
401    final boolean mOnlyCore;
402    final boolean mLazyDexOpt;
403    final long mDexOptLRUThresholdInMills;
404    final DisplayMetrics mMetrics;
405    final int mDefParseFlags;
406    final String[] mSeparateProcesses;
407    final boolean mIsUpgrade;
408
409    // This is where all application persistent data goes.
410    final File mAppDataDir;
411
412    // This is where all application persistent data goes for secondary users.
413    final File mUserAppDataDir;
414
415    /** The location for ASEC container files on internal storage. */
416    final String mAsecInternalPath;
417
418    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
419    // LOCK HELD.  Can be called with mInstallLock held.
420    final Installer mInstaller;
421
422    /** Directory where installed third-party apps stored */
423    final File mAppInstallDir;
424
425    /**
426     * Directory to which applications installed internally have their
427     * 32 bit native libraries copied.
428     */
429    private File mAppLib32InstallDir;
430
431    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
432    // apps.
433    final File mDrmAppPrivateInstallDir;
434
435    // ----------------------------------------------------------------
436
437    // Lock for state used when installing and doing other long running
438    // operations.  Methods that must be called with this lock held have
439    // the suffix "LI".
440    final Object mInstallLock = new Object();
441
442    // ----------------------------------------------------------------
443
444    // Keys are String (package name), values are Package.  This also serves
445    // as the lock for the global state.  Methods that must be called with
446    // this lock held have the prefix "LP".
447    final ArrayMap<String, PackageParser.Package> mPackages =
448            new ArrayMap<String, PackageParser.Package>();
449
450    // Tracks available target package names -> overlay package paths.
451    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
452        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
453
454    final Settings mSettings;
455    boolean mRestoredSettings;
456
457    // System configuration read by SystemConfig.
458    final int[] mGlobalGids;
459    final SparseArray<ArraySet<String>> mSystemPermissions;
460    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
461
462    // If mac_permissions.xml was found for seinfo labeling.
463    boolean mFoundPolicyFile;
464
465    // If a recursive restorecon of /data/data/<pkg> is needed.
466    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
467
468    public static final class SharedLibraryEntry {
469        public final String path;
470        public final String apk;
471
472        SharedLibraryEntry(String _path, String _apk) {
473            path = _path;
474            apk = _apk;
475        }
476    }
477
478    // Currently known shared libraries.
479    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
480            new ArrayMap<String, SharedLibraryEntry>();
481
482    // All available activities, for your resolving pleasure.
483    final ActivityIntentResolver mActivities =
484            new ActivityIntentResolver();
485
486    // All available receivers, for your resolving pleasure.
487    final ActivityIntentResolver mReceivers =
488            new ActivityIntentResolver();
489
490    // All available services, for your resolving pleasure.
491    final ServiceIntentResolver mServices = new ServiceIntentResolver();
492
493    // All available providers, for your resolving pleasure.
494    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
495
496    // Mapping from provider base names (first directory in content URI codePath)
497    // to the provider information.
498    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
499            new ArrayMap<String, PackageParser.Provider>();
500
501    // Mapping from instrumentation class names to info about them.
502    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
503            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
504
505    // Mapping from permission names to info about them.
506    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
507            new ArrayMap<String, PackageParser.PermissionGroup>();
508
509    // Packages whose data we have transfered into another package, thus
510    // should no longer exist.
511    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
512
513    // Broadcast actions that are only available to the system.
514    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
515
516    /** List of packages waiting for verification. */
517    final SparseArray<PackageVerificationState> mPendingVerification
518            = new SparseArray<PackageVerificationState>();
519
520    /** Set of packages associated with each app op permission. */
521    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
522
523    final PackageInstallerService mInstallerService;
524
525    private final PackageDexOptimizer mPackageDexOptimizer;
526
527    private AtomicInteger mNextMoveId = new AtomicInteger();
528    private final MoveCallbacks mMoveCallbacks;
529
530    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
531
532    // Cache of users who need badging.
533    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
534
535    /** Token for keys in mPendingVerification. */
536    private int mPendingVerificationToken = 0;
537
538    volatile boolean mSystemReady;
539    volatile boolean mSafeMode;
540    volatile boolean mHasSystemUidErrors;
541
542    ApplicationInfo mAndroidApplication;
543    final ActivityInfo mResolveActivity = new ActivityInfo();
544    final ResolveInfo mResolveInfo = new ResolveInfo();
545    ComponentName mResolveComponentName;
546    PackageParser.Package mPlatformPackage;
547    ComponentName mCustomResolverComponentName;
548
549    boolean mResolverReplaced = false;
550
551    private final ComponentName mIntentFilterVerifierComponent;
552    private int mIntentFilterVerificationToken = 0;
553
554    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
555            = new SparseArray<IntentFilterVerificationState>();
556
557    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
558            new DefaultPermissionGrantPolicy(this);
559
560    private static class IFVerificationParams {
561        PackageParser.Package pkg;
562        boolean replacing;
563        int userId;
564        int verifierUid;
565
566        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
567                int _userId, int _verifierUid) {
568            pkg = _pkg;
569            replacing = _replacing;
570            userId = _userId;
571            replacing = _replacing;
572            verifierUid = _verifierUid;
573        }
574    }
575
576    private interface IntentFilterVerifier<T extends IntentFilter> {
577        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
578                                               T filter, String packageName);
579        void startVerifications(int userId);
580        void receiveVerificationResponse(int verificationId);
581    }
582
583    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
584        private Context mContext;
585        private ComponentName mIntentFilterVerifierComponent;
586        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
587
588        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
589            mContext = context;
590            mIntentFilterVerifierComponent = verifierComponent;
591        }
592
593        private String getDefaultScheme() {
594            return IntentFilter.SCHEME_HTTPS;
595        }
596
597        @Override
598        public void startVerifications(int userId) {
599            // Launch verifications requests
600            int count = mCurrentIntentFilterVerifications.size();
601            for (int n=0; n<count; n++) {
602                int verificationId = mCurrentIntentFilterVerifications.get(n);
603                final IntentFilterVerificationState ivs =
604                        mIntentFilterVerificationStates.get(verificationId);
605
606                String packageName = ivs.getPackageName();
607
608                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
609                final int filterCount = filters.size();
610                ArraySet<String> domainsSet = new ArraySet<>();
611                for (int m=0; m<filterCount; m++) {
612                    PackageParser.ActivityIntentInfo filter = filters.get(m);
613                    domainsSet.addAll(filter.getHostsList());
614                }
615                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
616                synchronized (mPackages) {
617                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
618                            packageName, domainsList) != null) {
619                        scheduleWriteSettingsLocked();
620                    }
621                }
622                sendVerificationRequest(userId, verificationId, ivs);
623            }
624            mCurrentIntentFilterVerifications.clear();
625        }
626
627        private void sendVerificationRequest(int userId, int verificationId,
628                IntentFilterVerificationState ivs) {
629
630            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
631            verificationIntent.putExtra(
632                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
633                    verificationId);
634            verificationIntent.putExtra(
635                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
636                    getDefaultScheme());
637            verificationIntent.putExtra(
638                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
639                    ivs.getHostsString());
640            verificationIntent.putExtra(
641                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
642                    ivs.getPackageName());
643            verificationIntent.setComponent(mIntentFilterVerifierComponent);
644            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
645
646            UserHandle user = new UserHandle(userId);
647            mContext.sendBroadcastAsUser(verificationIntent, user);
648            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
649                    "Sending IntentFilter verification broadcast");
650        }
651
652        public void receiveVerificationResponse(int verificationId) {
653            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
654
655            final boolean verified = ivs.isVerified();
656
657            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
658            final int count = filters.size();
659            if (DEBUG_DOMAIN_VERIFICATION) {
660                Slog.i(TAG, "Received verification response " + verificationId
661                        + " for " + count + " filters, verified=" + verified);
662            }
663            for (int n=0; n<count; n++) {
664                PackageParser.ActivityIntentInfo filter = filters.get(n);
665                filter.setVerified(verified);
666
667                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
668                        + " verified with result:" + verified + " and hosts:"
669                        + ivs.getHostsString());
670            }
671
672            mIntentFilterVerificationStates.remove(verificationId);
673
674            final String packageName = ivs.getPackageName();
675            IntentFilterVerificationInfo ivi = null;
676
677            synchronized (mPackages) {
678                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
679            }
680            if (ivi == null) {
681                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
682                        + verificationId + " packageName:" + packageName);
683                return;
684            }
685            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
686                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
687
688            synchronized (mPackages) {
689                if (verified) {
690                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
691                } else {
692                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
693                }
694                scheduleWriteSettingsLocked();
695
696                final int userId = ivs.getUserId();
697                if (userId != UserHandle.USER_ALL) {
698                    final int userStatus =
699                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
700
701                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
702                    boolean needUpdate = false;
703
704                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
705                    // already been set by the User thru the Disambiguation dialog
706                    switch (userStatus) {
707                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
708                            if (verified) {
709                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
710                            } else {
711                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
712                            }
713                            needUpdate = true;
714                            break;
715
716                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
717                            if (verified) {
718                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
719                                needUpdate = true;
720                            }
721                            break;
722
723                        default:
724                            // Nothing to do
725                    }
726
727                    if (needUpdate) {
728                        mSettings.updateIntentFilterVerificationStatusLPw(
729                                packageName, updatedStatus, userId);
730                        scheduleWritePackageRestrictionsLocked(userId);
731                    }
732                }
733            }
734        }
735
736        @Override
737        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
738                    ActivityIntentInfo filter, String packageName) {
739            if (!hasValidDomains(filter)) {
740                return false;
741            }
742            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
743            if (ivs == null) {
744                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
745                        packageName);
746            }
747            if (DEBUG_DOMAIN_VERIFICATION) {
748                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
749            }
750            ivs.addFilter(filter);
751            return true;
752        }
753
754        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
755                int userId, int verificationId, String packageName) {
756            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
757                    verifierUid, userId, packageName);
758            ivs.setPendingState();
759            synchronized (mPackages) {
760                mIntentFilterVerificationStates.append(verificationId, ivs);
761                mCurrentIntentFilterVerifications.add(verificationId);
762            }
763            return ivs;
764        }
765    }
766
767    private static boolean hasValidDomains(ActivityIntentInfo filter) {
768        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
769                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
770        if (!hasHTTPorHTTPS) {
771            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
772                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
773            return false;
774        }
775        return true;
776    }
777
778    private IntentFilterVerifier mIntentFilterVerifier;
779
780    // Set of pending broadcasts for aggregating enable/disable of components.
781    static class PendingPackageBroadcasts {
782        // for each user id, a map of <package name -> components within that package>
783        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
784
785        public PendingPackageBroadcasts() {
786            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
787        }
788
789        public ArrayList<String> get(int userId, String packageName) {
790            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
791            return packages.get(packageName);
792        }
793
794        public void put(int userId, String packageName, ArrayList<String> components) {
795            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
796            packages.put(packageName, components);
797        }
798
799        public void remove(int userId, String packageName) {
800            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
801            if (packages != null) {
802                packages.remove(packageName);
803            }
804        }
805
806        public void remove(int userId) {
807            mUidMap.remove(userId);
808        }
809
810        public int userIdCount() {
811            return mUidMap.size();
812        }
813
814        public int userIdAt(int n) {
815            return mUidMap.keyAt(n);
816        }
817
818        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
819            return mUidMap.get(userId);
820        }
821
822        public int size() {
823            // total number of pending broadcast entries across all userIds
824            int num = 0;
825            for (int i = 0; i< mUidMap.size(); i++) {
826                num += mUidMap.valueAt(i).size();
827            }
828            return num;
829        }
830
831        public void clear() {
832            mUidMap.clear();
833        }
834
835        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
836            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
837            if (map == null) {
838                map = new ArrayMap<String, ArrayList<String>>();
839                mUidMap.put(userId, map);
840            }
841            return map;
842        }
843    }
844    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
845
846    // Service Connection to remote media container service to copy
847    // package uri's from external media onto secure containers
848    // or internal storage.
849    private IMediaContainerService mContainerService = null;
850
851    static final int SEND_PENDING_BROADCAST = 1;
852    static final int MCS_BOUND = 3;
853    static final int END_COPY = 4;
854    static final int INIT_COPY = 5;
855    static final int MCS_UNBIND = 6;
856    static final int START_CLEANING_PACKAGE = 7;
857    static final int FIND_INSTALL_LOC = 8;
858    static final int POST_INSTALL = 9;
859    static final int MCS_RECONNECT = 10;
860    static final int MCS_GIVE_UP = 11;
861    static final int UPDATED_MEDIA_STATUS = 12;
862    static final int WRITE_SETTINGS = 13;
863    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
864    static final int PACKAGE_VERIFIED = 15;
865    static final int CHECK_PENDING_VERIFICATION = 16;
866    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
867    static final int INTENT_FILTER_VERIFIED = 18;
868
869    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
870
871    // Delay time in millisecs
872    static final int BROADCAST_DELAY = 10 * 1000;
873
874    static UserManagerService sUserManager;
875
876    // Stores a list of users whose package restrictions file needs to be updated
877    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
878
879    final private DefaultContainerConnection mDefContainerConn =
880            new DefaultContainerConnection();
881    class DefaultContainerConnection implements ServiceConnection {
882        public void onServiceConnected(ComponentName name, IBinder service) {
883            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
884            IMediaContainerService imcs =
885                IMediaContainerService.Stub.asInterface(service);
886            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
887        }
888
889        public void onServiceDisconnected(ComponentName name) {
890            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
891        }
892    }
893
894    // Recordkeeping of restore-after-install operations that are currently in flight
895    // between the Package Manager and the Backup Manager
896    class PostInstallData {
897        public InstallArgs args;
898        public PackageInstalledInfo res;
899
900        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
901            args = _a;
902            res = _r;
903        }
904    }
905
906    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
907    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
908
909    // XML tags for backup/restore of various bits of state
910    private static final String TAG_PREFERRED_BACKUP = "pa";
911    private static final String TAG_DEFAULT_APPS = "da";
912    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
913
914    private final String mRequiredVerifierPackage;
915
916    private final PackageUsage mPackageUsage = new PackageUsage();
917
918    private class PackageUsage {
919        private static final int WRITE_INTERVAL
920            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
921
922        private final Object mFileLock = new Object();
923        private final AtomicLong mLastWritten = new AtomicLong(0);
924        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
925
926        private boolean mIsHistoricalPackageUsageAvailable = true;
927
928        boolean isHistoricalPackageUsageAvailable() {
929            return mIsHistoricalPackageUsageAvailable;
930        }
931
932        void write(boolean force) {
933            if (force) {
934                writeInternal();
935                return;
936            }
937            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
938                && !DEBUG_DEXOPT) {
939                return;
940            }
941            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
942                new Thread("PackageUsage_DiskWriter") {
943                    @Override
944                    public void run() {
945                        try {
946                            writeInternal();
947                        } finally {
948                            mBackgroundWriteRunning.set(false);
949                        }
950                    }
951                }.start();
952            }
953        }
954
955        private void writeInternal() {
956            synchronized (mPackages) {
957                synchronized (mFileLock) {
958                    AtomicFile file = getFile();
959                    FileOutputStream f = null;
960                    try {
961                        f = file.startWrite();
962                        BufferedOutputStream out = new BufferedOutputStream(f);
963                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
964                        StringBuilder sb = new StringBuilder();
965                        for (PackageParser.Package pkg : mPackages.values()) {
966                            if (pkg.mLastPackageUsageTimeInMills == 0) {
967                                continue;
968                            }
969                            sb.setLength(0);
970                            sb.append(pkg.packageName);
971                            sb.append(' ');
972                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
973                            sb.append('\n');
974                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
975                        }
976                        out.flush();
977                        file.finishWrite(f);
978                    } catch (IOException e) {
979                        if (f != null) {
980                            file.failWrite(f);
981                        }
982                        Log.e(TAG, "Failed to write package usage times", e);
983                    }
984                }
985            }
986            mLastWritten.set(SystemClock.elapsedRealtime());
987        }
988
989        void readLP() {
990            synchronized (mFileLock) {
991                AtomicFile file = getFile();
992                BufferedInputStream in = null;
993                try {
994                    in = new BufferedInputStream(file.openRead());
995                    StringBuffer sb = new StringBuffer();
996                    while (true) {
997                        String packageName = readToken(in, sb, ' ');
998                        if (packageName == null) {
999                            break;
1000                        }
1001                        String timeInMillisString = readToken(in, sb, '\n');
1002                        if (timeInMillisString == null) {
1003                            throw new IOException("Failed to find last usage time for package "
1004                                                  + packageName);
1005                        }
1006                        PackageParser.Package pkg = mPackages.get(packageName);
1007                        if (pkg == null) {
1008                            continue;
1009                        }
1010                        long timeInMillis;
1011                        try {
1012                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1013                        } catch (NumberFormatException e) {
1014                            throw new IOException("Failed to parse " + timeInMillisString
1015                                                  + " as a long.", e);
1016                        }
1017                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1018                    }
1019                } catch (FileNotFoundException expected) {
1020                    mIsHistoricalPackageUsageAvailable = false;
1021                } catch (IOException e) {
1022                    Log.w(TAG, "Failed to read package usage times", e);
1023                } finally {
1024                    IoUtils.closeQuietly(in);
1025                }
1026            }
1027            mLastWritten.set(SystemClock.elapsedRealtime());
1028        }
1029
1030        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1031                throws IOException {
1032            sb.setLength(0);
1033            while (true) {
1034                int ch = in.read();
1035                if (ch == -1) {
1036                    if (sb.length() == 0) {
1037                        return null;
1038                    }
1039                    throw new IOException("Unexpected EOF");
1040                }
1041                if (ch == endOfToken) {
1042                    return sb.toString();
1043                }
1044                sb.append((char)ch);
1045            }
1046        }
1047
1048        private AtomicFile getFile() {
1049            File dataDir = Environment.getDataDirectory();
1050            File systemDir = new File(dataDir, "system");
1051            File fname = new File(systemDir, "package-usage.list");
1052            return new AtomicFile(fname);
1053        }
1054    }
1055
1056    class PackageHandler extends Handler {
1057        private boolean mBound = false;
1058        final ArrayList<HandlerParams> mPendingInstalls =
1059            new ArrayList<HandlerParams>();
1060
1061        private boolean connectToService() {
1062            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1063                    " DefaultContainerService");
1064            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1065            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1066            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1067                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1068                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1069                mBound = true;
1070                return true;
1071            }
1072            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1073            return false;
1074        }
1075
1076        private void disconnectService() {
1077            mContainerService = null;
1078            mBound = false;
1079            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1080            mContext.unbindService(mDefContainerConn);
1081            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1082        }
1083
1084        PackageHandler(Looper looper) {
1085            super(looper);
1086        }
1087
1088        public void handleMessage(Message msg) {
1089            try {
1090                doHandleMessage(msg);
1091            } finally {
1092                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1093            }
1094        }
1095
1096        void doHandleMessage(Message msg) {
1097            switch (msg.what) {
1098                case INIT_COPY: {
1099                    HandlerParams params = (HandlerParams) msg.obj;
1100                    int idx = mPendingInstalls.size();
1101                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1102                    // If a bind was already initiated we dont really
1103                    // need to do anything. The pending install
1104                    // will be processed later on.
1105                    if (!mBound) {
1106                        // If this is the only one pending we might
1107                        // have to bind to the service again.
1108                        if (!connectToService()) {
1109                            Slog.e(TAG, "Failed to bind to media container service");
1110                            params.serviceError();
1111                            return;
1112                        } else {
1113                            // Once we bind to the service, the first
1114                            // pending request will be processed.
1115                            mPendingInstalls.add(idx, params);
1116                        }
1117                    } else {
1118                        mPendingInstalls.add(idx, params);
1119                        // Already bound to the service. Just make
1120                        // sure we trigger off processing the first request.
1121                        if (idx == 0) {
1122                            mHandler.sendEmptyMessage(MCS_BOUND);
1123                        }
1124                    }
1125                    break;
1126                }
1127                case MCS_BOUND: {
1128                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1129                    if (msg.obj != null) {
1130                        mContainerService = (IMediaContainerService) msg.obj;
1131                    }
1132                    if (mContainerService == null) {
1133                        if (!mBound) {
1134                            // Something seriously wrong since we are not bound and we are not
1135                            // waiting for connection. Bail out.
1136                            Slog.e(TAG, "Cannot bind to media container service");
1137                            for (HandlerParams params : mPendingInstalls) {
1138                                // Indicate service bind error
1139                                params.serviceError();
1140                            }
1141                            mPendingInstalls.clear();
1142                        } else {
1143                            Slog.w(TAG, "Waiting to connect to media container service");
1144                        }
1145                    } else if (mPendingInstalls.size() > 0) {
1146                        HandlerParams params = mPendingInstalls.get(0);
1147                        if (params != null) {
1148                            if (params.startCopy()) {
1149                                // We are done...  look for more work or to
1150                                // go idle.
1151                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1152                                        "Checking for more work or unbind...");
1153                                // Delete pending install
1154                                if (mPendingInstalls.size() > 0) {
1155                                    mPendingInstalls.remove(0);
1156                                }
1157                                if (mPendingInstalls.size() == 0) {
1158                                    if (mBound) {
1159                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1160                                                "Posting delayed MCS_UNBIND");
1161                                        removeMessages(MCS_UNBIND);
1162                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1163                                        // Unbind after a little delay, to avoid
1164                                        // continual thrashing.
1165                                        sendMessageDelayed(ubmsg, 10000);
1166                                    }
1167                                } else {
1168                                    // There are more pending requests in queue.
1169                                    // Just post MCS_BOUND message to trigger processing
1170                                    // of next pending install.
1171                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1172                                            "Posting MCS_BOUND for next work");
1173                                    mHandler.sendEmptyMessage(MCS_BOUND);
1174                                }
1175                            }
1176                        }
1177                    } else {
1178                        // Should never happen ideally.
1179                        Slog.w(TAG, "Empty queue");
1180                    }
1181                    break;
1182                }
1183                case MCS_RECONNECT: {
1184                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1185                    if (mPendingInstalls.size() > 0) {
1186                        if (mBound) {
1187                            disconnectService();
1188                        }
1189                        if (!connectToService()) {
1190                            Slog.e(TAG, "Failed to bind to media container service");
1191                            for (HandlerParams params : mPendingInstalls) {
1192                                // Indicate service bind error
1193                                params.serviceError();
1194                            }
1195                            mPendingInstalls.clear();
1196                        }
1197                    }
1198                    break;
1199                }
1200                case MCS_UNBIND: {
1201                    // If there is no actual work left, then time to unbind.
1202                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1203
1204                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1205                        if (mBound) {
1206                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1207
1208                            disconnectService();
1209                        }
1210                    } else if (mPendingInstalls.size() > 0) {
1211                        // There are more pending requests in queue.
1212                        // Just post MCS_BOUND message to trigger processing
1213                        // of next pending install.
1214                        mHandler.sendEmptyMessage(MCS_BOUND);
1215                    }
1216
1217                    break;
1218                }
1219                case MCS_GIVE_UP: {
1220                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1221                    mPendingInstalls.remove(0);
1222                    break;
1223                }
1224                case SEND_PENDING_BROADCAST: {
1225                    String packages[];
1226                    ArrayList<String> components[];
1227                    int size = 0;
1228                    int uids[];
1229                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1230                    synchronized (mPackages) {
1231                        if (mPendingBroadcasts == null) {
1232                            return;
1233                        }
1234                        size = mPendingBroadcasts.size();
1235                        if (size <= 0) {
1236                            // Nothing to be done. Just return
1237                            return;
1238                        }
1239                        packages = new String[size];
1240                        components = new ArrayList[size];
1241                        uids = new int[size];
1242                        int i = 0;  // filling out the above arrays
1243
1244                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1245                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1246                            Iterator<Map.Entry<String, ArrayList<String>>> it
1247                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1248                                            .entrySet().iterator();
1249                            while (it.hasNext() && i < size) {
1250                                Map.Entry<String, ArrayList<String>> ent = it.next();
1251                                packages[i] = ent.getKey();
1252                                components[i] = ent.getValue();
1253                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1254                                uids[i] = (ps != null)
1255                                        ? UserHandle.getUid(packageUserId, ps.appId)
1256                                        : -1;
1257                                i++;
1258                            }
1259                        }
1260                        size = i;
1261                        mPendingBroadcasts.clear();
1262                    }
1263                    // Send broadcasts
1264                    for (int i = 0; i < size; i++) {
1265                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1266                    }
1267                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1268                    break;
1269                }
1270                case START_CLEANING_PACKAGE: {
1271                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1272                    final String packageName = (String)msg.obj;
1273                    final int userId = msg.arg1;
1274                    final boolean andCode = msg.arg2 != 0;
1275                    synchronized (mPackages) {
1276                        if (userId == UserHandle.USER_ALL) {
1277                            int[] users = sUserManager.getUserIds();
1278                            for (int user : users) {
1279                                mSettings.addPackageToCleanLPw(
1280                                        new PackageCleanItem(user, packageName, andCode));
1281                            }
1282                        } else {
1283                            mSettings.addPackageToCleanLPw(
1284                                    new PackageCleanItem(userId, packageName, andCode));
1285                        }
1286                    }
1287                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1288                    startCleaningPackages();
1289                } break;
1290                case POST_INSTALL: {
1291                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1292                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1293                    mRunningInstalls.delete(msg.arg1);
1294                    boolean deleteOld = false;
1295
1296                    if (data != null) {
1297                        InstallArgs args = data.args;
1298                        PackageInstalledInfo res = data.res;
1299
1300                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1301                            res.removedInfo.sendBroadcast(false, true, false);
1302                            Bundle extras = new Bundle(1);
1303                            extras.putInt(Intent.EXTRA_UID, res.uid);
1304
1305                            // Now that we successfully installed the package, grant runtime
1306                            // permissions if requested before broadcasting the install.
1307                            if ((args.installFlags
1308                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1309                                grantRequestedRuntimePermissions(res.pkg,
1310                                        args.user.getIdentifier());
1311                            }
1312
1313                            // Determine the set of users who are adding this
1314                            // package for the first time vs. those who are seeing
1315                            // an update.
1316                            int[] firstUsers;
1317                            int[] updateUsers = new int[0];
1318                            if (res.origUsers == null || res.origUsers.length == 0) {
1319                                firstUsers = res.newUsers;
1320                            } else {
1321                                firstUsers = new int[0];
1322                                for (int i=0; i<res.newUsers.length; i++) {
1323                                    int user = res.newUsers[i];
1324                                    boolean isNew = true;
1325                                    for (int j=0; j<res.origUsers.length; j++) {
1326                                        if (res.origUsers[j] == user) {
1327                                            isNew = false;
1328                                            break;
1329                                        }
1330                                    }
1331                                    if (isNew) {
1332                                        int[] newFirst = new int[firstUsers.length+1];
1333                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1334                                                firstUsers.length);
1335                                        newFirst[firstUsers.length] = user;
1336                                        firstUsers = newFirst;
1337                                    } else {
1338                                        int[] newUpdate = new int[updateUsers.length+1];
1339                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1340                                                updateUsers.length);
1341                                        newUpdate[updateUsers.length] = user;
1342                                        updateUsers = newUpdate;
1343                                    }
1344                                }
1345                            }
1346                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1347                                    res.pkg.applicationInfo.packageName,
1348                                    extras, null, null, firstUsers);
1349                            final boolean update = res.removedInfo.removedPackage != null;
1350                            if (update) {
1351                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1352                            }
1353                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1354                                    res.pkg.applicationInfo.packageName,
1355                                    extras, null, null, updateUsers);
1356                            if (update) {
1357                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1358                                        res.pkg.applicationInfo.packageName,
1359                                        extras, null, null, updateUsers);
1360                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1361                                        null, null,
1362                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1363
1364                                // treat asec-hosted packages like removable media on upgrade
1365                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1366                                    if (DEBUG_INSTALL) {
1367                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1368                                                + " is ASEC-hosted -> AVAILABLE");
1369                                    }
1370                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1371                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1372                                    pkgList.add(res.pkg.applicationInfo.packageName);
1373                                    sendResourcesChangedBroadcast(true, true,
1374                                            pkgList,uidArray, null);
1375                                }
1376                            }
1377                            if (res.removedInfo.args != null) {
1378                                // Remove the replaced package's older resources safely now
1379                                deleteOld = true;
1380                            }
1381
1382                            // Log current value of "unknown sources" setting
1383                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1384                                getUnknownSourcesSettings());
1385                        }
1386                        // Force a gc to clear up things
1387                        Runtime.getRuntime().gc();
1388                        // We delete after a gc for applications  on sdcard.
1389                        if (deleteOld) {
1390                            synchronized (mInstallLock) {
1391                                res.removedInfo.args.doPostDeleteLI(true);
1392                            }
1393                        }
1394                        if (args.observer != null) {
1395                            try {
1396                                Bundle extras = extrasForInstallResult(res);
1397                                args.observer.onPackageInstalled(res.name, res.returnCode,
1398                                        res.returnMsg, extras);
1399                            } catch (RemoteException e) {
1400                                Slog.i(TAG, "Observer no longer exists.");
1401                            }
1402                        }
1403                    } else {
1404                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1405                    }
1406                } break;
1407                case UPDATED_MEDIA_STATUS: {
1408                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1409                    boolean reportStatus = msg.arg1 == 1;
1410                    boolean doGc = msg.arg2 == 1;
1411                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1412                    if (doGc) {
1413                        // Force a gc to clear up stale containers.
1414                        Runtime.getRuntime().gc();
1415                    }
1416                    if (msg.obj != null) {
1417                        @SuppressWarnings("unchecked")
1418                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1419                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1420                        // Unload containers
1421                        unloadAllContainers(args);
1422                    }
1423                    if (reportStatus) {
1424                        try {
1425                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1426                            PackageHelper.getMountService().finishMediaUpdate();
1427                        } catch (RemoteException e) {
1428                            Log.e(TAG, "MountService not running?");
1429                        }
1430                    }
1431                } break;
1432                case WRITE_SETTINGS: {
1433                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1434                    synchronized (mPackages) {
1435                        removeMessages(WRITE_SETTINGS);
1436                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1437                        mSettings.writeLPr();
1438                        mDirtyUsers.clear();
1439                    }
1440                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441                } break;
1442                case WRITE_PACKAGE_RESTRICTIONS: {
1443                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1444                    synchronized (mPackages) {
1445                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1446                        for (int userId : mDirtyUsers) {
1447                            mSettings.writePackageRestrictionsLPr(userId);
1448                        }
1449                        mDirtyUsers.clear();
1450                    }
1451                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1452                } break;
1453                case CHECK_PENDING_VERIFICATION: {
1454                    final int verificationId = msg.arg1;
1455                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1456
1457                    if ((state != null) && !state.timeoutExtended()) {
1458                        final InstallArgs args = state.getInstallArgs();
1459                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1460
1461                        Slog.i(TAG, "Verification timed out for " + originUri);
1462                        mPendingVerification.remove(verificationId);
1463
1464                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1465
1466                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1467                            Slog.i(TAG, "Continuing with installation of " + originUri);
1468                            state.setVerifierResponse(Binder.getCallingUid(),
1469                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1470                            broadcastPackageVerified(verificationId, originUri,
1471                                    PackageManager.VERIFICATION_ALLOW,
1472                                    state.getInstallArgs().getUser());
1473                            try {
1474                                ret = args.copyApk(mContainerService, true);
1475                            } catch (RemoteException e) {
1476                                Slog.e(TAG, "Could not contact the ContainerService");
1477                            }
1478                        } else {
1479                            broadcastPackageVerified(verificationId, originUri,
1480                                    PackageManager.VERIFICATION_REJECT,
1481                                    state.getInstallArgs().getUser());
1482                        }
1483
1484                        processPendingInstall(args, ret);
1485                        mHandler.sendEmptyMessage(MCS_UNBIND);
1486                    }
1487                    break;
1488                }
1489                case PACKAGE_VERIFIED: {
1490                    final int verificationId = msg.arg1;
1491
1492                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1493                    if (state == null) {
1494                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1495                        break;
1496                    }
1497
1498                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1499
1500                    state.setVerifierResponse(response.callerUid, response.code);
1501
1502                    if (state.isVerificationComplete()) {
1503                        mPendingVerification.remove(verificationId);
1504
1505                        final InstallArgs args = state.getInstallArgs();
1506                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1507
1508                        int ret;
1509                        if (state.isInstallAllowed()) {
1510                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1511                            broadcastPackageVerified(verificationId, originUri,
1512                                    response.code, state.getInstallArgs().getUser());
1513                            try {
1514                                ret = args.copyApk(mContainerService, true);
1515                            } catch (RemoteException e) {
1516                                Slog.e(TAG, "Could not contact the ContainerService");
1517                            }
1518                        } else {
1519                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1520                        }
1521
1522                        processPendingInstall(args, ret);
1523
1524                        mHandler.sendEmptyMessage(MCS_UNBIND);
1525                    }
1526
1527                    break;
1528                }
1529                case START_INTENT_FILTER_VERIFICATIONS: {
1530                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1531                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1532                            params.replacing, params.pkg);
1533                    break;
1534                }
1535                case INTENT_FILTER_VERIFIED: {
1536                    final int verificationId = msg.arg1;
1537
1538                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1539                            verificationId);
1540                    if (state == null) {
1541                        Slog.w(TAG, "Invalid IntentFilter verification token "
1542                                + verificationId + " received");
1543                        break;
1544                    }
1545
1546                    final int userId = state.getUserId();
1547
1548                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1549                            "Processing IntentFilter verification with token:"
1550                            + verificationId + " and userId:" + userId);
1551
1552                    final IntentFilterVerificationResponse response =
1553                            (IntentFilterVerificationResponse) msg.obj;
1554
1555                    state.setVerifierResponse(response.callerUid, response.code);
1556
1557                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1558                            "IntentFilter verification with token:" + verificationId
1559                            + " and userId:" + userId
1560                            + " is settings verifier response with response code:"
1561                            + response.code);
1562
1563                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1564                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1565                                + response.getFailedDomainsString());
1566                    }
1567
1568                    if (state.isVerificationComplete()) {
1569                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1570                    } else {
1571                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1572                                "IntentFilter verification with token:" + verificationId
1573                                + " was not said to be complete");
1574                    }
1575
1576                    break;
1577                }
1578            }
1579        }
1580    }
1581
1582    private StorageEventListener mStorageListener = new StorageEventListener() {
1583        @Override
1584        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1585            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1586                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1587                    // TODO: ensure that private directories exist for all active users
1588                    // TODO: remove user data whose serial number doesn't match
1589                    loadPrivatePackages(vol);
1590                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1591                    unloadPrivatePackages(vol);
1592                }
1593            }
1594
1595            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1596                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1597                    updateExternalMediaStatus(true, false);
1598                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1599                    updateExternalMediaStatus(false, false);
1600                }
1601            }
1602        }
1603
1604        @Override
1605        public void onVolumeForgotten(String fsUuid) {
1606            // TODO: remove all packages hosted on this uuid
1607        }
1608    };
1609
1610    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1611        if (userId >= UserHandle.USER_OWNER) {
1612            grantRequestedRuntimePermissionsForUser(pkg, userId);
1613        } else if (userId == UserHandle.USER_ALL) {
1614            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1615                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1616            }
1617        }
1618
1619        // We could have touched GID membership, so flush out packages.list
1620        synchronized (mPackages) {
1621            mSettings.writePackageListLPr();
1622        }
1623    }
1624
1625    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1626        SettingBase sb = (SettingBase) pkg.mExtras;
1627        if (sb == null) {
1628            return;
1629        }
1630
1631        PermissionsState permissionsState = sb.getPermissionsState();
1632
1633        for (String permission : pkg.requestedPermissions) {
1634            BasePermission bp = mSettings.mPermissions.get(permission);
1635            if (bp != null && bp.isRuntime()) {
1636                permissionsState.grantRuntimePermission(bp, userId);
1637            }
1638        }
1639    }
1640
1641    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1642        Bundle extras = null;
1643        switch (res.returnCode) {
1644            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1645                extras = new Bundle();
1646                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1647                        res.origPermission);
1648                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1649                        res.origPackage);
1650                break;
1651            }
1652            case PackageManager.INSTALL_SUCCEEDED: {
1653                extras = new Bundle();
1654                extras.putBoolean(Intent.EXTRA_REPLACING,
1655                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1656                break;
1657            }
1658        }
1659        return extras;
1660    }
1661
1662    void scheduleWriteSettingsLocked() {
1663        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1664            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1665        }
1666    }
1667
1668    void scheduleWritePackageRestrictionsLocked(int userId) {
1669        if (!sUserManager.exists(userId)) return;
1670        mDirtyUsers.add(userId);
1671        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1672            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1673        }
1674    }
1675
1676    public static PackageManagerService main(Context context, Installer installer,
1677            boolean factoryTest, boolean onlyCore) {
1678        PackageManagerService m = new PackageManagerService(context, installer,
1679                factoryTest, onlyCore);
1680        ServiceManager.addService("package", m);
1681        return m;
1682    }
1683
1684    static String[] splitString(String str, char sep) {
1685        int count = 1;
1686        int i = 0;
1687        while ((i=str.indexOf(sep, i)) >= 0) {
1688            count++;
1689            i++;
1690        }
1691
1692        String[] res = new String[count];
1693        i=0;
1694        count = 0;
1695        int lastI=0;
1696        while ((i=str.indexOf(sep, i)) >= 0) {
1697            res[count] = str.substring(lastI, i);
1698            count++;
1699            i++;
1700            lastI = i;
1701        }
1702        res[count] = str.substring(lastI, str.length());
1703        return res;
1704    }
1705
1706    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1707        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1708                Context.DISPLAY_SERVICE);
1709        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1710    }
1711
1712    public PackageManagerService(Context context, Installer installer,
1713            boolean factoryTest, boolean onlyCore) {
1714        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1715                SystemClock.uptimeMillis());
1716
1717        if (mSdkVersion <= 0) {
1718            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1719        }
1720
1721        mContext = context;
1722        mFactoryTest = factoryTest;
1723        mOnlyCore = onlyCore;
1724        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1725        mMetrics = new DisplayMetrics();
1726        mSettings = new Settings(mPackages);
1727        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1728                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1729        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1730                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1731        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1732                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1733        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1734                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1735        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1736                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1737        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1738                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1739
1740        // TODO: add a property to control this?
1741        long dexOptLRUThresholdInMinutes;
1742        if (mLazyDexOpt) {
1743            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1744        } else {
1745            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1746        }
1747        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1748
1749        String separateProcesses = SystemProperties.get("debug.separate_processes");
1750        if (separateProcesses != null && separateProcesses.length() > 0) {
1751            if ("*".equals(separateProcesses)) {
1752                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1753                mSeparateProcesses = null;
1754                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1755            } else {
1756                mDefParseFlags = 0;
1757                mSeparateProcesses = separateProcesses.split(",");
1758                Slog.w(TAG, "Running with debug.separate_processes: "
1759                        + separateProcesses);
1760            }
1761        } else {
1762            mDefParseFlags = 0;
1763            mSeparateProcesses = null;
1764        }
1765
1766        mInstaller = installer;
1767        mPackageDexOptimizer = new PackageDexOptimizer(this);
1768        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1769
1770        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1771                FgThread.get().getLooper());
1772
1773        getDefaultDisplayMetrics(context, mMetrics);
1774
1775        SystemConfig systemConfig = SystemConfig.getInstance();
1776        mGlobalGids = systemConfig.getGlobalGids();
1777        mSystemPermissions = systemConfig.getSystemPermissions();
1778        mAvailableFeatures = systemConfig.getAvailableFeatures();
1779
1780        synchronized (mInstallLock) {
1781        // writer
1782        synchronized (mPackages) {
1783            mHandlerThread = new ServiceThread(TAG,
1784                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1785            mHandlerThread.start();
1786            mHandler = new PackageHandler(mHandlerThread.getLooper());
1787            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1788
1789            File dataDir = Environment.getDataDirectory();
1790            mAppDataDir = new File(dataDir, "data");
1791            mAppInstallDir = new File(dataDir, "app");
1792            mAppLib32InstallDir = new File(dataDir, "app-lib");
1793            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1794            mUserAppDataDir = new File(dataDir, "user");
1795            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1796
1797            sUserManager = new UserManagerService(context, this,
1798                    mInstallLock, mPackages);
1799
1800            // Propagate permission configuration in to package manager.
1801            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1802                    = systemConfig.getPermissions();
1803            for (int i=0; i<permConfig.size(); i++) {
1804                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1805                BasePermission bp = mSettings.mPermissions.get(perm.name);
1806                if (bp == null) {
1807                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1808                    mSettings.mPermissions.put(perm.name, bp);
1809                }
1810                if (perm.gids != null) {
1811                    bp.setGids(perm.gids, perm.perUser);
1812                }
1813            }
1814
1815            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1816            for (int i=0; i<libConfig.size(); i++) {
1817                mSharedLibraries.put(libConfig.keyAt(i),
1818                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1819            }
1820
1821            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1822
1823            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1824                    mSdkVersion, mOnlyCore);
1825
1826            String customResolverActivity = Resources.getSystem().getString(
1827                    R.string.config_customResolverActivity);
1828            if (TextUtils.isEmpty(customResolverActivity)) {
1829                customResolverActivity = null;
1830            } else {
1831                mCustomResolverComponentName = ComponentName.unflattenFromString(
1832                        customResolverActivity);
1833            }
1834
1835            long startTime = SystemClock.uptimeMillis();
1836
1837            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1838                    startTime);
1839
1840            // Set flag to monitor and not change apk file paths when
1841            // scanning install directories.
1842            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1843
1844            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1845
1846            /**
1847             * Add everything in the in the boot class path to the
1848             * list of process files because dexopt will have been run
1849             * if necessary during zygote startup.
1850             */
1851            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1852            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1853
1854            if (bootClassPath != null) {
1855                String[] bootClassPathElements = splitString(bootClassPath, ':');
1856                for (String element : bootClassPathElements) {
1857                    alreadyDexOpted.add(element);
1858                }
1859            } else {
1860                Slog.w(TAG, "No BOOTCLASSPATH found!");
1861            }
1862
1863            if (systemServerClassPath != null) {
1864                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1865                for (String element : systemServerClassPathElements) {
1866                    alreadyDexOpted.add(element);
1867                }
1868            } else {
1869                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1870            }
1871
1872            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1873            final String[] dexCodeInstructionSets =
1874                    getDexCodeInstructionSets(
1875                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1876
1877            /**
1878             * Ensure all external libraries have had dexopt run on them.
1879             */
1880            if (mSharedLibraries.size() > 0) {
1881                // NOTE: For now, we're compiling these system "shared libraries"
1882                // (and framework jars) into all available architectures. It's possible
1883                // to compile them only when we come across an app that uses them (there's
1884                // already logic for that in scanPackageLI) but that adds some complexity.
1885                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1886                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1887                        final String lib = libEntry.path;
1888                        if (lib == null) {
1889                            continue;
1890                        }
1891
1892                        try {
1893                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1894                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1895                                alreadyDexOpted.add(lib);
1896                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1897                            }
1898                        } catch (FileNotFoundException e) {
1899                            Slog.w(TAG, "Library not found: " + lib);
1900                        } catch (IOException e) {
1901                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1902                                    + e.getMessage());
1903                        }
1904                    }
1905                }
1906            }
1907
1908            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1909
1910            // Gross hack for now: we know this file doesn't contain any
1911            // code, so don't dexopt it to avoid the resulting log spew.
1912            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1913
1914            // Gross hack for now: we know this file is only part of
1915            // the boot class path for art, so don't dexopt it to
1916            // avoid the resulting log spew.
1917            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1918
1919            /**
1920             * There are a number of commands implemented in Java, which
1921             * we currently need to do the dexopt on so that they can be
1922             * run from a non-root shell.
1923             */
1924            String[] frameworkFiles = frameworkDir.list();
1925            if (frameworkFiles != null) {
1926                // TODO: We could compile these only for the most preferred ABI. We should
1927                // first double check that the dex files for these commands are not referenced
1928                // by other system apps.
1929                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1930                    for (int i=0; i<frameworkFiles.length; i++) {
1931                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1932                        String path = libPath.getPath();
1933                        // Skip the file if we already did it.
1934                        if (alreadyDexOpted.contains(path)) {
1935                            continue;
1936                        }
1937                        // Skip the file if it is not a type we want to dexopt.
1938                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1939                            continue;
1940                        }
1941                        try {
1942                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1943                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1944                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1945                            }
1946                        } catch (FileNotFoundException e) {
1947                            Slog.w(TAG, "Jar not found: " + path);
1948                        } catch (IOException e) {
1949                            Slog.w(TAG, "Exception reading jar: " + path, e);
1950                        }
1951                    }
1952                }
1953            }
1954
1955            // Collect vendor overlay packages.
1956            // (Do this before scanning any apps.)
1957            // For security and version matching reason, only consider
1958            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1959            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1960            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1961                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1962
1963            // Find base frameworks (resource packages without code).
1964            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1965                    | PackageParser.PARSE_IS_SYSTEM_DIR
1966                    | PackageParser.PARSE_IS_PRIVILEGED,
1967                    scanFlags | SCAN_NO_DEX, 0);
1968
1969            // Collected privileged system packages.
1970            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1971            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1972                    | PackageParser.PARSE_IS_SYSTEM_DIR
1973                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1974
1975            // Collect ordinary system packages.
1976            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1977            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1978                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1979
1980            // Collect all vendor packages.
1981            File vendorAppDir = new File("/vendor/app");
1982            try {
1983                vendorAppDir = vendorAppDir.getCanonicalFile();
1984            } catch (IOException e) {
1985                // failed to look up canonical path, continue with original one
1986            }
1987            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1988                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1989
1990            // Collect all OEM packages.
1991            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1992            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1993                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1994
1995            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1996            mInstaller.moveFiles();
1997
1998            // Prune any system packages that no longer exist.
1999            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2000            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2001            if (!mOnlyCore) {
2002                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2003                while (psit.hasNext()) {
2004                    PackageSetting ps = psit.next();
2005
2006                    /*
2007                     * If this is not a system app, it can't be a
2008                     * disable system app.
2009                     */
2010                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2011                        continue;
2012                    }
2013
2014                    /*
2015                     * If the package is scanned, it's not erased.
2016                     */
2017                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2018                    if (scannedPkg != null) {
2019                        /*
2020                         * If the system app is both scanned and in the
2021                         * disabled packages list, then it must have been
2022                         * added via OTA. Remove it from the currently
2023                         * scanned package so the previously user-installed
2024                         * application can be scanned.
2025                         */
2026                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2027                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2028                                    + ps.name + "; removing system app.  Last known codePath="
2029                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2030                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2031                                    + scannedPkg.mVersionCode);
2032                            removePackageLI(ps, true);
2033                            expectingBetter.put(ps.name, ps.codePath);
2034                        }
2035
2036                        continue;
2037                    }
2038
2039                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2040                        psit.remove();
2041                        logCriticalInfo(Log.WARN, "System package " + ps.name
2042                                + " no longer exists; wiping its data");
2043                        removeDataDirsLI(null, ps.name);
2044                    } else {
2045                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2046                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2047                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2048                        }
2049                    }
2050                }
2051            }
2052
2053            //look for any incomplete package installations
2054            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2055            //clean up list
2056            for(int i = 0; i < deletePkgsList.size(); i++) {
2057                //clean up here
2058                cleanupInstallFailedPackage(deletePkgsList.get(i));
2059            }
2060            //delete tmp files
2061            deleteTempPackageFiles();
2062
2063            // Remove any shared userIDs that have no associated packages
2064            mSettings.pruneSharedUsersLPw();
2065
2066            if (!mOnlyCore) {
2067                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2068                        SystemClock.uptimeMillis());
2069                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2070
2071                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2072                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2073
2074                /**
2075                 * Remove disable package settings for any updated system
2076                 * apps that were removed via an OTA. If they're not a
2077                 * previously-updated app, remove them completely.
2078                 * Otherwise, just revoke their system-level permissions.
2079                 */
2080                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2081                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2082                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2083
2084                    String msg;
2085                    if (deletedPkg == null) {
2086                        msg = "Updated system package " + deletedAppName
2087                                + " no longer exists; wiping its data";
2088                        removeDataDirsLI(null, deletedAppName);
2089                    } else {
2090                        msg = "Updated system app + " + deletedAppName
2091                                + " no longer present; removing system privileges for "
2092                                + deletedAppName;
2093
2094                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2095
2096                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2097                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2098                    }
2099                    logCriticalInfo(Log.WARN, msg);
2100                }
2101
2102                /**
2103                 * Make sure all system apps that we expected to appear on
2104                 * the userdata partition actually showed up. If they never
2105                 * appeared, crawl back and revive the system version.
2106                 */
2107                for (int i = 0; i < expectingBetter.size(); i++) {
2108                    final String packageName = expectingBetter.keyAt(i);
2109                    if (!mPackages.containsKey(packageName)) {
2110                        final File scanFile = expectingBetter.valueAt(i);
2111
2112                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2113                                + " but never showed up; reverting to system");
2114
2115                        final int reparseFlags;
2116                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2117                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2118                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2119                                    | PackageParser.PARSE_IS_PRIVILEGED;
2120                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2121                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2122                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2123                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2124                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2125                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2126                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2127                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2128                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2129                        } else {
2130                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2131                            continue;
2132                        }
2133
2134                        mSettings.enableSystemPackageLPw(packageName);
2135
2136                        try {
2137                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2138                        } catch (PackageManagerException e) {
2139                            Slog.e(TAG, "Failed to parse original system package: "
2140                                    + e.getMessage());
2141                        }
2142                    }
2143                }
2144            }
2145
2146            // Now that we know all of the shared libraries, update all clients to have
2147            // the correct library paths.
2148            updateAllSharedLibrariesLPw();
2149
2150            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2151                // NOTE: We ignore potential failures here during a system scan (like
2152                // the rest of the commands above) because there's precious little we
2153                // can do about it. A settings error is reported, though.
2154                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2155                        false /* force dexopt */, false /* defer dexopt */);
2156            }
2157
2158            // Now that we know all the packages we are keeping,
2159            // read and update their last usage times.
2160            mPackageUsage.readLP();
2161
2162            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2163                    SystemClock.uptimeMillis());
2164            Slog.i(TAG, "Time to scan packages: "
2165                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2166                    + " seconds");
2167
2168            // If the platform SDK has changed since the last time we booted,
2169            // we need to re-grant app permission to catch any new ones that
2170            // appear.  This is really a hack, and means that apps can in some
2171            // cases get permissions that the user didn't initially explicitly
2172            // allow...  it would be nice to have some better way to handle
2173            // this situation.
2174            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2175                    != mSdkVersion;
2176            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2177                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2178                    + "; regranting permissions for internal storage");
2179            mSettings.mInternalSdkPlatform = mSdkVersion;
2180
2181            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2182                    | (regrantPermissions
2183                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2184                            : 0));
2185
2186            // If this is the first boot, and it is a normal boot, then
2187            // we need to initialize the default preferred apps.
2188            if (!mRestoredSettings && !onlyCore) {
2189                mSettings.readDefaultPreferredAppsLPw(this, 0);
2190            }
2191
2192            // If this is first boot after an OTA, and a normal boot, then
2193            // we need to clear code cache directories.
2194            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2195            if (mIsUpgrade && !onlyCore) {
2196                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2197                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2198                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2199                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2200                }
2201                mSettings.mFingerprint = Build.FINGERPRINT;
2202            }
2203
2204            primeDomainVerificationsLPw();
2205            checkDefaultBrowser();
2206
2207            // All the changes are done during package scanning.
2208            mSettings.updateInternalDatabaseVersion();
2209
2210            // can downgrade to reader
2211            mSettings.writeLPr();
2212
2213            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2214                    SystemClock.uptimeMillis());
2215
2216            mRequiredVerifierPackage = getRequiredVerifierLPr();
2217
2218            mInstallerService = new PackageInstallerService(context, this);
2219
2220            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2221            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2222                    mIntentFilterVerifierComponent);
2223
2224        } // synchronized (mPackages)
2225        } // synchronized (mInstallLock)
2226
2227        // Now after opening every single application zip, make sure they
2228        // are all flushed.  Not really needed, but keeps things nice and
2229        // tidy.
2230        Runtime.getRuntime().gc();
2231
2232        // Expose private service for system components to use.
2233        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2234    }
2235
2236    @Override
2237    public boolean isFirstBoot() {
2238        return !mRestoredSettings;
2239    }
2240
2241    @Override
2242    public boolean isOnlyCoreApps() {
2243        return mOnlyCore;
2244    }
2245
2246    @Override
2247    public boolean isUpgrade() {
2248        return mIsUpgrade;
2249    }
2250
2251    private String getRequiredVerifierLPr() {
2252        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2253        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2254                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2255
2256        String requiredVerifier = null;
2257
2258        final int N = receivers.size();
2259        for (int i = 0; i < N; i++) {
2260            final ResolveInfo info = receivers.get(i);
2261
2262            if (info.activityInfo == null) {
2263                continue;
2264            }
2265
2266            final String packageName = info.activityInfo.packageName;
2267
2268            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2269                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2270                continue;
2271            }
2272
2273            if (requiredVerifier != null) {
2274                throw new RuntimeException("There can be only one required verifier");
2275            }
2276
2277            requiredVerifier = packageName;
2278        }
2279
2280        return requiredVerifier;
2281    }
2282
2283    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2284        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2285        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2286                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2287
2288        ComponentName verifierComponentName = null;
2289
2290        int priority = -1000;
2291        final int N = receivers.size();
2292        for (int i = 0; i < N; i++) {
2293            final ResolveInfo info = receivers.get(i);
2294
2295            if (info.activityInfo == null) {
2296                continue;
2297            }
2298
2299            final String packageName = info.activityInfo.packageName;
2300
2301            final PackageSetting ps = mSettings.mPackages.get(packageName);
2302            if (ps == null) {
2303                continue;
2304            }
2305
2306            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2307                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2308                continue;
2309            }
2310
2311            // Select the IntentFilterVerifier with the highest priority
2312            if (priority < info.priority) {
2313                priority = info.priority;
2314                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2315                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2316                        + verifierComponentName + " with priority: " + info.priority);
2317            }
2318        }
2319
2320        return verifierComponentName;
2321    }
2322
2323    private void primeDomainVerificationsLPw() {
2324        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2325        boolean updated = false;
2326        ArraySet<String> allHostsSet = new ArraySet<>();
2327        for (PackageParser.Package pkg : mPackages.values()) {
2328            final String packageName = pkg.packageName;
2329            if (!hasDomainURLs(pkg)) {
2330                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2331                            "package with no domain URLs: " + packageName);
2332                continue;
2333            }
2334            if (!pkg.isSystemApp()) {
2335                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2336                        "No priming domain verifications for a non system package : " +
2337                                packageName);
2338                continue;
2339            }
2340            for (PackageParser.Activity a : pkg.activities) {
2341                for (ActivityIntentInfo filter : a.intents) {
2342                    if (hasValidDomains(filter)) {
2343                        allHostsSet.addAll(filter.getHostsList());
2344                    }
2345                }
2346            }
2347            if (allHostsSet.size() == 0) {
2348                allHostsSet.add("*");
2349            }
2350            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2351            IntentFilterVerificationInfo ivi =
2352                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2353            if (ivi != null) {
2354                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2355                        "Priming domain verifications for package: " + packageName +
2356                        " with hosts:" + ivi.getDomainsString());
2357                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2358                updated = true;
2359            }
2360            else {
2361                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2362                        "No priming domain verifications for package: " + packageName);
2363            }
2364            allHostsSet.clear();
2365        }
2366        if (updated) {
2367            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2368                    "Will need to write primed domain verifications");
2369        }
2370        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2371    }
2372
2373    private void checkDefaultBrowser() {
2374        final int myUserId = UserHandle.myUserId();
2375        final String packageName = getDefaultBrowserPackageName(myUserId);
2376        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2377        if (info == null) {
2378            Slog.w(TAG, "Default browser no longer installed: " + packageName);
2379            setDefaultBrowserPackageName(null, myUserId);
2380        }
2381    }
2382
2383    @Override
2384    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2385            throws RemoteException {
2386        try {
2387            return super.onTransact(code, data, reply, flags);
2388        } catch (RuntimeException e) {
2389            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2390                Slog.wtf(TAG, "Package Manager Crash", e);
2391            }
2392            throw e;
2393        }
2394    }
2395
2396    void cleanupInstallFailedPackage(PackageSetting ps) {
2397        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2398
2399        removeDataDirsLI(ps.volumeUuid, ps.name);
2400        if (ps.codePath != null) {
2401            if (ps.codePath.isDirectory()) {
2402                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2403            } else {
2404                ps.codePath.delete();
2405            }
2406        }
2407        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2408            if (ps.resourcePath.isDirectory()) {
2409                FileUtils.deleteContents(ps.resourcePath);
2410            }
2411            ps.resourcePath.delete();
2412        }
2413        mSettings.removePackageLPw(ps.name);
2414    }
2415
2416    static int[] appendInts(int[] cur, int[] add) {
2417        if (add == null) return cur;
2418        if (cur == null) return add;
2419        final int N = add.length;
2420        for (int i=0; i<N; i++) {
2421            cur = appendInt(cur, add[i]);
2422        }
2423        return cur;
2424    }
2425
2426    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2427        if (!sUserManager.exists(userId)) return null;
2428        final PackageSetting ps = (PackageSetting) p.mExtras;
2429        if (ps == null) {
2430            return null;
2431        }
2432
2433        final PermissionsState permissionsState = ps.getPermissionsState();
2434
2435        final int[] gids = permissionsState.computeGids(userId);
2436        final Set<String> permissions = permissionsState.getPermissions(userId);
2437        final PackageUserState state = ps.readUserState(userId);
2438
2439        return PackageParser.generatePackageInfo(p, gids, flags,
2440                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2441    }
2442
2443    @Override
2444    public boolean isPackageFrozen(String packageName) {
2445        synchronized (mPackages) {
2446            final PackageSetting ps = mSettings.mPackages.get(packageName);
2447            if (ps != null) {
2448                return ps.frozen;
2449            }
2450        }
2451        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2452        return true;
2453    }
2454
2455    @Override
2456    public boolean isPackageAvailable(String packageName, int userId) {
2457        if (!sUserManager.exists(userId)) return false;
2458        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2459        synchronized (mPackages) {
2460            PackageParser.Package p = mPackages.get(packageName);
2461            if (p != null) {
2462                final PackageSetting ps = (PackageSetting) p.mExtras;
2463                if (ps != null) {
2464                    final PackageUserState state = ps.readUserState(userId);
2465                    if (state != null) {
2466                        return PackageParser.isAvailable(state);
2467                    }
2468                }
2469            }
2470        }
2471        return false;
2472    }
2473
2474    @Override
2475    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2476        if (!sUserManager.exists(userId)) return null;
2477        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2478        // reader
2479        synchronized (mPackages) {
2480            PackageParser.Package p = mPackages.get(packageName);
2481            if (DEBUG_PACKAGE_INFO)
2482                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2483            if (p != null) {
2484                return generatePackageInfo(p, flags, userId);
2485            }
2486            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2487                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2488            }
2489        }
2490        return null;
2491    }
2492
2493    @Override
2494    public String[] currentToCanonicalPackageNames(String[] names) {
2495        String[] out = new String[names.length];
2496        // reader
2497        synchronized (mPackages) {
2498            for (int i=names.length-1; i>=0; i--) {
2499                PackageSetting ps = mSettings.mPackages.get(names[i]);
2500                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2501            }
2502        }
2503        return out;
2504    }
2505
2506    @Override
2507    public String[] canonicalToCurrentPackageNames(String[] names) {
2508        String[] out = new String[names.length];
2509        // reader
2510        synchronized (mPackages) {
2511            for (int i=names.length-1; i>=0; i--) {
2512                String cur = mSettings.mRenamedPackages.get(names[i]);
2513                out[i] = cur != null ? cur : names[i];
2514            }
2515        }
2516        return out;
2517    }
2518
2519    @Override
2520    public int getPackageUid(String packageName, int userId) {
2521        if (!sUserManager.exists(userId)) return -1;
2522        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2523
2524        // reader
2525        synchronized (mPackages) {
2526            PackageParser.Package p = mPackages.get(packageName);
2527            if(p != null) {
2528                return UserHandle.getUid(userId, p.applicationInfo.uid);
2529            }
2530            PackageSetting ps = mSettings.mPackages.get(packageName);
2531            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2532                return -1;
2533            }
2534            p = ps.pkg;
2535            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2536        }
2537    }
2538
2539    @Override
2540    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2541        if (!sUserManager.exists(userId)) {
2542            return null;
2543        }
2544
2545        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2546                "getPackageGids");
2547
2548        // reader
2549        synchronized (mPackages) {
2550            PackageParser.Package p = mPackages.get(packageName);
2551            if (DEBUG_PACKAGE_INFO) {
2552                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2553            }
2554            if (p != null) {
2555                PackageSetting ps = (PackageSetting) p.mExtras;
2556                return ps.getPermissionsState().computeGids(userId);
2557            }
2558        }
2559
2560        return null;
2561    }
2562
2563    static PermissionInfo generatePermissionInfo(
2564            BasePermission bp, int flags) {
2565        if (bp.perm != null) {
2566            return PackageParser.generatePermissionInfo(bp.perm, flags);
2567        }
2568        PermissionInfo pi = new PermissionInfo();
2569        pi.name = bp.name;
2570        pi.packageName = bp.sourcePackage;
2571        pi.nonLocalizedLabel = bp.name;
2572        pi.protectionLevel = bp.protectionLevel;
2573        return pi;
2574    }
2575
2576    @Override
2577    public PermissionInfo getPermissionInfo(String name, int flags) {
2578        // reader
2579        synchronized (mPackages) {
2580            final BasePermission p = mSettings.mPermissions.get(name);
2581            if (p != null) {
2582                return generatePermissionInfo(p, flags);
2583            }
2584            return null;
2585        }
2586    }
2587
2588    @Override
2589    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2590        // reader
2591        synchronized (mPackages) {
2592            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2593            for (BasePermission p : mSettings.mPermissions.values()) {
2594                if (group == null) {
2595                    if (p.perm == null || p.perm.info.group == null) {
2596                        out.add(generatePermissionInfo(p, flags));
2597                    }
2598                } else {
2599                    if (p.perm != null && group.equals(p.perm.info.group)) {
2600                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2601                    }
2602                }
2603            }
2604
2605            if (out.size() > 0) {
2606                return out;
2607            }
2608            return mPermissionGroups.containsKey(group) ? out : null;
2609        }
2610    }
2611
2612    @Override
2613    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2614        // reader
2615        synchronized (mPackages) {
2616            return PackageParser.generatePermissionGroupInfo(
2617                    mPermissionGroups.get(name), flags);
2618        }
2619    }
2620
2621    @Override
2622    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2623        // reader
2624        synchronized (mPackages) {
2625            final int N = mPermissionGroups.size();
2626            ArrayList<PermissionGroupInfo> out
2627                    = new ArrayList<PermissionGroupInfo>(N);
2628            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2629                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2630            }
2631            return out;
2632        }
2633    }
2634
2635    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2636            int userId) {
2637        if (!sUserManager.exists(userId)) return null;
2638        PackageSetting ps = mSettings.mPackages.get(packageName);
2639        if (ps != null) {
2640            if (ps.pkg == null) {
2641                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2642                        flags, userId);
2643                if (pInfo != null) {
2644                    return pInfo.applicationInfo;
2645                }
2646                return null;
2647            }
2648            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2649                    ps.readUserState(userId), userId);
2650        }
2651        return null;
2652    }
2653
2654    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2655            int userId) {
2656        if (!sUserManager.exists(userId)) return null;
2657        PackageSetting ps = mSettings.mPackages.get(packageName);
2658        if (ps != null) {
2659            PackageParser.Package pkg = ps.pkg;
2660            if (pkg == null) {
2661                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2662                    return null;
2663                }
2664                // Only data remains, so we aren't worried about code paths
2665                pkg = new PackageParser.Package(packageName);
2666                pkg.applicationInfo.packageName = packageName;
2667                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2668                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2669                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2670                        packageName, userId).getAbsolutePath();
2671                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2672                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2673            }
2674            return generatePackageInfo(pkg, flags, userId);
2675        }
2676        return null;
2677    }
2678
2679    @Override
2680    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2681        if (!sUserManager.exists(userId)) return null;
2682        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2683        // writer
2684        synchronized (mPackages) {
2685            PackageParser.Package p = mPackages.get(packageName);
2686            if (DEBUG_PACKAGE_INFO) Log.v(
2687                    TAG, "getApplicationInfo " + packageName
2688                    + ": " + p);
2689            if (p != null) {
2690                PackageSetting ps = mSettings.mPackages.get(packageName);
2691                if (ps == null) return null;
2692                // Note: isEnabledLP() does not apply here - always return info
2693                return PackageParser.generateApplicationInfo(
2694                        p, flags, ps.readUserState(userId), userId);
2695            }
2696            if ("android".equals(packageName)||"system".equals(packageName)) {
2697                return mAndroidApplication;
2698            }
2699            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2700                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2701            }
2702        }
2703        return null;
2704    }
2705
2706    @Override
2707    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2708            final IPackageDataObserver observer) {
2709        mContext.enforceCallingOrSelfPermission(
2710                android.Manifest.permission.CLEAR_APP_CACHE, null);
2711        // Queue up an async operation since clearing cache may take a little while.
2712        mHandler.post(new Runnable() {
2713            public void run() {
2714                mHandler.removeCallbacks(this);
2715                int retCode = -1;
2716                synchronized (mInstallLock) {
2717                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2718                    if (retCode < 0) {
2719                        Slog.w(TAG, "Couldn't clear application caches");
2720                    }
2721                }
2722                if (observer != null) {
2723                    try {
2724                        observer.onRemoveCompleted(null, (retCode >= 0));
2725                    } catch (RemoteException e) {
2726                        Slog.w(TAG, "RemoveException when invoking call back");
2727                    }
2728                }
2729            }
2730        });
2731    }
2732
2733    @Override
2734    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2735            final IntentSender pi) {
2736        mContext.enforceCallingOrSelfPermission(
2737                android.Manifest.permission.CLEAR_APP_CACHE, null);
2738        // Queue up an async operation since clearing cache may take a little while.
2739        mHandler.post(new Runnable() {
2740            public void run() {
2741                mHandler.removeCallbacks(this);
2742                int retCode = -1;
2743                synchronized (mInstallLock) {
2744                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2745                    if (retCode < 0) {
2746                        Slog.w(TAG, "Couldn't clear application caches");
2747                    }
2748                }
2749                if(pi != null) {
2750                    try {
2751                        // Callback via pending intent
2752                        int code = (retCode >= 0) ? 1 : 0;
2753                        pi.sendIntent(null, code, null,
2754                                null, null);
2755                    } catch (SendIntentException e1) {
2756                        Slog.i(TAG, "Failed to send pending intent");
2757                    }
2758                }
2759            }
2760        });
2761    }
2762
2763    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2764        synchronized (mInstallLock) {
2765            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2766                throw new IOException("Failed to free enough space");
2767            }
2768        }
2769    }
2770
2771    @Override
2772    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2773        if (!sUserManager.exists(userId)) return null;
2774        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2775        synchronized (mPackages) {
2776            PackageParser.Activity a = mActivities.mActivities.get(component);
2777
2778            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2779            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2780                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2781                if (ps == null) return null;
2782                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2783                        userId);
2784            }
2785            if (mResolveComponentName.equals(component)) {
2786                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2787                        new PackageUserState(), userId);
2788            }
2789        }
2790        return null;
2791    }
2792
2793    @Override
2794    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2795            String resolvedType) {
2796        synchronized (mPackages) {
2797            PackageParser.Activity a = mActivities.mActivities.get(component);
2798            if (a == null) {
2799                return false;
2800            }
2801            for (int i=0; i<a.intents.size(); i++) {
2802                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2803                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2804                    return true;
2805                }
2806            }
2807            return false;
2808        }
2809    }
2810
2811    @Override
2812    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2813        if (!sUserManager.exists(userId)) return null;
2814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2815        synchronized (mPackages) {
2816            PackageParser.Activity a = mReceivers.mActivities.get(component);
2817            if (DEBUG_PACKAGE_INFO) Log.v(
2818                TAG, "getReceiverInfo " + component + ": " + a);
2819            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2820                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2821                if (ps == null) return null;
2822                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2823                        userId);
2824            }
2825        }
2826        return null;
2827    }
2828
2829    @Override
2830    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2831        if (!sUserManager.exists(userId)) return null;
2832        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2833        synchronized (mPackages) {
2834            PackageParser.Service s = mServices.mServices.get(component);
2835            if (DEBUG_PACKAGE_INFO) Log.v(
2836                TAG, "getServiceInfo " + component + ": " + s);
2837            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2838                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2839                if (ps == null) return null;
2840                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2841                        userId);
2842            }
2843        }
2844        return null;
2845    }
2846
2847    @Override
2848    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2849        if (!sUserManager.exists(userId)) return null;
2850        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2851        synchronized (mPackages) {
2852            PackageParser.Provider p = mProviders.mProviders.get(component);
2853            if (DEBUG_PACKAGE_INFO) Log.v(
2854                TAG, "getProviderInfo " + component + ": " + p);
2855            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2856                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2857                if (ps == null) return null;
2858                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2859                        userId);
2860            }
2861        }
2862        return null;
2863    }
2864
2865    @Override
2866    public String[] getSystemSharedLibraryNames() {
2867        Set<String> libSet;
2868        synchronized (mPackages) {
2869            libSet = mSharedLibraries.keySet();
2870            int size = libSet.size();
2871            if (size > 0) {
2872                String[] libs = new String[size];
2873                libSet.toArray(libs);
2874                return libs;
2875            }
2876        }
2877        return null;
2878    }
2879
2880    /**
2881     * @hide
2882     */
2883    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2884        synchronized (mPackages) {
2885            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2886            if (lib != null && lib.apk != null) {
2887                return mPackages.get(lib.apk);
2888            }
2889        }
2890        return null;
2891    }
2892
2893    @Override
2894    public FeatureInfo[] getSystemAvailableFeatures() {
2895        Collection<FeatureInfo> featSet;
2896        synchronized (mPackages) {
2897            featSet = mAvailableFeatures.values();
2898            int size = featSet.size();
2899            if (size > 0) {
2900                FeatureInfo[] features = new FeatureInfo[size+1];
2901                featSet.toArray(features);
2902                FeatureInfo fi = new FeatureInfo();
2903                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2904                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2905                features[size] = fi;
2906                return features;
2907            }
2908        }
2909        return null;
2910    }
2911
2912    @Override
2913    public boolean hasSystemFeature(String name) {
2914        synchronized (mPackages) {
2915            return mAvailableFeatures.containsKey(name);
2916        }
2917    }
2918
2919    private void checkValidCaller(int uid, int userId) {
2920        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2921            return;
2922
2923        throw new SecurityException("Caller uid=" + uid
2924                + " is not privileged to communicate with user=" + userId);
2925    }
2926
2927    @Override
2928    public int checkPermission(String permName, String pkgName, int userId) {
2929        if (!sUserManager.exists(userId)) {
2930            return PackageManager.PERMISSION_DENIED;
2931        }
2932
2933        synchronized (mPackages) {
2934            final PackageParser.Package p = mPackages.get(pkgName);
2935            if (p != null && p.mExtras != null) {
2936                final PackageSetting ps = (PackageSetting) p.mExtras;
2937                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2938                    return PackageManager.PERMISSION_GRANTED;
2939                }
2940            }
2941        }
2942
2943        return PackageManager.PERMISSION_DENIED;
2944    }
2945
2946    @Override
2947    public int checkUidPermission(String permName, int uid) {
2948        final int userId = UserHandle.getUserId(uid);
2949
2950        if (!sUserManager.exists(userId)) {
2951            return PackageManager.PERMISSION_DENIED;
2952        }
2953
2954        synchronized (mPackages) {
2955            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2956            if (obj != null) {
2957                final SettingBase ps = (SettingBase) obj;
2958                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2959                    return PackageManager.PERMISSION_GRANTED;
2960                }
2961            } else {
2962                ArraySet<String> perms = mSystemPermissions.get(uid);
2963                if (perms != null && perms.contains(permName)) {
2964                    return PackageManager.PERMISSION_GRANTED;
2965                }
2966            }
2967        }
2968
2969        return PackageManager.PERMISSION_DENIED;
2970    }
2971
2972    /**
2973     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2974     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2975     * @param checkShell TODO(yamasani):
2976     * @param message the message to log on security exception
2977     */
2978    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2979            boolean checkShell, String message) {
2980        if (userId < 0) {
2981            throw new IllegalArgumentException("Invalid userId " + userId);
2982        }
2983        if (checkShell) {
2984            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2985        }
2986        if (userId == UserHandle.getUserId(callingUid)) return;
2987        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2988            if (requireFullPermission) {
2989                mContext.enforceCallingOrSelfPermission(
2990                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2991            } else {
2992                try {
2993                    mContext.enforceCallingOrSelfPermission(
2994                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2995                } catch (SecurityException se) {
2996                    mContext.enforceCallingOrSelfPermission(
2997                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2998                }
2999            }
3000        }
3001    }
3002
3003    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3004        if (callingUid == Process.SHELL_UID) {
3005            if (userHandle >= 0
3006                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3007                throw new SecurityException("Shell does not have permission to access user "
3008                        + userHandle);
3009            } else if (userHandle < 0) {
3010                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3011                        + Debug.getCallers(3));
3012            }
3013        }
3014    }
3015
3016    private BasePermission findPermissionTreeLP(String permName) {
3017        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3018            if (permName.startsWith(bp.name) &&
3019                    permName.length() > bp.name.length() &&
3020                    permName.charAt(bp.name.length()) == '.') {
3021                return bp;
3022            }
3023        }
3024        return null;
3025    }
3026
3027    private BasePermission checkPermissionTreeLP(String permName) {
3028        if (permName != null) {
3029            BasePermission bp = findPermissionTreeLP(permName);
3030            if (bp != null) {
3031                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3032                    return bp;
3033                }
3034                throw new SecurityException("Calling uid "
3035                        + Binder.getCallingUid()
3036                        + " is not allowed to add to permission tree "
3037                        + bp.name + " owned by uid " + bp.uid);
3038            }
3039        }
3040        throw new SecurityException("No permission tree found for " + permName);
3041    }
3042
3043    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3044        if (s1 == null) {
3045            return s2 == null;
3046        }
3047        if (s2 == null) {
3048            return false;
3049        }
3050        if (s1.getClass() != s2.getClass()) {
3051            return false;
3052        }
3053        return s1.equals(s2);
3054    }
3055
3056    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3057        if (pi1.icon != pi2.icon) return false;
3058        if (pi1.logo != pi2.logo) return false;
3059        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3060        if (!compareStrings(pi1.name, pi2.name)) return false;
3061        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3062        // We'll take care of setting this one.
3063        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3064        // These are not currently stored in settings.
3065        //if (!compareStrings(pi1.group, pi2.group)) return false;
3066        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3067        //if (pi1.labelRes != pi2.labelRes) return false;
3068        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3069        return true;
3070    }
3071
3072    int permissionInfoFootprint(PermissionInfo info) {
3073        int size = info.name.length();
3074        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3075        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3076        return size;
3077    }
3078
3079    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3080        int size = 0;
3081        for (BasePermission perm : mSettings.mPermissions.values()) {
3082            if (perm.uid == tree.uid) {
3083                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3084            }
3085        }
3086        return size;
3087    }
3088
3089    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3090        // We calculate the max size of permissions defined by this uid and throw
3091        // if that plus the size of 'info' would exceed our stated maximum.
3092        if (tree.uid != Process.SYSTEM_UID) {
3093            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3094            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3095                throw new SecurityException("Permission tree size cap exceeded");
3096            }
3097        }
3098    }
3099
3100    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3101        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3102            throw new SecurityException("Label must be specified in permission");
3103        }
3104        BasePermission tree = checkPermissionTreeLP(info.name);
3105        BasePermission bp = mSettings.mPermissions.get(info.name);
3106        boolean added = bp == null;
3107        boolean changed = true;
3108        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3109        if (added) {
3110            enforcePermissionCapLocked(info, tree);
3111            bp = new BasePermission(info.name, tree.sourcePackage,
3112                    BasePermission.TYPE_DYNAMIC);
3113        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3114            throw new SecurityException(
3115                    "Not allowed to modify non-dynamic permission "
3116                    + info.name);
3117        } else {
3118            if (bp.protectionLevel == fixedLevel
3119                    && bp.perm.owner.equals(tree.perm.owner)
3120                    && bp.uid == tree.uid
3121                    && comparePermissionInfos(bp.perm.info, info)) {
3122                changed = false;
3123            }
3124        }
3125        bp.protectionLevel = fixedLevel;
3126        info = new PermissionInfo(info);
3127        info.protectionLevel = fixedLevel;
3128        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3129        bp.perm.info.packageName = tree.perm.info.packageName;
3130        bp.uid = tree.uid;
3131        if (added) {
3132            mSettings.mPermissions.put(info.name, bp);
3133        }
3134        if (changed) {
3135            if (!async) {
3136                mSettings.writeLPr();
3137            } else {
3138                scheduleWriteSettingsLocked();
3139            }
3140        }
3141        return added;
3142    }
3143
3144    @Override
3145    public boolean addPermission(PermissionInfo info) {
3146        synchronized (mPackages) {
3147            return addPermissionLocked(info, false);
3148        }
3149    }
3150
3151    @Override
3152    public boolean addPermissionAsync(PermissionInfo info) {
3153        synchronized (mPackages) {
3154            return addPermissionLocked(info, true);
3155        }
3156    }
3157
3158    @Override
3159    public void removePermission(String name) {
3160        synchronized (mPackages) {
3161            checkPermissionTreeLP(name);
3162            BasePermission bp = mSettings.mPermissions.get(name);
3163            if (bp != null) {
3164                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3165                    throw new SecurityException(
3166                            "Not allowed to modify non-dynamic permission "
3167                            + name);
3168                }
3169                mSettings.mPermissions.remove(name);
3170                mSettings.writeLPr();
3171            }
3172        }
3173    }
3174
3175    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3176            BasePermission bp) {
3177        int index = pkg.requestedPermissions.indexOf(bp.name);
3178        if (index == -1) {
3179            throw new SecurityException("Package " + pkg.packageName
3180                    + " has not requested permission " + bp.name);
3181        }
3182        if (!bp.isRuntime()) {
3183            throw new SecurityException("Permission " + bp.name
3184                    + " is not a changeable permission type");
3185        }
3186    }
3187
3188    @Override
3189    public void grantRuntimePermission(String packageName, String name, final int userId) {
3190        if (!sUserManager.exists(userId)) {
3191            Log.e(TAG, "No such user:" + userId);
3192            return;
3193        }
3194
3195        mContext.enforceCallingOrSelfPermission(
3196                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3197                "grantRuntimePermission");
3198
3199        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3200                "grantRuntimePermission");
3201
3202        final SettingBase sb;
3203
3204        synchronized (mPackages) {
3205            final PackageParser.Package pkg = mPackages.get(packageName);
3206            if (pkg == null) {
3207                throw new IllegalArgumentException("Unknown package: " + packageName);
3208            }
3209
3210            final BasePermission bp = mSettings.mPermissions.get(name);
3211            if (bp == null) {
3212                throw new IllegalArgumentException("Unknown permission: " + name);
3213            }
3214
3215            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3216
3217            sb = (SettingBase) pkg.mExtras;
3218            if (sb == null) {
3219                throw new IllegalArgumentException("Unknown package: " + packageName);
3220            }
3221
3222            final PermissionsState permissionsState = sb.getPermissionsState();
3223
3224            final int flags = permissionsState.getPermissionFlags(name, userId);
3225            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3226                throw new SecurityException("Cannot grant system fixed permission: "
3227                        + name + " for package: " + packageName);
3228            }
3229
3230            final int result = permissionsState.grantRuntimePermission(bp, userId);
3231            switch (result) {
3232                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3233                    return;
3234                }
3235
3236                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3237                    mHandler.post(new Runnable() {
3238                        @Override
3239                        public void run() {
3240                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3241                        }
3242                    });
3243                } break;
3244            }
3245
3246            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3247
3248            // Not critical if that is lost - app has to request again.
3249            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3250        }
3251    }
3252
3253    @Override
3254    public void revokeRuntimePermission(String packageName, String name, int userId) {
3255        if (!sUserManager.exists(userId)) {
3256            Log.e(TAG, "No such user:" + userId);
3257            return;
3258        }
3259
3260        mContext.enforceCallingOrSelfPermission(
3261                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3262                "revokeRuntimePermission");
3263
3264        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3265                "revokeRuntimePermission");
3266
3267        final SettingBase sb;
3268
3269        synchronized (mPackages) {
3270            final PackageParser.Package pkg = mPackages.get(packageName);
3271            if (pkg == null) {
3272                throw new IllegalArgumentException("Unknown package: " + packageName);
3273            }
3274
3275            final BasePermission bp = mSettings.mPermissions.get(name);
3276            if (bp == null) {
3277                throw new IllegalArgumentException("Unknown permission: " + name);
3278            }
3279
3280            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3281
3282            sb = (SettingBase) pkg.mExtras;
3283            if (sb == null) {
3284                throw new IllegalArgumentException("Unknown package: " + packageName);
3285            }
3286
3287            final PermissionsState permissionsState = sb.getPermissionsState();
3288
3289            final int flags = permissionsState.getPermissionFlags(name, userId);
3290            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3291                throw new SecurityException("Cannot revoke system fixed permission: "
3292                        + name + " for package: " + packageName);
3293            }
3294
3295            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3296                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3297                return;
3298            }
3299
3300            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3301
3302            // Critical, after this call app should never have the permission.
3303            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3304        }
3305
3306        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3307    }
3308
3309    @Override
3310    public int getPermissionFlags(String name, String packageName, int userId) {
3311        if (!sUserManager.exists(userId)) {
3312            return 0;
3313        }
3314
3315        mContext.enforceCallingOrSelfPermission(
3316                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3317                "getPermissionFlags");
3318
3319        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3320                "getPermissionFlags");
3321
3322        synchronized (mPackages) {
3323            final PackageParser.Package pkg = mPackages.get(packageName);
3324            if (pkg == null) {
3325                throw new IllegalArgumentException("Unknown package: " + packageName);
3326            }
3327
3328            final BasePermission bp = mSettings.mPermissions.get(name);
3329            if (bp == null) {
3330                throw new IllegalArgumentException("Unknown permission: " + name);
3331            }
3332
3333            SettingBase sb = (SettingBase) pkg.mExtras;
3334            if (sb == null) {
3335                throw new IllegalArgumentException("Unknown package: " + packageName);
3336            }
3337
3338            PermissionsState permissionsState = sb.getPermissionsState();
3339            return permissionsState.getPermissionFlags(name, userId);
3340        }
3341    }
3342
3343    @Override
3344    public void updatePermissionFlags(String name, String packageName, int flagMask,
3345            int flagValues, int userId) {
3346        if (!sUserManager.exists(userId)) {
3347            return;
3348        }
3349
3350        mContext.enforceCallingOrSelfPermission(
3351                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3352                "updatePermissionFlags");
3353
3354        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3355                "updatePermissionFlags");
3356
3357        // Only the system can change policy and system fixed flags.
3358        if (getCallingUid() != Process.SYSTEM_UID) {
3359            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3360            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3361
3362            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3363            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3364        }
3365
3366        synchronized (mPackages) {
3367            final PackageParser.Package pkg = mPackages.get(packageName);
3368            if (pkg == null) {
3369                throw new IllegalArgumentException("Unknown package: " + packageName);
3370            }
3371
3372            final BasePermission bp = mSettings.mPermissions.get(name);
3373            if (bp == null) {
3374                throw new IllegalArgumentException("Unknown permission: " + name);
3375            }
3376
3377            SettingBase sb = (SettingBase) pkg.mExtras;
3378            if (sb == null) {
3379                throw new IllegalArgumentException("Unknown package: " + packageName);
3380            }
3381
3382            PermissionsState permissionsState = sb.getPermissionsState();
3383
3384            // Only the package manager can change flags for system component permissions.
3385            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3386            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3387                return;
3388            }
3389
3390            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3391                // Install and runtime permissions are stored in different places,
3392                // so figure out what permission changed and persist the change.
3393                if (permissionsState.getInstallPermissionState(name) != null) {
3394                    scheduleWriteSettingsLocked();
3395                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3396                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3397                }
3398            }
3399        }
3400    }
3401
3402    @Override
3403    public boolean shouldShowRequestPermissionRationale(String permissionName,
3404            String packageName, int userId) {
3405        if (UserHandle.getCallingUserId() != userId) {
3406            mContext.enforceCallingPermission(
3407                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3408                    "canShowRequestPermissionRationale for user " + userId);
3409        }
3410
3411        final int uid = getPackageUid(packageName, userId);
3412        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3413            return false;
3414        }
3415
3416        if (checkPermission(permissionName, packageName, userId)
3417                == PackageManager.PERMISSION_GRANTED) {
3418            return false;
3419        }
3420
3421        final int flags;
3422
3423        final long identity = Binder.clearCallingIdentity();
3424        try {
3425            flags = getPermissionFlags(permissionName,
3426                    packageName, userId);
3427        } finally {
3428            Binder.restoreCallingIdentity(identity);
3429        }
3430
3431        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3432                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3433                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3434
3435        if ((flags & fixedFlags) != 0) {
3436            return false;
3437        }
3438
3439        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3440    }
3441
3442    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3443        BasePermission bp = mSettings.mPermissions.get(permission);
3444        if (bp == null) {
3445            throw new SecurityException("Missing " + permission + " permission");
3446        }
3447
3448        SettingBase sb = (SettingBase) pkg.mExtras;
3449        PermissionsState permissionsState = sb.getPermissionsState();
3450
3451        if (permissionsState.grantInstallPermission(bp) !=
3452                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3453            scheduleWriteSettingsLocked();
3454        }
3455    }
3456
3457    @Override
3458    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3459        mContext.enforceCallingOrSelfPermission(
3460                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3461                "addOnPermissionsChangeListener");
3462
3463        synchronized (mPackages) {
3464            mOnPermissionChangeListeners.addListenerLocked(listener);
3465        }
3466    }
3467
3468    @Override
3469    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3470        synchronized (mPackages) {
3471            mOnPermissionChangeListeners.removeListenerLocked(listener);
3472        }
3473    }
3474
3475    @Override
3476    public boolean isProtectedBroadcast(String actionName) {
3477        synchronized (mPackages) {
3478            return mProtectedBroadcasts.contains(actionName);
3479        }
3480    }
3481
3482    @Override
3483    public int checkSignatures(String pkg1, String pkg2) {
3484        synchronized (mPackages) {
3485            final PackageParser.Package p1 = mPackages.get(pkg1);
3486            final PackageParser.Package p2 = mPackages.get(pkg2);
3487            if (p1 == null || p1.mExtras == null
3488                    || p2 == null || p2.mExtras == null) {
3489                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3490            }
3491            return compareSignatures(p1.mSignatures, p2.mSignatures);
3492        }
3493    }
3494
3495    @Override
3496    public int checkUidSignatures(int uid1, int uid2) {
3497        // Map to base uids.
3498        uid1 = UserHandle.getAppId(uid1);
3499        uid2 = UserHandle.getAppId(uid2);
3500        // reader
3501        synchronized (mPackages) {
3502            Signature[] s1;
3503            Signature[] s2;
3504            Object obj = mSettings.getUserIdLPr(uid1);
3505            if (obj != null) {
3506                if (obj instanceof SharedUserSetting) {
3507                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3508                } else if (obj instanceof PackageSetting) {
3509                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3510                } else {
3511                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3512                }
3513            } else {
3514                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3515            }
3516            obj = mSettings.getUserIdLPr(uid2);
3517            if (obj != null) {
3518                if (obj instanceof SharedUserSetting) {
3519                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3520                } else if (obj instanceof PackageSetting) {
3521                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3522                } else {
3523                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3524                }
3525            } else {
3526                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3527            }
3528            return compareSignatures(s1, s2);
3529        }
3530    }
3531
3532    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3533        final long identity = Binder.clearCallingIdentity();
3534        try {
3535            if (sb instanceof SharedUserSetting) {
3536                SharedUserSetting sus = (SharedUserSetting) sb;
3537                final int packageCount = sus.packages.size();
3538                for (int i = 0; i < packageCount; i++) {
3539                    PackageSetting susPs = sus.packages.valueAt(i);
3540                    if (userId == UserHandle.USER_ALL) {
3541                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3542                    } else {
3543                        final int uid = UserHandle.getUid(userId, susPs.appId);
3544                        killUid(uid, reason);
3545                    }
3546                }
3547            } else if (sb instanceof PackageSetting) {
3548                PackageSetting ps = (PackageSetting) sb;
3549                if (userId == UserHandle.USER_ALL) {
3550                    killApplication(ps.pkg.packageName, ps.appId, reason);
3551                } else {
3552                    final int uid = UserHandle.getUid(userId, ps.appId);
3553                    killUid(uid, reason);
3554                }
3555            }
3556        } finally {
3557            Binder.restoreCallingIdentity(identity);
3558        }
3559    }
3560
3561    private static void killUid(int uid, String reason) {
3562        IActivityManager am = ActivityManagerNative.getDefault();
3563        if (am != null) {
3564            try {
3565                am.killUid(uid, reason);
3566            } catch (RemoteException e) {
3567                /* ignore - same process */
3568            }
3569        }
3570    }
3571
3572    /**
3573     * Compares two sets of signatures. Returns:
3574     * <br />
3575     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3576     * <br />
3577     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3578     * <br />
3579     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3580     * <br />
3581     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3582     * <br />
3583     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3584     */
3585    static int compareSignatures(Signature[] s1, Signature[] s2) {
3586        if (s1 == null) {
3587            return s2 == null
3588                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3589                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3590        }
3591
3592        if (s2 == null) {
3593            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3594        }
3595
3596        if (s1.length != s2.length) {
3597            return PackageManager.SIGNATURE_NO_MATCH;
3598        }
3599
3600        // Since both signature sets are of size 1, we can compare without HashSets.
3601        if (s1.length == 1) {
3602            return s1[0].equals(s2[0]) ?
3603                    PackageManager.SIGNATURE_MATCH :
3604                    PackageManager.SIGNATURE_NO_MATCH;
3605        }
3606
3607        ArraySet<Signature> set1 = new ArraySet<Signature>();
3608        for (Signature sig : s1) {
3609            set1.add(sig);
3610        }
3611        ArraySet<Signature> set2 = new ArraySet<Signature>();
3612        for (Signature sig : s2) {
3613            set2.add(sig);
3614        }
3615        // Make sure s2 contains all signatures in s1.
3616        if (set1.equals(set2)) {
3617            return PackageManager.SIGNATURE_MATCH;
3618        }
3619        return PackageManager.SIGNATURE_NO_MATCH;
3620    }
3621
3622    /**
3623     * If the database version for this type of package (internal storage or
3624     * external storage) is less than the version where package signatures
3625     * were updated, return true.
3626     */
3627    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3628        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3629                DatabaseVersion.SIGNATURE_END_ENTITY))
3630                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3631                        DatabaseVersion.SIGNATURE_END_ENTITY));
3632    }
3633
3634    /**
3635     * Used for backward compatibility to make sure any packages with
3636     * certificate chains get upgraded to the new style. {@code existingSigs}
3637     * will be in the old format (since they were stored on disk from before the
3638     * system upgrade) and {@code scannedSigs} will be in the newer format.
3639     */
3640    private int compareSignaturesCompat(PackageSignatures existingSigs,
3641            PackageParser.Package scannedPkg) {
3642        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3643            return PackageManager.SIGNATURE_NO_MATCH;
3644        }
3645
3646        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3647        for (Signature sig : existingSigs.mSignatures) {
3648            existingSet.add(sig);
3649        }
3650        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3651        for (Signature sig : scannedPkg.mSignatures) {
3652            try {
3653                Signature[] chainSignatures = sig.getChainSignatures();
3654                for (Signature chainSig : chainSignatures) {
3655                    scannedCompatSet.add(chainSig);
3656                }
3657            } catch (CertificateEncodingException e) {
3658                scannedCompatSet.add(sig);
3659            }
3660        }
3661        /*
3662         * Make sure the expanded scanned set contains all signatures in the
3663         * existing one.
3664         */
3665        if (scannedCompatSet.equals(existingSet)) {
3666            // Migrate the old signatures to the new scheme.
3667            existingSigs.assignSignatures(scannedPkg.mSignatures);
3668            // The new KeySets will be re-added later in the scanning process.
3669            synchronized (mPackages) {
3670                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3671            }
3672            return PackageManager.SIGNATURE_MATCH;
3673        }
3674        return PackageManager.SIGNATURE_NO_MATCH;
3675    }
3676
3677    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3678        if (isExternal(scannedPkg)) {
3679            return mSettings.isExternalDatabaseVersionOlderThan(
3680                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3681        } else {
3682            return mSettings.isInternalDatabaseVersionOlderThan(
3683                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3684        }
3685    }
3686
3687    private int compareSignaturesRecover(PackageSignatures existingSigs,
3688            PackageParser.Package scannedPkg) {
3689        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3690            return PackageManager.SIGNATURE_NO_MATCH;
3691        }
3692
3693        String msg = null;
3694        try {
3695            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3696                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3697                        + scannedPkg.packageName);
3698                return PackageManager.SIGNATURE_MATCH;
3699            }
3700        } catch (CertificateException e) {
3701            msg = e.getMessage();
3702        }
3703
3704        logCriticalInfo(Log.INFO,
3705                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3706        return PackageManager.SIGNATURE_NO_MATCH;
3707    }
3708
3709    @Override
3710    public String[] getPackagesForUid(int uid) {
3711        uid = UserHandle.getAppId(uid);
3712        // reader
3713        synchronized (mPackages) {
3714            Object obj = mSettings.getUserIdLPr(uid);
3715            if (obj instanceof SharedUserSetting) {
3716                final SharedUserSetting sus = (SharedUserSetting) obj;
3717                final int N = sus.packages.size();
3718                final String[] res = new String[N];
3719                final Iterator<PackageSetting> it = sus.packages.iterator();
3720                int i = 0;
3721                while (it.hasNext()) {
3722                    res[i++] = it.next().name;
3723                }
3724                return res;
3725            } else if (obj instanceof PackageSetting) {
3726                final PackageSetting ps = (PackageSetting) obj;
3727                return new String[] { ps.name };
3728            }
3729        }
3730        return null;
3731    }
3732
3733    @Override
3734    public String getNameForUid(int uid) {
3735        // reader
3736        synchronized (mPackages) {
3737            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3738            if (obj instanceof SharedUserSetting) {
3739                final SharedUserSetting sus = (SharedUserSetting) obj;
3740                return sus.name + ":" + sus.userId;
3741            } else if (obj instanceof PackageSetting) {
3742                final PackageSetting ps = (PackageSetting) obj;
3743                return ps.name;
3744            }
3745        }
3746        return null;
3747    }
3748
3749    @Override
3750    public int getUidForSharedUser(String sharedUserName) {
3751        if(sharedUserName == null) {
3752            return -1;
3753        }
3754        // reader
3755        synchronized (mPackages) {
3756            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3757            if (suid == null) {
3758                return -1;
3759            }
3760            return suid.userId;
3761        }
3762    }
3763
3764    @Override
3765    public int getFlagsForUid(int uid) {
3766        synchronized (mPackages) {
3767            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3768            if (obj instanceof SharedUserSetting) {
3769                final SharedUserSetting sus = (SharedUserSetting) obj;
3770                return sus.pkgFlags;
3771            } else if (obj instanceof PackageSetting) {
3772                final PackageSetting ps = (PackageSetting) obj;
3773                return ps.pkgFlags;
3774            }
3775        }
3776        return 0;
3777    }
3778
3779    @Override
3780    public int getPrivateFlagsForUid(int uid) {
3781        synchronized (mPackages) {
3782            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3783            if (obj instanceof SharedUserSetting) {
3784                final SharedUserSetting sus = (SharedUserSetting) obj;
3785                return sus.pkgPrivateFlags;
3786            } else if (obj instanceof PackageSetting) {
3787                final PackageSetting ps = (PackageSetting) obj;
3788                return ps.pkgPrivateFlags;
3789            }
3790        }
3791        return 0;
3792    }
3793
3794    @Override
3795    public boolean isUidPrivileged(int uid) {
3796        uid = UserHandle.getAppId(uid);
3797        // reader
3798        synchronized (mPackages) {
3799            Object obj = mSettings.getUserIdLPr(uid);
3800            if (obj instanceof SharedUserSetting) {
3801                final SharedUserSetting sus = (SharedUserSetting) obj;
3802                final Iterator<PackageSetting> it = sus.packages.iterator();
3803                while (it.hasNext()) {
3804                    if (it.next().isPrivileged()) {
3805                        return true;
3806                    }
3807                }
3808            } else if (obj instanceof PackageSetting) {
3809                final PackageSetting ps = (PackageSetting) obj;
3810                return ps.isPrivileged();
3811            }
3812        }
3813        return false;
3814    }
3815
3816    @Override
3817    public String[] getAppOpPermissionPackages(String permissionName) {
3818        synchronized (mPackages) {
3819            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3820            if (pkgs == null) {
3821                return null;
3822            }
3823            return pkgs.toArray(new String[pkgs.size()]);
3824        }
3825    }
3826
3827    @Override
3828    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3829            int flags, int userId) {
3830        if (!sUserManager.exists(userId)) return null;
3831        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3832        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3833        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3834    }
3835
3836    @Override
3837    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3838            IntentFilter filter, int match, ComponentName activity) {
3839        final int userId = UserHandle.getCallingUserId();
3840        if (DEBUG_PREFERRED) {
3841            Log.v(TAG, "setLastChosenActivity intent=" + intent
3842                + " resolvedType=" + resolvedType
3843                + " flags=" + flags
3844                + " filter=" + filter
3845                + " match=" + match
3846                + " activity=" + activity);
3847            filter.dump(new PrintStreamPrinter(System.out), "    ");
3848        }
3849        intent.setComponent(null);
3850        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3851        // Find any earlier preferred or last chosen entries and nuke them
3852        findPreferredActivity(intent, resolvedType,
3853                flags, query, 0, false, true, false, userId);
3854        // Add the new activity as the last chosen for this filter
3855        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3856                "Setting last chosen");
3857    }
3858
3859    @Override
3860    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3861        final int userId = UserHandle.getCallingUserId();
3862        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3863        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3864        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3865                false, false, false, userId);
3866    }
3867
3868    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3869            int flags, List<ResolveInfo> query, int userId) {
3870        if (query != null) {
3871            final int N = query.size();
3872            if (N == 1) {
3873                return query.get(0);
3874            } else if (N > 1) {
3875                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3876                // If there is more than one activity with the same priority,
3877                // then let the user decide between them.
3878                ResolveInfo r0 = query.get(0);
3879                ResolveInfo r1 = query.get(1);
3880                if (DEBUG_INTENT_MATCHING || debug) {
3881                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3882                            + r1.activityInfo.name + "=" + r1.priority);
3883                }
3884                // If the first activity has a higher priority, or a different
3885                // default, then it is always desireable to pick it.
3886                if (r0.priority != r1.priority
3887                        || r0.preferredOrder != r1.preferredOrder
3888                        || r0.isDefault != r1.isDefault) {
3889                    return query.get(0);
3890                }
3891                // If we have saved a preference for a preferred activity for
3892                // this Intent, use that.
3893                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3894                        flags, query, r0.priority, true, false, debug, userId);
3895                if (ri != null) {
3896                    return ri;
3897                }
3898                if (userId != 0) {
3899                    ri = new ResolveInfo(mResolveInfo);
3900                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3901                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3902                            ri.activityInfo.applicationInfo);
3903                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3904                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3905                    return ri;
3906                }
3907                return mResolveInfo;
3908            }
3909        }
3910        return null;
3911    }
3912
3913    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3914            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3915        final int N = query.size();
3916        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3917                .get(userId);
3918        // Get the list of persistent preferred activities that handle the intent
3919        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3920        List<PersistentPreferredActivity> pprefs = ppir != null
3921                ? ppir.queryIntent(intent, resolvedType,
3922                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3923                : null;
3924        if (pprefs != null && pprefs.size() > 0) {
3925            final int M = pprefs.size();
3926            for (int i=0; i<M; i++) {
3927                final PersistentPreferredActivity ppa = pprefs.get(i);
3928                if (DEBUG_PREFERRED || debug) {
3929                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3930                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3931                            + "\n  component=" + ppa.mComponent);
3932                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3933                }
3934                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3935                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3936                if (DEBUG_PREFERRED || debug) {
3937                    Slog.v(TAG, "Found persistent preferred activity:");
3938                    if (ai != null) {
3939                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3940                    } else {
3941                        Slog.v(TAG, "  null");
3942                    }
3943                }
3944                if (ai == null) {
3945                    // This previously registered persistent preferred activity
3946                    // component is no longer known. Ignore it and do NOT remove it.
3947                    continue;
3948                }
3949                for (int j=0; j<N; j++) {
3950                    final ResolveInfo ri = query.get(j);
3951                    if (!ri.activityInfo.applicationInfo.packageName
3952                            .equals(ai.applicationInfo.packageName)) {
3953                        continue;
3954                    }
3955                    if (!ri.activityInfo.name.equals(ai.name)) {
3956                        continue;
3957                    }
3958                    //  Found a persistent preference that can handle the intent.
3959                    if (DEBUG_PREFERRED || debug) {
3960                        Slog.v(TAG, "Returning persistent preferred activity: " +
3961                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3962                    }
3963                    return ri;
3964                }
3965            }
3966        }
3967        return null;
3968    }
3969
3970    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3971            List<ResolveInfo> query, int priority, boolean always,
3972            boolean removeMatches, boolean debug, int userId) {
3973        if (!sUserManager.exists(userId)) return null;
3974        // writer
3975        synchronized (mPackages) {
3976            if (intent.getSelector() != null) {
3977                intent = intent.getSelector();
3978            }
3979            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3980
3981            // Try to find a matching persistent preferred activity.
3982            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3983                    debug, userId);
3984
3985            // If a persistent preferred activity matched, use it.
3986            if (pri != null) {
3987                return pri;
3988            }
3989
3990            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3991            // Get the list of preferred activities that handle the intent
3992            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3993            List<PreferredActivity> prefs = pir != null
3994                    ? pir.queryIntent(intent, resolvedType,
3995                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3996                    : null;
3997            if (prefs != null && prefs.size() > 0) {
3998                boolean changed = false;
3999                try {
4000                    // First figure out how good the original match set is.
4001                    // We will only allow preferred activities that came
4002                    // from the same match quality.
4003                    int match = 0;
4004
4005                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4006
4007                    final int N = query.size();
4008                    for (int j=0; j<N; j++) {
4009                        final ResolveInfo ri = query.get(j);
4010                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4011                                + ": 0x" + Integer.toHexString(match));
4012                        if (ri.match > match) {
4013                            match = ri.match;
4014                        }
4015                    }
4016
4017                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4018                            + Integer.toHexString(match));
4019
4020                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4021                    final int M = prefs.size();
4022                    for (int i=0; i<M; i++) {
4023                        final PreferredActivity pa = prefs.get(i);
4024                        if (DEBUG_PREFERRED || debug) {
4025                            Slog.v(TAG, "Checking PreferredActivity ds="
4026                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4027                                    + "\n  component=" + pa.mPref.mComponent);
4028                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4029                        }
4030                        if (pa.mPref.mMatch != match) {
4031                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4032                                    + Integer.toHexString(pa.mPref.mMatch));
4033                            continue;
4034                        }
4035                        // If it's not an "always" type preferred activity and that's what we're
4036                        // looking for, skip it.
4037                        if (always && !pa.mPref.mAlways) {
4038                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4039                            continue;
4040                        }
4041                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4042                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4043                        if (DEBUG_PREFERRED || debug) {
4044                            Slog.v(TAG, "Found preferred activity:");
4045                            if (ai != null) {
4046                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4047                            } else {
4048                                Slog.v(TAG, "  null");
4049                            }
4050                        }
4051                        if (ai == null) {
4052                            // This previously registered preferred activity
4053                            // component is no longer known.  Most likely an update
4054                            // to the app was installed and in the new version this
4055                            // component no longer exists.  Clean it up by removing
4056                            // it from the preferred activities list, and skip it.
4057                            Slog.w(TAG, "Removing dangling preferred activity: "
4058                                    + pa.mPref.mComponent);
4059                            pir.removeFilter(pa);
4060                            changed = true;
4061                            continue;
4062                        }
4063                        for (int j=0; j<N; j++) {
4064                            final ResolveInfo ri = query.get(j);
4065                            if (!ri.activityInfo.applicationInfo.packageName
4066                                    .equals(ai.applicationInfo.packageName)) {
4067                                continue;
4068                            }
4069                            if (!ri.activityInfo.name.equals(ai.name)) {
4070                                continue;
4071                            }
4072
4073                            if (removeMatches) {
4074                                pir.removeFilter(pa);
4075                                changed = true;
4076                                if (DEBUG_PREFERRED) {
4077                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4078                                }
4079                                break;
4080                            }
4081
4082                            // Okay we found a previously set preferred or last chosen app.
4083                            // If the result set is different from when this
4084                            // was created, we need to clear it and re-ask the
4085                            // user their preference, if we're looking for an "always" type entry.
4086                            if (always && !pa.mPref.sameSet(query)) {
4087                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4088                                        + intent + " type " + resolvedType);
4089                                if (DEBUG_PREFERRED) {
4090                                    Slog.v(TAG, "Removing preferred activity since set changed "
4091                                            + pa.mPref.mComponent);
4092                                }
4093                                pir.removeFilter(pa);
4094                                // Re-add the filter as a "last chosen" entry (!always)
4095                                PreferredActivity lastChosen = new PreferredActivity(
4096                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4097                                pir.addFilter(lastChosen);
4098                                changed = true;
4099                                return null;
4100                            }
4101
4102                            // Yay! Either the set matched or we're looking for the last chosen
4103                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4104                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4105                            return ri;
4106                        }
4107                    }
4108                } finally {
4109                    if (changed) {
4110                        if (DEBUG_PREFERRED) {
4111                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4112                        }
4113                        scheduleWritePackageRestrictionsLocked(userId);
4114                    }
4115                }
4116            }
4117        }
4118        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4119        return null;
4120    }
4121
4122    /*
4123     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4124     */
4125    @Override
4126    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4127            int targetUserId) {
4128        mContext.enforceCallingOrSelfPermission(
4129                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4130        List<CrossProfileIntentFilter> matches =
4131                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4132        if (matches != null) {
4133            int size = matches.size();
4134            for (int i = 0; i < size; i++) {
4135                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4136            }
4137        }
4138        if (hasWebURI(intent)) {
4139            // cross-profile app linking works only towards the parent.
4140            final UserInfo parent = getProfileParent(sourceUserId);
4141            synchronized(mPackages) {
4142                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4143                        parent.id) != null;
4144            }
4145        }
4146        return false;
4147    }
4148
4149    private UserInfo getProfileParent(int userId) {
4150        final long identity = Binder.clearCallingIdentity();
4151        try {
4152            return sUserManager.getProfileParent(userId);
4153        } finally {
4154            Binder.restoreCallingIdentity(identity);
4155        }
4156    }
4157
4158    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4159            String resolvedType, int userId) {
4160        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4161        if (resolver != null) {
4162            return resolver.queryIntent(intent, resolvedType, false, userId);
4163        }
4164        return null;
4165    }
4166
4167    @Override
4168    public List<ResolveInfo> queryIntentActivities(Intent intent,
4169            String resolvedType, int flags, int userId) {
4170        if (!sUserManager.exists(userId)) return Collections.emptyList();
4171        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4172        ComponentName comp = intent.getComponent();
4173        if (comp == null) {
4174            if (intent.getSelector() != null) {
4175                intent = intent.getSelector();
4176                comp = intent.getComponent();
4177            }
4178        }
4179
4180        if (comp != null) {
4181            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4182            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4183            if (ai != null) {
4184                final ResolveInfo ri = new ResolveInfo();
4185                ri.activityInfo = ai;
4186                list.add(ri);
4187            }
4188            return list;
4189        }
4190
4191        // reader
4192        synchronized (mPackages) {
4193            final String pkgName = intent.getPackage();
4194            if (pkgName == null) {
4195                List<CrossProfileIntentFilter> matchingFilters =
4196                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4197                // Check for results that need to skip the current profile.
4198                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4199                        resolvedType, flags, userId);
4200                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4201                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4202                    result.add(xpResolveInfo);
4203                    return filterIfNotPrimaryUser(result, userId);
4204                }
4205
4206                // Check for results in the current profile.
4207                List<ResolveInfo> result = mActivities.queryIntent(
4208                        intent, resolvedType, flags, userId);
4209
4210                // Check for cross profile results.
4211                xpResolveInfo = queryCrossProfileIntents(
4212                        matchingFilters, intent, resolvedType, flags, userId);
4213                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4214                    result.add(xpResolveInfo);
4215                    Collections.sort(result, mResolvePrioritySorter);
4216                }
4217                result = filterIfNotPrimaryUser(result, userId);
4218                if (hasWebURI(intent)) {
4219                    CrossProfileDomainInfo xpDomainInfo = null;
4220                    final UserInfo parent = getProfileParent(userId);
4221                    if (parent != null) {
4222                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4223                                flags, userId, parent.id);
4224                    }
4225                    if (xpDomainInfo != null) {
4226                        if (xpResolveInfo != null) {
4227                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4228                            // in the result.
4229                            result.remove(xpResolveInfo);
4230                        }
4231                        if (result.size() == 0) {
4232                            result.add(xpDomainInfo.resolveInfo);
4233                            return result;
4234                        }
4235                    } else if (result.size() <= 1) {
4236                        return result;
4237                    }
4238                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4239                            xpDomainInfo);
4240                    Collections.sort(result, mResolvePrioritySorter);
4241                }
4242                return result;
4243            }
4244            final PackageParser.Package pkg = mPackages.get(pkgName);
4245            if (pkg != null) {
4246                return filterIfNotPrimaryUser(
4247                        mActivities.queryIntentForPackage(
4248                                intent, resolvedType, flags, pkg.activities, userId),
4249                        userId);
4250            }
4251            return new ArrayList<ResolveInfo>();
4252        }
4253    }
4254
4255    private static class CrossProfileDomainInfo {
4256        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4257        ResolveInfo resolveInfo;
4258        /* Best domain verification status of the activities found in the other profile */
4259        int bestDomainVerificationStatus;
4260    }
4261
4262    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4263            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4264        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4265                sourceUserId)) {
4266            return null;
4267        }
4268        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4269                resolvedType, flags, parentUserId);
4270
4271        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4272            return null;
4273        }
4274        CrossProfileDomainInfo result = null;
4275        int size = resultTargetUser.size();
4276        for (int i = 0; i < size; i++) {
4277            ResolveInfo riTargetUser = resultTargetUser.get(i);
4278            // Intent filter verification is only for filters that specify a host. So don't return
4279            // those that handle all web uris.
4280            if (riTargetUser.handleAllWebDataURI) {
4281                continue;
4282            }
4283            String packageName = riTargetUser.activityInfo.packageName;
4284            PackageSetting ps = mSettings.mPackages.get(packageName);
4285            if (ps == null) {
4286                continue;
4287            }
4288            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4289            if (result == null) {
4290                result = new CrossProfileDomainInfo();
4291                result.resolveInfo =
4292                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4293                result.bestDomainVerificationStatus = status;
4294            } else {
4295                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4296                        result.bestDomainVerificationStatus);
4297            }
4298        }
4299        return result;
4300    }
4301
4302    /**
4303     * Verification statuses are ordered from the worse to the best, except for
4304     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4305     */
4306    private int bestDomainVerificationStatus(int status1, int status2) {
4307        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4308            return status2;
4309        }
4310        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4311            return status1;
4312        }
4313        return (int) MathUtils.max(status1, status2);
4314    }
4315
4316    private boolean isUserEnabled(int userId) {
4317        long callingId = Binder.clearCallingIdentity();
4318        try {
4319            UserInfo userInfo = sUserManager.getUserInfo(userId);
4320            return userInfo != null && userInfo.isEnabled();
4321        } finally {
4322            Binder.restoreCallingIdentity(callingId);
4323        }
4324    }
4325
4326    /**
4327     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4328     *
4329     * @return filtered list
4330     */
4331    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4332        if (userId == UserHandle.USER_OWNER) {
4333            return resolveInfos;
4334        }
4335        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4336            ResolveInfo info = resolveInfos.get(i);
4337            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4338                resolveInfos.remove(i);
4339            }
4340        }
4341        return resolveInfos;
4342    }
4343
4344    private static boolean hasWebURI(Intent intent) {
4345        if (intent.getData() == null) {
4346            return false;
4347        }
4348        final String scheme = intent.getScheme();
4349        if (TextUtils.isEmpty(scheme)) {
4350            return false;
4351        }
4352        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4353    }
4354
4355    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4356            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4357        if (DEBUG_PREFERRED) {
4358            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4359                    candidates.size());
4360        }
4361
4362        final int userId = UserHandle.getCallingUserId();
4363        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4364        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4365        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4366        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4367        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4368
4369        synchronized (mPackages) {
4370            final int count = candidates.size();
4371            // First, try to use the domain prefered App. Partition the candidates into four lists:
4372            // one for the final results, one for the "do not use ever", one for "undefined status"
4373            // and finally one for "Browser App type".
4374            for (int n=0; n<count; n++) {
4375                ResolveInfo info = candidates.get(n);
4376                String packageName = info.activityInfo.packageName;
4377                PackageSetting ps = mSettings.mPackages.get(packageName);
4378                if (ps != null) {
4379                    // Add to the special match all list (Browser use case)
4380                    if (info.handleAllWebDataURI) {
4381                        matchAllList.add(info);
4382                        continue;
4383                    }
4384                    // Try to get the status from User settings first
4385                    int status = getDomainVerificationStatusLPr(ps, userId);
4386                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4387                        alwaysList.add(info);
4388                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4389                        neverList.add(info);
4390                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4391                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4392                        undefinedList.add(info);
4393                    }
4394                }
4395            }
4396            // First try to add the "always" resolution for the current user if there is any
4397            if (alwaysList.size() > 0) {
4398                result.addAll(alwaysList);
4399            // if there is an "always" for the parent user, add it.
4400            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4401                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4402                result.add(xpDomainInfo.resolveInfo);
4403            } else {
4404                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4405                result.addAll(undefinedList);
4406                if (xpDomainInfo != null && (
4407                        xpDomainInfo.bestDomainVerificationStatus
4408                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4409                        || xpDomainInfo.bestDomainVerificationStatus
4410                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4411                    result.add(xpDomainInfo.resolveInfo);
4412                }
4413                // Also add Browsers (all of them or only the default one)
4414                if ((flags & MATCH_ALL) != 0) {
4415                    result.addAll(matchAllList);
4416                } else {
4417                    // Try to add the Default Browser if we can
4418                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4419                            UserHandle.myUserId());
4420                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4421                        boolean defaultBrowserFound = false;
4422                        final int browserCount = matchAllList.size();
4423                        for (int n=0; n<browserCount; n++) {
4424                            ResolveInfo browser = matchAllList.get(n);
4425                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4426                                result.add(browser);
4427                                defaultBrowserFound = true;
4428                                break;
4429                            }
4430                        }
4431                        if (!defaultBrowserFound) {
4432                            result.addAll(matchAllList);
4433                        }
4434                    } else {
4435                        result.addAll(matchAllList);
4436                    }
4437                }
4438
4439                // If there is nothing selected, add all candidates and remove the ones that the User
4440                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4441                if (result.size() == 0) {
4442                    result.addAll(candidates);
4443                    result.removeAll(neverList);
4444                }
4445            }
4446        }
4447        if (DEBUG_PREFERRED) {
4448            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4449                    result.size());
4450        }
4451        return result;
4452    }
4453
4454    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4455        int status = ps.getDomainVerificationStatusForUser(userId);
4456        // if none available, get the master status
4457        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4458            if (ps.getIntentFilterVerificationInfo() != null) {
4459                status = ps.getIntentFilterVerificationInfo().getStatus();
4460            }
4461        }
4462        return status;
4463    }
4464
4465    private ResolveInfo querySkipCurrentProfileIntents(
4466            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4467            int flags, int sourceUserId) {
4468        if (matchingFilters != null) {
4469            int size = matchingFilters.size();
4470            for (int i = 0; i < size; i ++) {
4471                CrossProfileIntentFilter filter = matchingFilters.get(i);
4472                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4473                    // Checking if there are activities in the target user that can handle the
4474                    // intent.
4475                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4476                            flags, sourceUserId);
4477                    if (resolveInfo != null) {
4478                        return resolveInfo;
4479                    }
4480                }
4481            }
4482        }
4483        return null;
4484    }
4485
4486    // Return matching ResolveInfo if any for skip current profile intent filters.
4487    private ResolveInfo queryCrossProfileIntents(
4488            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4489            int flags, int sourceUserId) {
4490        if (matchingFilters != null) {
4491            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4492            // match the same intent. For performance reasons, it is better not to
4493            // run queryIntent twice for the same userId
4494            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4495            int size = matchingFilters.size();
4496            for (int i = 0; i < size; i++) {
4497                CrossProfileIntentFilter filter = matchingFilters.get(i);
4498                int targetUserId = filter.getTargetUserId();
4499                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4500                        && !alreadyTriedUserIds.get(targetUserId)) {
4501                    // Checking if there are activities in the target user that can handle the
4502                    // intent.
4503                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4504                            flags, sourceUserId);
4505                    if (resolveInfo != null) return resolveInfo;
4506                    alreadyTriedUserIds.put(targetUserId, true);
4507                }
4508            }
4509        }
4510        return null;
4511    }
4512
4513    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4514            String resolvedType, int flags, int sourceUserId) {
4515        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4516                resolvedType, flags, filter.getTargetUserId());
4517        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4518            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4519        }
4520        return null;
4521    }
4522
4523    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4524            int sourceUserId, int targetUserId) {
4525        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4526        String className;
4527        if (targetUserId == UserHandle.USER_OWNER) {
4528            className = FORWARD_INTENT_TO_USER_OWNER;
4529        } else {
4530            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4531        }
4532        ComponentName forwardingActivityComponentName = new ComponentName(
4533                mAndroidApplication.packageName, className);
4534        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4535                sourceUserId);
4536        if (targetUserId == UserHandle.USER_OWNER) {
4537            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4538            forwardingResolveInfo.noResourceId = true;
4539        }
4540        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4541        forwardingResolveInfo.priority = 0;
4542        forwardingResolveInfo.preferredOrder = 0;
4543        forwardingResolveInfo.match = 0;
4544        forwardingResolveInfo.isDefault = true;
4545        forwardingResolveInfo.filter = filter;
4546        forwardingResolveInfo.targetUserId = targetUserId;
4547        return forwardingResolveInfo;
4548    }
4549
4550    @Override
4551    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4552            Intent[] specifics, String[] specificTypes, Intent intent,
4553            String resolvedType, int flags, int userId) {
4554        if (!sUserManager.exists(userId)) return Collections.emptyList();
4555        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4556                false, "query intent activity options");
4557        final String resultsAction = intent.getAction();
4558
4559        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4560                | PackageManager.GET_RESOLVED_FILTER, userId);
4561
4562        if (DEBUG_INTENT_MATCHING) {
4563            Log.v(TAG, "Query " + intent + ": " + results);
4564        }
4565
4566        int specificsPos = 0;
4567        int N;
4568
4569        // todo: note that the algorithm used here is O(N^2).  This
4570        // isn't a problem in our current environment, but if we start running
4571        // into situations where we have more than 5 or 10 matches then this
4572        // should probably be changed to something smarter...
4573
4574        // First we go through and resolve each of the specific items
4575        // that were supplied, taking care of removing any corresponding
4576        // duplicate items in the generic resolve list.
4577        if (specifics != null) {
4578            for (int i=0; i<specifics.length; i++) {
4579                final Intent sintent = specifics[i];
4580                if (sintent == null) {
4581                    continue;
4582                }
4583
4584                if (DEBUG_INTENT_MATCHING) {
4585                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4586                }
4587
4588                String action = sintent.getAction();
4589                if (resultsAction != null && resultsAction.equals(action)) {
4590                    // If this action was explicitly requested, then don't
4591                    // remove things that have it.
4592                    action = null;
4593                }
4594
4595                ResolveInfo ri = null;
4596                ActivityInfo ai = null;
4597
4598                ComponentName comp = sintent.getComponent();
4599                if (comp == null) {
4600                    ri = resolveIntent(
4601                        sintent,
4602                        specificTypes != null ? specificTypes[i] : null,
4603                            flags, userId);
4604                    if (ri == null) {
4605                        continue;
4606                    }
4607                    if (ri == mResolveInfo) {
4608                        // ACK!  Must do something better with this.
4609                    }
4610                    ai = ri.activityInfo;
4611                    comp = new ComponentName(ai.applicationInfo.packageName,
4612                            ai.name);
4613                } else {
4614                    ai = getActivityInfo(comp, flags, userId);
4615                    if (ai == null) {
4616                        continue;
4617                    }
4618                }
4619
4620                // Look for any generic query activities that are duplicates
4621                // of this specific one, and remove them from the results.
4622                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4623                N = results.size();
4624                int j;
4625                for (j=specificsPos; j<N; j++) {
4626                    ResolveInfo sri = results.get(j);
4627                    if ((sri.activityInfo.name.equals(comp.getClassName())
4628                            && sri.activityInfo.applicationInfo.packageName.equals(
4629                                    comp.getPackageName()))
4630                        || (action != null && sri.filter.matchAction(action))) {
4631                        results.remove(j);
4632                        if (DEBUG_INTENT_MATCHING) Log.v(
4633                            TAG, "Removing duplicate item from " + j
4634                            + " due to specific " + specificsPos);
4635                        if (ri == null) {
4636                            ri = sri;
4637                        }
4638                        j--;
4639                        N--;
4640                    }
4641                }
4642
4643                // Add this specific item to its proper place.
4644                if (ri == null) {
4645                    ri = new ResolveInfo();
4646                    ri.activityInfo = ai;
4647                }
4648                results.add(specificsPos, ri);
4649                ri.specificIndex = i;
4650                specificsPos++;
4651            }
4652        }
4653
4654        // Now we go through the remaining generic results and remove any
4655        // duplicate actions that are found here.
4656        N = results.size();
4657        for (int i=specificsPos; i<N-1; i++) {
4658            final ResolveInfo rii = results.get(i);
4659            if (rii.filter == null) {
4660                continue;
4661            }
4662
4663            // Iterate over all of the actions of this result's intent
4664            // filter...  typically this should be just one.
4665            final Iterator<String> it = rii.filter.actionsIterator();
4666            if (it == null) {
4667                continue;
4668            }
4669            while (it.hasNext()) {
4670                final String action = it.next();
4671                if (resultsAction != null && resultsAction.equals(action)) {
4672                    // If this action was explicitly requested, then don't
4673                    // remove things that have it.
4674                    continue;
4675                }
4676                for (int j=i+1; j<N; j++) {
4677                    final ResolveInfo rij = results.get(j);
4678                    if (rij.filter != null && rij.filter.hasAction(action)) {
4679                        results.remove(j);
4680                        if (DEBUG_INTENT_MATCHING) Log.v(
4681                            TAG, "Removing duplicate item from " + j
4682                            + " due to action " + action + " at " + i);
4683                        j--;
4684                        N--;
4685                    }
4686                }
4687            }
4688
4689            // If the caller didn't request filter information, drop it now
4690            // so we don't have to marshall/unmarshall it.
4691            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4692                rii.filter = null;
4693            }
4694        }
4695
4696        // Filter out the caller activity if so requested.
4697        if (caller != null) {
4698            N = results.size();
4699            for (int i=0; i<N; i++) {
4700                ActivityInfo ainfo = results.get(i).activityInfo;
4701                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4702                        && caller.getClassName().equals(ainfo.name)) {
4703                    results.remove(i);
4704                    break;
4705                }
4706            }
4707        }
4708
4709        // If the caller didn't request filter information,
4710        // drop them now so we don't have to
4711        // marshall/unmarshall it.
4712        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4713            N = results.size();
4714            for (int i=0; i<N; i++) {
4715                results.get(i).filter = null;
4716            }
4717        }
4718
4719        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4720        return results;
4721    }
4722
4723    @Override
4724    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4725            int userId) {
4726        if (!sUserManager.exists(userId)) return Collections.emptyList();
4727        ComponentName comp = intent.getComponent();
4728        if (comp == null) {
4729            if (intent.getSelector() != null) {
4730                intent = intent.getSelector();
4731                comp = intent.getComponent();
4732            }
4733        }
4734        if (comp != null) {
4735            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4736            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4737            if (ai != null) {
4738                ResolveInfo ri = new ResolveInfo();
4739                ri.activityInfo = ai;
4740                list.add(ri);
4741            }
4742            return list;
4743        }
4744
4745        // reader
4746        synchronized (mPackages) {
4747            String pkgName = intent.getPackage();
4748            if (pkgName == null) {
4749                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4750            }
4751            final PackageParser.Package pkg = mPackages.get(pkgName);
4752            if (pkg != null) {
4753                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4754                        userId);
4755            }
4756            return null;
4757        }
4758    }
4759
4760    @Override
4761    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4762        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4763        if (!sUserManager.exists(userId)) return null;
4764        if (query != null) {
4765            if (query.size() >= 1) {
4766                // If there is more than one service with the same priority,
4767                // just arbitrarily pick the first one.
4768                return query.get(0);
4769            }
4770        }
4771        return null;
4772    }
4773
4774    @Override
4775    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4776            int userId) {
4777        if (!sUserManager.exists(userId)) return Collections.emptyList();
4778        ComponentName comp = intent.getComponent();
4779        if (comp == null) {
4780            if (intent.getSelector() != null) {
4781                intent = intent.getSelector();
4782                comp = intent.getComponent();
4783            }
4784        }
4785        if (comp != null) {
4786            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4787            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4788            if (si != null) {
4789                final ResolveInfo ri = new ResolveInfo();
4790                ri.serviceInfo = si;
4791                list.add(ri);
4792            }
4793            return list;
4794        }
4795
4796        // reader
4797        synchronized (mPackages) {
4798            String pkgName = intent.getPackage();
4799            if (pkgName == null) {
4800                return mServices.queryIntent(intent, resolvedType, flags, userId);
4801            }
4802            final PackageParser.Package pkg = mPackages.get(pkgName);
4803            if (pkg != null) {
4804                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4805                        userId);
4806            }
4807            return null;
4808        }
4809    }
4810
4811    @Override
4812    public List<ResolveInfo> queryIntentContentProviders(
4813            Intent intent, String resolvedType, int flags, int userId) {
4814        if (!sUserManager.exists(userId)) return Collections.emptyList();
4815        ComponentName comp = intent.getComponent();
4816        if (comp == null) {
4817            if (intent.getSelector() != null) {
4818                intent = intent.getSelector();
4819                comp = intent.getComponent();
4820            }
4821        }
4822        if (comp != null) {
4823            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4824            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4825            if (pi != null) {
4826                final ResolveInfo ri = new ResolveInfo();
4827                ri.providerInfo = pi;
4828                list.add(ri);
4829            }
4830            return list;
4831        }
4832
4833        // reader
4834        synchronized (mPackages) {
4835            String pkgName = intent.getPackage();
4836            if (pkgName == null) {
4837                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4838            }
4839            final PackageParser.Package pkg = mPackages.get(pkgName);
4840            if (pkg != null) {
4841                return mProviders.queryIntentForPackage(
4842                        intent, resolvedType, flags, pkg.providers, userId);
4843            }
4844            return null;
4845        }
4846    }
4847
4848    @Override
4849    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4850        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4851
4852        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4853
4854        // writer
4855        synchronized (mPackages) {
4856            ArrayList<PackageInfo> list;
4857            if (listUninstalled) {
4858                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4859                for (PackageSetting ps : mSettings.mPackages.values()) {
4860                    PackageInfo pi;
4861                    if (ps.pkg != null) {
4862                        pi = generatePackageInfo(ps.pkg, flags, userId);
4863                    } else {
4864                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4865                    }
4866                    if (pi != null) {
4867                        list.add(pi);
4868                    }
4869                }
4870            } else {
4871                list = new ArrayList<PackageInfo>(mPackages.size());
4872                for (PackageParser.Package p : mPackages.values()) {
4873                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4874                    if (pi != null) {
4875                        list.add(pi);
4876                    }
4877                }
4878            }
4879
4880            return new ParceledListSlice<PackageInfo>(list);
4881        }
4882    }
4883
4884    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4885            String[] permissions, boolean[] tmp, int flags, int userId) {
4886        int numMatch = 0;
4887        final PermissionsState permissionsState = ps.getPermissionsState();
4888        for (int i=0; i<permissions.length; i++) {
4889            final String permission = permissions[i];
4890            if (permissionsState.hasPermission(permission, userId)) {
4891                tmp[i] = true;
4892                numMatch++;
4893            } else {
4894                tmp[i] = false;
4895            }
4896        }
4897        if (numMatch == 0) {
4898            return;
4899        }
4900        PackageInfo pi;
4901        if (ps.pkg != null) {
4902            pi = generatePackageInfo(ps.pkg, flags, userId);
4903        } else {
4904            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4905        }
4906        // The above might return null in cases of uninstalled apps or install-state
4907        // skew across users/profiles.
4908        if (pi != null) {
4909            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4910                if (numMatch == permissions.length) {
4911                    pi.requestedPermissions = permissions;
4912                } else {
4913                    pi.requestedPermissions = new String[numMatch];
4914                    numMatch = 0;
4915                    for (int i=0; i<permissions.length; i++) {
4916                        if (tmp[i]) {
4917                            pi.requestedPermissions[numMatch] = permissions[i];
4918                            numMatch++;
4919                        }
4920                    }
4921                }
4922            }
4923            list.add(pi);
4924        }
4925    }
4926
4927    @Override
4928    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4929            String[] permissions, int flags, int userId) {
4930        if (!sUserManager.exists(userId)) return null;
4931        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4932
4933        // writer
4934        synchronized (mPackages) {
4935            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4936            boolean[] tmpBools = new boolean[permissions.length];
4937            if (listUninstalled) {
4938                for (PackageSetting ps : mSettings.mPackages.values()) {
4939                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4940                }
4941            } else {
4942                for (PackageParser.Package pkg : mPackages.values()) {
4943                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4944                    if (ps != null) {
4945                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4946                                userId);
4947                    }
4948                }
4949            }
4950
4951            return new ParceledListSlice<PackageInfo>(list);
4952        }
4953    }
4954
4955    @Override
4956    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4957        if (!sUserManager.exists(userId)) return null;
4958        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4959
4960        // writer
4961        synchronized (mPackages) {
4962            ArrayList<ApplicationInfo> list;
4963            if (listUninstalled) {
4964                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4965                for (PackageSetting ps : mSettings.mPackages.values()) {
4966                    ApplicationInfo ai;
4967                    if (ps.pkg != null) {
4968                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4969                                ps.readUserState(userId), userId);
4970                    } else {
4971                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4972                    }
4973                    if (ai != null) {
4974                        list.add(ai);
4975                    }
4976                }
4977            } else {
4978                list = new ArrayList<ApplicationInfo>(mPackages.size());
4979                for (PackageParser.Package p : mPackages.values()) {
4980                    if (p.mExtras != null) {
4981                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4982                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4983                        if (ai != null) {
4984                            list.add(ai);
4985                        }
4986                    }
4987                }
4988            }
4989
4990            return new ParceledListSlice<ApplicationInfo>(list);
4991        }
4992    }
4993
4994    public List<ApplicationInfo> getPersistentApplications(int flags) {
4995        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4996
4997        // reader
4998        synchronized (mPackages) {
4999            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5000            final int userId = UserHandle.getCallingUserId();
5001            while (i.hasNext()) {
5002                final PackageParser.Package p = i.next();
5003                if (p.applicationInfo != null
5004                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5005                        && (!mSafeMode || isSystemApp(p))) {
5006                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5007                    if (ps != null) {
5008                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5009                                ps.readUserState(userId), userId);
5010                        if (ai != null) {
5011                            finalList.add(ai);
5012                        }
5013                    }
5014                }
5015            }
5016        }
5017
5018        return finalList;
5019    }
5020
5021    @Override
5022    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5023        if (!sUserManager.exists(userId)) return null;
5024        // reader
5025        synchronized (mPackages) {
5026            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5027            PackageSetting ps = provider != null
5028                    ? mSettings.mPackages.get(provider.owner.packageName)
5029                    : null;
5030            return ps != null
5031                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5032                    && (!mSafeMode || (provider.info.applicationInfo.flags
5033                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5034                    ? PackageParser.generateProviderInfo(provider, flags,
5035                            ps.readUserState(userId), userId)
5036                    : null;
5037        }
5038    }
5039
5040    /**
5041     * @deprecated
5042     */
5043    @Deprecated
5044    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5045        // reader
5046        synchronized (mPackages) {
5047            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5048                    .entrySet().iterator();
5049            final int userId = UserHandle.getCallingUserId();
5050            while (i.hasNext()) {
5051                Map.Entry<String, PackageParser.Provider> entry = i.next();
5052                PackageParser.Provider p = entry.getValue();
5053                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5054
5055                if (ps != null && p.syncable
5056                        && (!mSafeMode || (p.info.applicationInfo.flags
5057                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5058                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5059                            ps.readUserState(userId), userId);
5060                    if (info != null) {
5061                        outNames.add(entry.getKey());
5062                        outInfo.add(info);
5063                    }
5064                }
5065            }
5066        }
5067    }
5068
5069    @Override
5070    public List<ProviderInfo> queryContentProviders(String processName,
5071            int uid, int flags) {
5072        ArrayList<ProviderInfo> finalList = null;
5073        // reader
5074        synchronized (mPackages) {
5075            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5076            final int userId = processName != null ?
5077                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5078            while (i.hasNext()) {
5079                final PackageParser.Provider p = i.next();
5080                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5081                if (ps != null && p.info.authority != null
5082                        && (processName == null
5083                                || (p.info.processName.equals(processName)
5084                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5085                        && mSettings.isEnabledLPr(p.info, flags, userId)
5086                        && (!mSafeMode
5087                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5088                    if (finalList == null) {
5089                        finalList = new ArrayList<ProviderInfo>(3);
5090                    }
5091                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5092                            ps.readUserState(userId), userId);
5093                    if (info != null) {
5094                        finalList.add(info);
5095                    }
5096                }
5097            }
5098        }
5099
5100        if (finalList != null) {
5101            Collections.sort(finalList, mProviderInitOrderSorter);
5102        }
5103
5104        return finalList;
5105    }
5106
5107    @Override
5108    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5109            int flags) {
5110        // reader
5111        synchronized (mPackages) {
5112            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5113            return PackageParser.generateInstrumentationInfo(i, flags);
5114        }
5115    }
5116
5117    @Override
5118    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5119            int flags) {
5120        ArrayList<InstrumentationInfo> finalList =
5121            new ArrayList<InstrumentationInfo>();
5122
5123        // reader
5124        synchronized (mPackages) {
5125            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5126            while (i.hasNext()) {
5127                final PackageParser.Instrumentation p = i.next();
5128                if (targetPackage == null
5129                        || targetPackage.equals(p.info.targetPackage)) {
5130                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5131                            flags);
5132                    if (ii != null) {
5133                        finalList.add(ii);
5134                    }
5135                }
5136            }
5137        }
5138
5139        return finalList;
5140    }
5141
5142    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5143        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5144        if (overlays == null) {
5145            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5146            return;
5147        }
5148        for (PackageParser.Package opkg : overlays.values()) {
5149            // Not much to do if idmap fails: we already logged the error
5150            // and we certainly don't want to abort installation of pkg simply
5151            // because an overlay didn't fit properly. For these reasons,
5152            // ignore the return value of createIdmapForPackagePairLI.
5153            createIdmapForPackagePairLI(pkg, opkg);
5154        }
5155    }
5156
5157    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5158            PackageParser.Package opkg) {
5159        if (!opkg.mTrustedOverlay) {
5160            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5161                    opkg.baseCodePath + ": overlay not trusted");
5162            return false;
5163        }
5164        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5165        if (overlaySet == null) {
5166            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5167                    opkg.baseCodePath + " but target package has no known overlays");
5168            return false;
5169        }
5170        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5171        // TODO: generate idmap for split APKs
5172        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5173            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5174                    + opkg.baseCodePath);
5175            return false;
5176        }
5177        PackageParser.Package[] overlayArray =
5178            overlaySet.values().toArray(new PackageParser.Package[0]);
5179        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5180            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5181                return p1.mOverlayPriority - p2.mOverlayPriority;
5182            }
5183        };
5184        Arrays.sort(overlayArray, cmp);
5185
5186        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5187        int i = 0;
5188        for (PackageParser.Package p : overlayArray) {
5189            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5190        }
5191        return true;
5192    }
5193
5194    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5195        final File[] files = dir.listFiles();
5196        if (ArrayUtils.isEmpty(files)) {
5197            Log.d(TAG, "No files in app dir " + dir);
5198            return;
5199        }
5200
5201        if (DEBUG_PACKAGE_SCANNING) {
5202            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5203                    + " flags=0x" + Integer.toHexString(parseFlags));
5204        }
5205
5206        for (File file : files) {
5207            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5208                    && !PackageInstallerService.isStageName(file.getName());
5209            if (!isPackage) {
5210                // Ignore entries which are not packages
5211                continue;
5212            }
5213            try {
5214                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5215                        scanFlags, currentTime, null);
5216            } catch (PackageManagerException e) {
5217                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5218
5219                // Delete invalid userdata apps
5220                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5221                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5222                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5223                    if (file.isDirectory()) {
5224                        mInstaller.rmPackageDir(file.getAbsolutePath());
5225                    } else {
5226                        file.delete();
5227                    }
5228                }
5229            }
5230        }
5231    }
5232
5233    private static File getSettingsProblemFile() {
5234        File dataDir = Environment.getDataDirectory();
5235        File systemDir = new File(dataDir, "system");
5236        File fname = new File(systemDir, "uiderrors.txt");
5237        return fname;
5238    }
5239
5240    static void reportSettingsProblem(int priority, String msg) {
5241        logCriticalInfo(priority, msg);
5242    }
5243
5244    static void logCriticalInfo(int priority, String msg) {
5245        Slog.println(priority, TAG, msg);
5246        EventLogTags.writePmCriticalInfo(msg);
5247        try {
5248            File fname = getSettingsProblemFile();
5249            FileOutputStream out = new FileOutputStream(fname, true);
5250            PrintWriter pw = new FastPrintWriter(out);
5251            SimpleDateFormat formatter = new SimpleDateFormat();
5252            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5253            pw.println(dateString + ": " + msg);
5254            pw.close();
5255            FileUtils.setPermissions(
5256                    fname.toString(),
5257                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5258                    -1, -1);
5259        } catch (java.io.IOException e) {
5260        }
5261    }
5262
5263    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5264            PackageParser.Package pkg, File srcFile, int parseFlags)
5265            throws PackageManagerException {
5266        if (ps != null
5267                && ps.codePath.equals(srcFile)
5268                && ps.timeStamp == srcFile.lastModified()
5269                && !isCompatSignatureUpdateNeeded(pkg)
5270                && !isRecoverSignatureUpdateNeeded(pkg)) {
5271            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5272            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5273            ArraySet<PublicKey> signingKs;
5274            synchronized (mPackages) {
5275                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5276            }
5277            if (ps.signatures.mSignatures != null
5278                    && ps.signatures.mSignatures.length != 0
5279                    && signingKs != null) {
5280                // Optimization: reuse the existing cached certificates
5281                // if the package appears to be unchanged.
5282                pkg.mSignatures = ps.signatures.mSignatures;
5283                pkg.mSigningKeys = signingKs;
5284                return;
5285            }
5286
5287            Slog.w(TAG, "PackageSetting for " + ps.name
5288                    + " is missing signatures.  Collecting certs again to recover them.");
5289        } else {
5290            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5291        }
5292
5293        try {
5294            pp.collectCertificates(pkg, parseFlags);
5295            pp.collectManifestDigest(pkg);
5296        } catch (PackageParserException e) {
5297            throw PackageManagerException.from(e);
5298        }
5299    }
5300
5301    /*
5302     *  Scan a package and return the newly parsed package.
5303     *  Returns null in case of errors and the error code is stored in mLastScanError
5304     */
5305    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5306            long currentTime, UserHandle user) throws PackageManagerException {
5307        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5308        parseFlags |= mDefParseFlags;
5309        PackageParser pp = new PackageParser();
5310        pp.setSeparateProcesses(mSeparateProcesses);
5311        pp.setOnlyCoreApps(mOnlyCore);
5312        pp.setDisplayMetrics(mMetrics);
5313
5314        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5315            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5316        }
5317
5318        final PackageParser.Package pkg;
5319        try {
5320            pkg = pp.parsePackage(scanFile, parseFlags);
5321        } catch (PackageParserException e) {
5322            throw PackageManagerException.from(e);
5323        }
5324
5325        PackageSetting ps = null;
5326        PackageSetting updatedPkg;
5327        // reader
5328        synchronized (mPackages) {
5329            // Look to see if we already know about this package.
5330            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5331            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5332                // This package has been renamed to its original name.  Let's
5333                // use that.
5334                ps = mSettings.peekPackageLPr(oldName);
5335            }
5336            // If there was no original package, see one for the real package name.
5337            if (ps == null) {
5338                ps = mSettings.peekPackageLPr(pkg.packageName);
5339            }
5340            // Check to see if this package could be hiding/updating a system
5341            // package.  Must look for it either under the original or real
5342            // package name depending on our state.
5343            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5344            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5345        }
5346        boolean updatedPkgBetter = false;
5347        // First check if this is a system package that may involve an update
5348        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5349            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5350            // it needs to drop FLAG_PRIVILEGED.
5351            if (locationIsPrivileged(scanFile)) {
5352                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5353            } else {
5354                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5355            }
5356
5357            if (ps != null && !ps.codePath.equals(scanFile)) {
5358                // The path has changed from what was last scanned...  check the
5359                // version of the new path against what we have stored to determine
5360                // what to do.
5361                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5362                if (pkg.mVersionCode <= ps.versionCode) {
5363                    // The system package has been updated and the code path does not match
5364                    // Ignore entry. Skip it.
5365                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5366                            + " ignored: updated version " + ps.versionCode
5367                            + " better than this " + pkg.mVersionCode);
5368                    if (!updatedPkg.codePath.equals(scanFile)) {
5369                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5370                                + ps.name + " changing from " + updatedPkg.codePathString
5371                                + " to " + scanFile);
5372                        updatedPkg.codePath = scanFile;
5373                        updatedPkg.codePathString = scanFile.toString();
5374                        updatedPkg.resourcePath = scanFile;
5375                        updatedPkg.resourcePathString = scanFile.toString();
5376                    }
5377                    updatedPkg.pkg = pkg;
5378                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5379                } else {
5380                    // The current app on the system partition is better than
5381                    // what we have updated to on the data partition; switch
5382                    // back to the system partition version.
5383                    // At this point, its safely assumed that package installation for
5384                    // apps in system partition will go through. If not there won't be a working
5385                    // version of the app
5386                    // writer
5387                    synchronized (mPackages) {
5388                        // Just remove the loaded entries from package lists.
5389                        mPackages.remove(ps.name);
5390                    }
5391
5392                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5393                            + " reverting from " + ps.codePathString
5394                            + ": new version " + pkg.mVersionCode
5395                            + " better than installed " + ps.versionCode);
5396
5397                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5398                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5399                    synchronized (mInstallLock) {
5400                        args.cleanUpResourcesLI();
5401                    }
5402                    synchronized (mPackages) {
5403                        mSettings.enableSystemPackageLPw(ps.name);
5404                    }
5405                    updatedPkgBetter = true;
5406                }
5407            }
5408        }
5409
5410        if (updatedPkg != null) {
5411            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5412            // initially
5413            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5414
5415            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5416            // flag set initially
5417            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5418                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5419            }
5420        }
5421
5422        // Verify certificates against what was last scanned
5423        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5424
5425        /*
5426         * A new system app appeared, but we already had a non-system one of the
5427         * same name installed earlier.
5428         */
5429        boolean shouldHideSystemApp = false;
5430        if (updatedPkg == null && ps != null
5431                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5432            /*
5433             * Check to make sure the signatures match first. If they don't,
5434             * wipe the installed application and its data.
5435             */
5436            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5437                    != PackageManager.SIGNATURE_MATCH) {
5438                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5439                        + " signatures don't match existing userdata copy; removing");
5440                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5441                ps = null;
5442            } else {
5443                /*
5444                 * If the newly-added system app is an older version than the
5445                 * already installed version, hide it. It will be scanned later
5446                 * and re-added like an update.
5447                 */
5448                if (pkg.mVersionCode <= ps.versionCode) {
5449                    shouldHideSystemApp = true;
5450                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5451                            + " but new version " + pkg.mVersionCode + " better than installed "
5452                            + ps.versionCode + "; hiding system");
5453                } else {
5454                    /*
5455                     * The newly found system app is a newer version that the
5456                     * one previously installed. Simply remove the
5457                     * already-installed application and replace it with our own
5458                     * while keeping the application data.
5459                     */
5460                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5461                            + " reverting from " + ps.codePathString + ": new version "
5462                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5463                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5464                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5465                    synchronized (mInstallLock) {
5466                        args.cleanUpResourcesLI();
5467                    }
5468                }
5469            }
5470        }
5471
5472        // The apk is forward locked (not public) if its code and resources
5473        // are kept in different files. (except for app in either system or
5474        // vendor path).
5475        // TODO grab this value from PackageSettings
5476        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5477            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5478                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5479            }
5480        }
5481
5482        // TODO: extend to support forward-locked splits
5483        String resourcePath = null;
5484        String baseResourcePath = null;
5485        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5486            if (ps != null && ps.resourcePathString != null) {
5487                resourcePath = ps.resourcePathString;
5488                baseResourcePath = ps.resourcePathString;
5489            } else {
5490                // Should not happen at all. Just log an error.
5491                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5492            }
5493        } else {
5494            resourcePath = pkg.codePath;
5495            baseResourcePath = pkg.baseCodePath;
5496        }
5497
5498        // Set application objects path explicitly.
5499        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5500        pkg.applicationInfo.setCodePath(pkg.codePath);
5501        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5502        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5503        pkg.applicationInfo.setResourcePath(resourcePath);
5504        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5505        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5506
5507        // Note that we invoke the following method only if we are about to unpack an application
5508        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5509                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5510
5511        /*
5512         * If the system app should be overridden by a previously installed
5513         * data, hide the system app now and let the /data/app scan pick it up
5514         * again.
5515         */
5516        if (shouldHideSystemApp) {
5517            synchronized (mPackages) {
5518                /*
5519                 * We have to grant systems permissions before we hide, because
5520                 * grantPermissions will assume the package update is trying to
5521                 * expand its permissions.
5522                 */
5523                grantPermissionsLPw(pkg, true, pkg.packageName);
5524                mSettings.disableSystemPackageLPw(pkg.packageName);
5525            }
5526        }
5527
5528        return scannedPkg;
5529    }
5530
5531    private static String fixProcessName(String defProcessName,
5532            String processName, int uid) {
5533        if (processName == null) {
5534            return defProcessName;
5535        }
5536        return processName;
5537    }
5538
5539    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5540            throws PackageManagerException {
5541        if (pkgSetting.signatures.mSignatures != null) {
5542            // Already existing package. Make sure signatures match
5543            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5544                    == PackageManager.SIGNATURE_MATCH;
5545            if (!match) {
5546                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5547                        == PackageManager.SIGNATURE_MATCH;
5548            }
5549            if (!match) {
5550                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5551                        == PackageManager.SIGNATURE_MATCH;
5552            }
5553            if (!match) {
5554                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5555                        + pkg.packageName + " signatures do not match the "
5556                        + "previously installed version; ignoring!");
5557            }
5558        }
5559
5560        // Check for shared user signatures
5561        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5562            // Already existing package. Make sure signatures match
5563            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5564                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5565            if (!match) {
5566                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5567                        == PackageManager.SIGNATURE_MATCH;
5568            }
5569            if (!match) {
5570                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5571                        == PackageManager.SIGNATURE_MATCH;
5572            }
5573            if (!match) {
5574                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5575                        "Package " + pkg.packageName
5576                        + " has no signatures that match those in shared user "
5577                        + pkgSetting.sharedUser.name + "; ignoring!");
5578            }
5579        }
5580    }
5581
5582    /**
5583     * Enforces that only the system UID or root's UID can call a method exposed
5584     * via Binder.
5585     *
5586     * @param message used as message if SecurityException is thrown
5587     * @throws SecurityException if the caller is not system or root
5588     */
5589    private static final void enforceSystemOrRoot(String message) {
5590        final int uid = Binder.getCallingUid();
5591        if (uid != Process.SYSTEM_UID && uid != 0) {
5592            throw new SecurityException(message);
5593        }
5594    }
5595
5596    @Override
5597    public void performBootDexOpt() {
5598        enforceSystemOrRoot("Only the system can request dexopt be performed");
5599
5600        // Before everything else, see whether we need to fstrim.
5601        try {
5602            IMountService ms = PackageHelper.getMountService();
5603            if (ms != null) {
5604                final boolean isUpgrade = isUpgrade();
5605                boolean doTrim = isUpgrade;
5606                if (doTrim) {
5607                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5608                } else {
5609                    final long interval = android.provider.Settings.Global.getLong(
5610                            mContext.getContentResolver(),
5611                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5612                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5613                    if (interval > 0) {
5614                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5615                        if (timeSinceLast > interval) {
5616                            doTrim = true;
5617                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5618                                    + "; running immediately");
5619                        }
5620                    }
5621                }
5622                if (doTrim) {
5623                    if (!isFirstBoot()) {
5624                        try {
5625                            ActivityManagerNative.getDefault().showBootMessage(
5626                                    mContext.getResources().getString(
5627                                            R.string.android_upgrading_fstrim), true);
5628                        } catch (RemoteException e) {
5629                        }
5630                    }
5631                    ms.runMaintenance();
5632                }
5633            } else {
5634                Slog.e(TAG, "Mount service unavailable!");
5635            }
5636        } catch (RemoteException e) {
5637            // Can't happen; MountService is local
5638        }
5639
5640        final ArraySet<PackageParser.Package> pkgs;
5641        synchronized (mPackages) {
5642            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5643        }
5644
5645        if (pkgs != null) {
5646            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5647            // in case the device runs out of space.
5648            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5649            // Give priority to core apps.
5650            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5651                PackageParser.Package pkg = it.next();
5652                if (pkg.coreApp) {
5653                    if (DEBUG_DEXOPT) {
5654                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5655                    }
5656                    sortedPkgs.add(pkg);
5657                    it.remove();
5658                }
5659            }
5660            // Give priority to system apps that listen for pre boot complete.
5661            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5662            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5663            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5664                PackageParser.Package pkg = it.next();
5665                if (pkgNames.contains(pkg.packageName)) {
5666                    if (DEBUG_DEXOPT) {
5667                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5668                    }
5669                    sortedPkgs.add(pkg);
5670                    it.remove();
5671                }
5672            }
5673            // Give priority to system apps.
5674            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5675                PackageParser.Package pkg = it.next();
5676                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5677                    if (DEBUG_DEXOPT) {
5678                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5679                    }
5680                    sortedPkgs.add(pkg);
5681                    it.remove();
5682                }
5683            }
5684            // Give priority to updated system apps.
5685            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5686                PackageParser.Package pkg = it.next();
5687                if (pkg.isUpdatedSystemApp()) {
5688                    if (DEBUG_DEXOPT) {
5689                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5690                    }
5691                    sortedPkgs.add(pkg);
5692                    it.remove();
5693                }
5694            }
5695            // Give priority to apps that listen for boot complete.
5696            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5697            pkgNames = getPackageNamesForIntent(intent);
5698            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5699                PackageParser.Package pkg = it.next();
5700                if (pkgNames.contains(pkg.packageName)) {
5701                    if (DEBUG_DEXOPT) {
5702                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5703                    }
5704                    sortedPkgs.add(pkg);
5705                    it.remove();
5706                }
5707            }
5708            // Filter out packages that aren't recently used.
5709            filterRecentlyUsedApps(pkgs);
5710            // Add all remaining apps.
5711            for (PackageParser.Package pkg : pkgs) {
5712                if (DEBUG_DEXOPT) {
5713                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5714                }
5715                sortedPkgs.add(pkg);
5716            }
5717
5718            // If we want to be lazy, filter everything that wasn't recently used.
5719            if (mLazyDexOpt) {
5720                filterRecentlyUsedApps(sortedPkgs);
5721            }
5722
5723            int i = 0;
5724            int total = sortedPkgs.size();
5725            File dataDir = Environment.getDataDirectory();
5726            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5727            if (lowThreshold == 0) {
5728                throw new IllegalStateException("Invalid low memory threshold");
5729            }
5730            for (PackageParser.Package pkg : sortedPkgs) {
5731                long usableSpace = dataDir.getUsableSpace();
5732                if (usableSpace < lowThreshold) {
5733                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5734                    break;
5735                }
5736                performBootDexOpt(pkg, ++i, total);
5737            }
5738        }
5739    }
5740
5741    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5742        // Filter out packages that aren't recently used.
5743        //
5744        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5745        // should do a full dexopt.
5746        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5747            int total = pkgs.size();
5748            int skipped = 0;
5749            long now = System.currentTimeMillis();
5750            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5751                PackageParser.Package pkg = i.next();
5752                long then = pkg.mLastPackageUsageTimeInMills;
5753                if (then + mDexOptLRUThresholdInMills < now) {
5754                    if (DEBUG_DEXOPT) {
5755                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5756                              ((then == 0) ? "never" : new Date(then)));
5757                    }
5758                    i.remove();
5759                    skipped++;
5760                }
5761            }
5762            if (DEBUG_DEXOPT) {
5763                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5764            }
5765        }
5766    }
5767
5768    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5769        List<ResolveInfo> ris = null;
5770        try {
5771            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5772                    intent, null, 0, UserHandle.USER_OWNER);
5773        } catch (RemoteException e) {
5774        }
5775        ArraySet<String> pkgNames = new ArraySet<String>();
5776        if (ris != null) {
5777            for (ResolveInfo ri : ris) {
5778                pkgNames.add(ri.activityInfo.packageName);
5779            }
5780        }
5781        return pkgNames;
5782    }
5783
5784    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5785        if (DEBUG_DEXOPT) {
5786            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5787        }
5788        if (!isFirstBoot()) {
5789            try {
5790                ActivityManagerNative.getDefault().showBootMessage(
5791                        mContext.getResources().getString(R.string.android_upgrading_apk,
5792                                curr, total), true);
5793            } catch (RemoteException e) {
5794            }
5795        }
5796        PackageParser.Package p = pkg;
5797        synchronized (mInstallLock) {
5798            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5799                    false /* force dex */, false /* defer */, true /* include dependencies */);
5800        }
5801    }
5802
5803    @Override
5804    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5805        return performDexOpt(packageName, instructionSet, false);
5806    }
5807
5808    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5809        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5810        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5811        if (!dexopt && !updateUsage) {
5812            // We aren't going to dexopt or update usage, so bail early.
5813            return false;
5814        }
5815        PackageParser.Package p;
5816        final String targetInstructionSet;
5817        synchronized (mPackages) {
5818            p = mPackages.get(packageName);
5819            if (p == null) {
5820                return false;
5821            }
5822            if (updateUsage) {
5823                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5824            }
5825            mPackageUsage.write(false);
5826            if (!dexopt) {
5827                // We aren't going to dexopt, so bail early.
5828                return false;
5829            }
5830
5831            targetInstructionSet = instructionSet != null ? instructionSet :
5832                    getPrimaryInstructionSet(p.applicationInfo);
5833            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5834                return false;
5835            }
5836        }
5837
5838        synchronized (mInstallLock) {
5839            final String[] instructionSets = new String[] { targetInstructionSet };
5840            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5841                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5842            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5843        }
5844    }
5845
5846    public ArraySet<String> getPackagesThatNeedDexOpt() {
5847        ArraySet<String> pkgs = null;
5848        synchronized (mPackages) {
5849            for (PackageParser.Package p : mPackages.values()) {
5850                if (DEBUG_DEXOPT) {
5851                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5852                }
5853                if (!p.mDexOptPerformed.isEmpty()) {
5854                    continue;
5855                }
5856                if (pkgs == null) {
5857                    pkgs = new ArraySet<String>();
5858                }
5859                pkgs.add(p.packageName);
5860            }
5861        }
5862        return pkgs;
5863    }
5864
5865    public void shutdown() {
5866        mPackageUsage.write(true);
5867    }
5868
5869    @Override
5870    public void forceDexOpt(String packageName) {
5871        enforceSystemOrRoot("forceDexOpt");
5872
5873        PackageParser.Package pkg;
5874        synchronized (mPackages) {
5875            pkg = mPackages.get(packageName);
5876            if (pkg == null) {
5877                throw new IllegalArgumentException("Missing package: " + packageName);
5878            }
5879        }
5880
5881        synchronized (mInstallLock) {
5882            final String[] instructionSets = new String[] {
5883                    getPrimaryInstructionSet(pkg.applicationInfo) };
5884            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5885                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5886            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5887                throw new IllegalStateException("Failed to dexopt: " + res);
5888            }
5889        }
5890    }
5891
5892    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5893        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5894            Slog.w(TAG, "Unable to update from " + oldPkg.name
5895                    + " to " + newPkg.packageName
5896                    + ": old package not in system partition");
5897            return false;
5898        } else if (mPackages.get(oldPkg.name) != null) {
5899            Slog.w(TAG, "Unable to update from " + oldPkg.name
5900                    + " to " + newPkg.packageName
5901                    + ": old package still exists");
5902            return false;
5903        }
5904        return true;
5905    }
5906
5907    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5908        int[] users = sUserManager.getUserIds();
5909        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5910        if (res < 0) {
5911            return res;
5912        }
5913        for (int user : users) {
5914            if (user != 0) {
5915                res = mInstaller.createUserData(volumeUuid, packageName,
5916                        UserHandle.getUid(user, uid), user, seinfo);
5917                if (res < 0) {
5918                    return res;
5919                }
5920            }
5921        }
5922        return res;
5923    }
5924
5925    private int removeDataDirsLI(String volumeUuid, String packageName) {
5926        int[] users = sUserManager.getUserIds();
5927        int res = 0;
5928        for (int user : users) {
5929            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5930            if (resInner < 0) {
5931                res = resInner;
5932            }
5933        }
5934
5935        return res;
5936    }
5937
5938    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5939        int[] users = sUserManager.getUserIds();
5940        int res = 0;
5941        for (int user : users) {
5942            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5943            if (resInner < 0) {
5944                res = resInner;
5945            }
5946        }
5947        return res;
5948    }
5949
5950    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5951            PackageParser.Package changingLib) {
5952        if (file.path != null) {
5953            usesLibraryFiles.add(file.path);
5954            return;
5955        }
5956        PackageParser.Package p = mPackages.get(file.apk);
5957        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5958            // If we are doing this while in the middle of updating a library apk,
5959            // then we need to make sure to use that new apk for determining the
5960            // dependencies here.  (We haven't yet finished committing the new apk
5961            // to the package manager state.)
5962            if (p == null || p.packageName.equals(changingLib.packageName)) {
5963                p = changingLib;
5964            }
5965        }
5966        if (p != null) {
5967            usesLibraryFiles.addAll(p.getAllCodePaths());
5968        }
5969    }
5970
5971    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5972            PackageParser.Package changingLib) throws PackageManagerException {
5973        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5974            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5975            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5976            for (int i=0; i<N; i++) {
5977                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5978                if (file == null) {
5979                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5980                            "Package " + pkg.packageName + " requires unavailable shared library "
5981                            + pkg.usesLibraries.get(i) + "; failing!");
5982                }
5983                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5984            }
5985            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5986            for (int i=0; i<N; i++) {
5987                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5988                if (file == null) {
5989                    Slog.w(TAG, "Package " + pkg.packageName
5990                            + " desires unavailable shared library "
5991                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5992                } else {
5993                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5994                }
5995            }
5996            N = usesLibraryFiles.size();
5997            if (N > 0) {
5998                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5999            } else {
6000                pkg.usesLibraryFiles = null;
6001            }
6002        }
6003    }
6004
6005    private static boolean hasString(List<String> list, List<String> which) {
6006        if (list == null) {
6007            return false;
6008        }
6009        for (int i=list.size()-1; i>=0; i--) {
6010            for (int j=which.size()-1; j>=0; j--) {
6011                if (which.get(j).equals(list.get(i))) {
6012                    return true;
6013                }
6014            }
6015        }
6016        return false;
6017    }
6018
6019    private void updateAllSharedLibrariesLPw() {
6020        for (PackageParser.Package pkg : mPackages.values()) {
6021            try {
6022                updateSharedLibrariesLPw(pkg, null);
6023            } catch (PackageManagerException e) {
6024                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6025            }
6026        }
6027    }
6028
6029    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6030            PackageParser.Package changingPkg) {
6031        ArrayList<PackageParser.Package> res = null;
6032        for (PackageParser.Package pkg : mPackages.values()) {
6033            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6034                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6035                if (res == null) {
6036                    res = new ArrayList<PackageParser.Package>();
6037                }
6038                res.add(pkg);
6039                try {
6040                    updateSharedLibrariesLPw(pkg, changingPkg);
6041                } catch (PackageManagerException e) {
6042                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6043                }
6044            }
6045        }
6046        return res;
6047    }
6048
6049    /**
6050     * Derive the value of the {@code cpuAbiOverride} based on the provided
6051     * value and an optional stored value from the package settings.
6052     */
6053    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6054        String cpuAbiOverride = null;
6055
6056        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6057            cpuAbiOverride = null;
6058        } else if (abiOverride != null) {
6059            cpuAbiOverride = abiOverride;
6060        } else if (settings != null) {
6061            cpuAbiOverride = settings.cpuAbiOverrideString;
6062        }
6063
6064        return cpuAbiOverride;
6065    }
6066
6067    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6068            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6069        boolean success = false;
6070        try {
6071            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6072                    currentTime, user);
6073            success = true;
6074            return res;
6075        } finally {
6076            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6077                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6078            }
6079        }
6080    }
6081
6082    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6083            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6084        final File scanFile = new File(pkg.codePath);
6085        if (pkg.applicationInfo.getCodePath() == null ||
6086                pkg.applicationInfo.getResourcePath() == null) {
6087            // Bail out. The resource and code paths haven't been set.
6088            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6089                    "Code and resource paths haven't been set correctly");
6090        }
6091
6092        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6093            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6094        } else {
6095            // Only allow system apps to be flagged as core apps.
6096            pkg.coreApp = false;
6097        }
6098
6099        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6100            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6101        }
6102
6103        if (mCustomResolverComponentName != null &&
6104                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6105            setUpCustomResolverActivity(pkg);
6106        }
6107
6108        if (pkg.packageName.equals("android")) {
6109            synchronized (mPackages) {
6110                if (mAndroidApplication != null) {
6111                    Slog.w(TAG, "*************************************************");
6112                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6113                    Slog.w(TAG, " file=" + scanFile);
6114                    Slog.w(TAG, "*************************************************");
6115                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6116                            "Core android package being redefined.  Skipping.");
6117                }
6118
6119                // Set up information for our fall-back user intent resolution activity.
6120                mPlatformPackage = pkg;
6121                pkg.mVersionCode = mSdkVersion;
6122                mAndroidApplication = pkg.applicationInfo;
6123
6124                if (!mResolverReplaced) {
6125                    mResolveActivity.applicationInfo = mAndroidApplication;
6126                    mResolveActivity.name = ResolverActivity.class.getName();
6127                    mResolveActivity.packageName = mAndroidApplication.packageName;
6128                    mResolveActivity.processName = "system:ui";
6129                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6130                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6131                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6132                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6133                    mResolveActivity.exported = true;
6134                    mResolveActivity.enabled = true;
6135                    mResolveInfo.activityInfo = mResolveActivity;
6136                    mResolveInfo.priority = 0;
6137                    mResolveInfo.preferredOrder = 0;
6138                    mResolveInfo.match = 0;
6139                    mResolveComponentName = new ComponentName(
6140                            mAndroidApplication.packageName, mResolveActivity.name);
6141                }
6142            }
6143        }
6144
6145        if (DEBUG_PACKAGE_SCANNING) {
6146            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6147                Log.d(TAG, "Scanning package " + pkg.packageName);
6148        }
6149
6150        if (mPackages.containsKey(pkg.packageName)
6151                || mSharedLibraries.containsKey(pkg.packageName)) {
6152            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6153                    "Application package " + pkg.packageName
6154                    + " already installed.  Skipping duplicate.");
6155        }
6156
6157        // If we're only installing presumed-existing packages, require that the
6158        // scanned APK is both already known and at the path previously established
6159        // for it.  Previously unknown packages we pick up normally, but if we have an
6160        // a priori expectation about this package's install presence, enforce it.
6161        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6162            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6163            if (known != null) {
6164                if (DEBUG_PACKAGE_SCANNING) {
6165                    Log.d(TAG, "Examining " + pkg.codePath
6166                            + " and requiring known paths " + known.codePathString
6167                            + " & " + known.resourcePathString);
6168                }
6169                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6170                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6171                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6172                            "Application package " + pkg.packageName
6173                            + " found at " + pkg.applicationInfo.getCodePath()
6174                            + " but expected at " + known.codePathString + "; ignoring.");
6175                }
6176            }
6177        }
6178
6179        // Initialize package source and resource directories
6180        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6181        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6182
6183        SharedUserSetting suid = null;
6184        PackageSetting pkgSetting = null;
6185
6186        if (!isSystemApp(pkg)) {
6187            // Only system apps can use these features.
6188            pkg.mOriginalPackages = null;
6189            pkg.mRealPackage = null;
6190            pkg.mAdoptPermissions = null;
6191        }
6192
6193        // writer
6194        synchronized (mPackages) {
6195            if (pkg.mSharedUserId != null) {
6196                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6197                if (suid == null) {
6198                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6199                            "Creating application package " + pkg.packageName
6200                            + " for shared user failed");
6201                }
6202                if (DEBUG_PACKAGE_SCANNING) {
6203                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6204                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6205                                + "): packages=" + suid.packages);
6206                }
6207            }
6208
6209            // Check if we are renaming from an original package name.
6210            PackageSetting origPackage = null;
6211            String realName = null;
6212            if (pkg.mOriginalPackages != null) {
6213                // This package may need to be renamed to a previously
6214                // installed name.  Let's check on that...
6215                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6216                if (pkg.mOriginalPackages.contains(renamed)) {
6217                    // This package had originally been installed as the
6218                    // original name, and we have already taken care of
6219                    // transitioning to the new one.  Just update the new
6220                    // one to continue using the old name.
6221                    realName = pkg.mRealPackage;
6222                    if (!pkg.packageName.equals(renamed)) {
6223                        // Callers into this function may have already taken
6224                        // care of renaming the package; only do it here if
6225                        // it is not already done.
6226                        pkg.setPackageName(renamed);
6227                    }
6228
6229                } else {
6230                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6231                        if ((origPackage = mSettings.peekPackageLPr(
6232                                pkg.mOriginalPackages.get(i))) != null) {
6233                            // We do have the package already installed under its
6234                            // original name...  should we use it?
6235                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6236                                // New package is not compatible with original.
6237                                origPackage = null;
6238                                continue;
6239                            } else if (origPackage.sharedUser != null) {
6240                                // Make sure uid is compatible between packages.
6241                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6242                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6243                                            + " to " + pkg.packageName + ": old uid "
6244                                            + origPackage.sharedUser.name
6245                                            + " differs from " + pkg.mSharedUserId);
6246                                    origPackage = null;
6247                                    continue;
6248                                }
6249                            } else {
6250                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6251                                        + pkg.packageName + " to old name " + origPackage.name);
6252                            }
6253                            break;
6254                        }
6255                    }
6256                }
6257            }
6258
6259            if (mTransferedPackages.contains(pkg.packageName)) {
6260                Slog.w(TAG, "Package " + pkg.packageName
6261                        + " was transferred to another, but its .apk remains");
6262            }
6263
6264            // Just create the setting, don't add it yet. For already existing packages
6265            // the PkgSetting exists already and doesn't have to be created.
6266            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6267                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6268                    pkg.applicationInfo.primaryCpuAbi,
6269                    pkg.applicationInfo.secondaryCpuAbi,
6270                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6271                    user, false);
6272            if (pkgSetting == null) {
6273                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6274                        "Creating application package " + pkg.packageName + " failed");
6275            }
6276
6277            if (pkgSetting.origPackage != null) {
6278                // If we are first transitioning from an original package,
6279                // fix up the new package's name now.  We need to do this after
6280                // looking up the package under its new name, so getPackageLP
6281                // can take care of fiddling things correctly.
6282                pkg.setPackageName(origPackage.name);
6283
6284                // File a report about this.
6285                String msg = "New package " + pkgSetting.realName
6286                        + " renamed to replace old package " + pkgSetting.name;
6287                reportSettingsProblem(Log.WARN, msg);
6288
6289                // Make a note of it.
6290                mTransferedPackages.add(origPackage.name);
6291
6292                // No longer need to retain this.
6293                pkgSetting.origPackage = null;
6294            }
6295
6296            if (realName != null) {
6297                // Make a note of it.
6298                mTransferedPackages.add(pkg.packageName);
6299            }
6300
6301            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6302                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6303            }
6304
6305            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6306                // Check all shared libraries and map to their actual file path.
6307                // We only do this here for apps not on a system dir, because those
6308                // are the only ones that can fail an install due to this.  We
6309                // will take care of the system apps by updating all of their
6310                // library paths after the scan is done.
6311                updateSharedLibrariesLPw(pkg, null);
6312            }
6313
6314            if (mFoundPolicyFile) {
6315                SELinuxMMAC.assignSeinfoValue(pkg);
6316            }
6317
6318            pkg.applicationInfo.uid = pkgSetting.appId;
6319            pkg.mExtras = pkgSetting;
6320            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6321                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6322                    // We just determined the app is signed correctly, so bring
6323                    // over the latest parsed certs.
6324                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6325                } else {
6326                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6327                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6328                                "Package " + pkg.packageName + " upgrade keys do not match the "
6329                                + "previously installed version");
6330                    } else {
6331                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6332                        String msg = "System package " + pkg.packageName
6333                            + " signature changed; retaining data.";
6334                        reportSettingsProblem(Log.WARN, msg);
6335                    }
6336                }
6337            } else {
6338                try {
6339                    verifySignaturesLP(pkgSetting, pkg);
6340                    // We just determined the app is signed correctly, so bring
6341                    // over the latest parsed certs.
6342                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6343                } catch (PackageManagerException e) {
6344                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6345                        throw e;
6346                    }
6347                    // The signature has changed, but this package is in the system
6348                    // image...  let's recover!
6349                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6350                    // However...  if this package is part of a shared user, but it
6351                    // doesn't match the signature of the shared user, let's fail.
6352                    // What this means is that you can't change the signatures
6353                    // associated with an overall shared user, which doesn't seem all
6354                    // that unreasonable.
6355                    if (pkgSetting.sharedUser != null) {
6356                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6357                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6358                            throw new PackageManagerException(
6359                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6360                                            "Signature mismatch for shared user : "
6361                                            + pkgSetting.sharedUser);
6362                        }
6363                    }
6364                    // File a report about this.
6365                    String msg = "System package " + pkg.packageName
6366                        + " signature changed; retaining data.";
6367                    reportSettingsProblem(Log.WARN, msg);
6368                }
6369            }
6370            // Verify that this new package doesn't have any content providers
6371            // that conflict with existing packages.  Only do this if the
6372            // package isn't already installed, since we don't want to break
6373            // things that are installed.
6374            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6375                final int N = pkg.providers.size();
6376                int i;
6377                for (i=0; i<N; i++) {
6378                    PackageParser.Provider p = pkg.providers.get(i);
6379                    if (p.info.authority != null) {
6380                        String names[] = p.info.authority.split(";");
6381                        for (int j = 0; j < names.length; j++) {
6382                            if (mProvidersByAuthority.containsKey(names[j])) {
6383                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6384                                final String otherPackageName =
6385                                        ((other != null && other.getComponentName() != null) ?
6386                                                other.getComponentName().getPackageName() : "?");
6387                                throw new PackageManagerException(
6388                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6389                                                "Can't install because provider name " + names[j]
6390                                                + " (in package " + pkg.applicationInfo.packageName
6391                                                + ") is already used by " + otherPackageName);
6392                            }
6393                        }
6394                    }
6395                }
6396            }
6397
6398            if (pkg.mAdoptPermissions != null) {
6399                // This package wants to adopt ownership of permissions from
6400                // another package.
6401                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6402                    final String origName = pkg.mAdoptPermissions.get(i);
6403                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6404                    if (orig != null) {
6405                        if (verifyPackageUpdateLPr(orig, pkg)) {
6406                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6407                                    + pkg.packageName);
6408                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6409                        }
6410                    }
6411                }
6412            }
6413        }
6414
6415        final String pkgName = pkg.packageName;
6416
6417        final long scanFileTime = scanFile.lastModified();
6418        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6419        pkg.applicationInfo.processName = fixProcessName(
6420                pkg.applicationInfo.packageName,
6421                pkg.applicationInfo.processName,
6422                pkg.applicationInfo.uid);
6423
6424        File dataPath;
6425        if (mPlatformPackage == pkg) {
6426            // The system package is special.
6427            dataPath = new File(Environment.getDataDirectory(), "system");
6428
6429            pkg.applicationInfo.dataDir = dataPath.getPath();
6430
6431        } else {
6432            // This is a normal package, need to make its data directory.
6433            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6434                    UserHandle.USER_OWNER);
6435
6436            boolean uidError = false;
6437            if (dataPath.exists()) {
6438                int currentUid = 0;
6439                try {
6440                    StructStat stat = Os.stat(dataPath.getPath());
6441                    currentUid = stat.st_uid;
6442                } catch (ErrnoException e) {
6443                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6444                }
6445
6446                // If we have mismatched owners for the data path, we have a problem.
6447                if (currentUid != pkg.applicationInfo.uid) {
6448                    boolean recovered = false;
6449                    if (currentUid == 0) {
6450                        // The directory somehow became owned by root.  Wow.
6451                        // This is probably because the system was stopped while
6452                        // installd was in the middle of messing with its libs
6453                        // directory.  Ask installd to fix that.
6454                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6455                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6456                        if (ret >= 0) {
6457                            recovered = true;
6458                            String msg = "Package " + pkg.packageName
6459                                    + " unexpectedly changed to uid 0; recovered to " +
6460                                    + pkg.applicationInfo.uid;
6461                            reportSettingsProblem(Log.WARN, msg);
6462                        }
6463                    }
6464                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6465                            || (scanFlags&SCAN_BOOTING) != 0)) {
6466                        // If this is a system app, we can at least delete its
6467                        // current data so the application will still work.
6468                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6469                        if (ret >= 0) {
6470                            // TODO: Kill the processes first
6471                            // Old data gone!
6472                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6473                                    ? "System package " : "Third party package ";
6474                            String msg = prefix + pkg.packageName
6475                                    + " has changed from uid: "
6476                                    + currentUid + " to "
6477                                    + pkg.applicationInfo.uid + "; old data erased";
6478                            reportSettingsProblem(Log.WARN, msg);
6479                            recovered = true;
6480
6481                            // And now re-install the app.
6482                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6483                                    pkg.applicationInfo.seinfo);
6484                            if (ret == -1) {
6485                                // Ack should not happen!
6486                                msg = prefix + pkg.packageName
6487                                        + " could not have data directory re-created after delete.";
6488                                reportSettingsProblem(Log.WARN, msg);
6489                                throw new PackageManagerException(
6490                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6491                            }
6492                        }
6493                        if (!recovered) {
6494                            mHasSystemUidErrors = true;
6495                        }
6496                    } else if (!recovered) {
6497                        // If we allow this install to proceed, we will be broken.
6498                        // Abort, abort!
6499                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6500                                "scanPackageLI");
6501                    }
6502                    if (!recovered) {
6503                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6504                            + pkg.applicationInfo.uid + "/fs_"
6505                            + currentUid;
6506                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6507                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6508                        String msg = "Package " + pkg.packageName
6509                                + " has mismatched uid: "
6510                                + currentUid + " on disk, "
6511                                + pkg.applicationInfo.uid + " in settings";
6512                        // writer
6513                        synchronized (mPackages) {
6514                            mSettings.mReadMessages.append(msg);
6515                            mSettings.mReadMessages.append('\n');
6516                            uidError = true;
6517                            if (!pkgSetting.uidError) {
6518                                reportSettingsProblem(Log.ERROR, msg);
6519                            }
6520                        }
6521                    }
6522                }
6523                pkg.applicationInfo.dataDir = dataPath.getPath();
6524                if (mShouldRestoreconData) {
6525                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6526                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6527                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6528                }
6529            } else {
6530                if (DEBUG_PACKAGE_SCANNING) {
6531                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6532                        Log.v(TAG, "Want this data dir: " + dataPath);
6533                }
6534                //invoke installer to do the actual installation
6535                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6536                        pkg.applicationInfo.seinfo);
6537                if (ret < 0) {
6538                    // Error from installer
6539                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6540                            "Unable to create data dirs [errorCode=" + ret + "]");
6541                }
6542
6543                if (dataPath.exists()) {
6544                    pkg.applicationInfo.dataDir = dataPath.getPath();
6545                } else {
6546                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6547                    pkg.applicationInfo.dataDir = null;
6548                }
6549            }
6550
6551            pkgSetting.uidError = uidError;
6552        }
6553
6554        final String path = scanFile.getPath();
6555        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6556
6557        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6558            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6559
6560            // Some system apps still use directory structure for native libraries
6561            // in which case we might end up not detecting abi solely based on apk
6562            // structure. Try to detect abi based on directory structure.
6563            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6564                    pkg.applicationInfo.primaryCpuAbi == null) {
6565                setBundledAppAbisAndRoots(pkg, pkgSetting);
6566                setNativeLibraryPaths(pkg);
6567            }
6568
6569        } else {
6570            if ((scanFlags & SCAN_MOVE) != 0) {
6571                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6572                // but we already have this packages package info in the PackageSetting. We just
6573                // use that and derive the native library path based on the new codepath.
6574                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6575                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6576            }
6577
6578            // Set native library paths again. For moves, the path will be updated based on the
6579            // ABIs we've determined above. For non-moves, the path will be updated based on the
6580            // ABIs we determined during compilation, but the path will depend on the final
6581            // package path (after the rename away from the stage path).
6582            setNativeLibraryPaths(pkg);
6583        }
6584
6585        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6586        final int[] userIds = sUserManager.getUserIds();
6587        synchronized (mInstallLock) {
6588            // Create a native library symlink only if we have native libraries
6589            // and if the native libraries are 32 bit libraries. We do not provide
6590            // this symlink for 64 bit libraries.
6591            if (pkg.applicationInfo.primaryCpuAbi != null &&
6592                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6593                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6594                for (int userId : userIds) {
6595                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6596                            nativeLibPath, userId) < 0) {
6597                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6598                                "Failed linking native library dir (user=" + userId + ")");
6599                    }
6600                }
6601            }
6602        }
6603
6604        // This is a special case for the "system" package, where the ABI is
6605        // dictated by the zygote configuration (and init.rc). We should keep track
6606        // of this ABI so that we can deal with "normal" applications that run under
6607        // the same UID correctly.
6608        if (mPlatformPackage == pkg) {
6609            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6610                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6611        }
6612
6613        // If there's a mismatch between the abi-override in the package setting
6614        // and the abiOverride specified for the install. Warn about this because we
6615        // would've already compiled the app without taking the package setting into
6616        // account.
6617        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6618            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6619                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6620                        " for package: " + pkg.packageName);
6621            }
6622        }
6623
6624        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6625        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6626        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6627
6628        // Copy the derived override back to the parsed package, so that we can
6629        // update the package settings accordingly.
6630        pkg.cpuAbiOverride = cpuAbiOverride;
6631
6632        if (DEBUG_ABI_SELECTION) {
6633            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6634                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6635                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6636        }
6637
6638        // Push the derived path down into PackageSettings so we know what to
6639        // clean up at uninstall time.
6640        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6641
6642        if (DEBUG_ABI_SELECTION) {
6643            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6644                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6645                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6646        }
6647
6648        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6649            // We don't do this here during boot because we can do it all
6650            // at once after scanning all existing packages.
6651            //
6652            // We also do this *before* we perform dexopt on this package, so that
6653            // we can avoid redundant dexopts, and also to make sure we've got the
6654            // code and package path correct.
6655            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6656                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6657        }
6658
6659        if ((scanFlags & SCAN_NO_DEX) == 0) {
6660            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6661                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6662            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6663                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6664            }
6665        }
6666        if (mFactoryTest && pkg.requestedPermissions.contains(
6667                android.Manifest.permission.FACTORY_TEST)) {
6668            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6669        }
6670
6671        ArrayList<PackageParser.Package> clientLibPkgs = null;
6672
6673        // writer
6674        synchronized (mPackages) {
6675            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6676                // Only system apps can add new shared libraries.
6677                if (pkg.libraryNames != null) {
6678                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6679                        String name = pkg.libraryNames.get(i);
6680                        boolean allowed = false;
6681                        if (pkg.isUpdatedSystemApp()) {
6682                            // New library entries can only be added through the
6683                            // system image.  This is important to get rid of a lot
6684                            // of nasty edge cases: for example if we allowed a non-
6685                            // system update of the app to add a library, then uninstalling
6686                            // the update would make the library go away, and assumptions
6687                            // we made such as through app install filtering would now
6688                            // have allowed apps on the device which aren't compatible
6689                            // with it.  Better to just have the restriction here, be
6690                            // conservative, and create many fewer cases that can negatively
6691                            // impact the user experience.
6692                            final PackageSetting sysPs = mSettings
6693                                    .getDisabledSystemPkgLPr(pkg.packageName);
6694                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6695                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6696                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6697                                        allowed = true;
6698                                        allowed = true;
6699                                        break;
6700                                    }
6701                                }
6702                            }
6703                        } else {
6704                            allowed = true;
6705                        }
6706                        if (allowed) {
6707                            if (!mSharedLibraries.containsKey(name)) {
6708                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6709                            } else if (!name.equals(pkg.packageName)) {
6710                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6711                                        + name + " already exists; skipping");
6712                            }
6713                        } else {
6714                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6715                                    + name + " that is not declared on system image; skipping");
6716                        }
6717                    }
6718                    if ((scanFlags&SCAN_BOOTING) == 0) {
6719                        // If we are not booting, we need to update any applications
6720                        // that are clients of our shared library.  If we are booting,
6721                        // this will all be done once the scan is complete.
6722                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6723                    }
6724                }
6725            }
6726        }
6727
6728        // We also need to dexopt any apps that are dependent on this library.  Note that
6729        // if these fail, we should abort the install since installing the library will
6730        // result in some apps being broken.
6731        if (clientLibPkgs != null) {
6732            if ((scanFlags & SCAN_NO_DEX) == 0) {
6733                for (int i = 0; i < clientLibPkgs.size(); i++) {
6734                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6735                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6736                            null /* instruction sets */, forceDex,
6737                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6738                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6739                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6740                                "scanPackageLI failed to dexopt clientLibPkgs");
6741                    }
6742                }
6743            }
6744        }
6745
6746        // Also need to kill any apps that are dependent on the library.
6747        if (clientLibPkgs != null) {
6748            for (int i=0; i<clientLibPkgs.size(); i++) {
6749                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6750                killApplication(clientPkg.applicationInfo.packageName,
6751                        clientPkg.applicationInfo.uid, "update lib");
6752            }
6753        }
6754
6755        // Make sure we're not adding any bogus keyset info
6756        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6757        ksms.assertScannedPackageValid(pkg);
6758
6759        // writer
6760        synchronized (mPackages) {
6761            // We don't expect installation to fail beyond this point
6762
6763            // Add the new setting to mSettings
6764            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6765            // Add the new setting to mPackages
6766            mPackages.put(pkg.applicationInfo.packageName, pkg);
6767            // Make sure we don't accidentally delete its data.
6768            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6769            while (iter.hasNext()) {
6770                PackageCleanItem item = iter.next();
6771                if (pkgName.equals(item.packageName)) {
6772                    iter.remove();
6773                }
6774            }
6775
6776            // Take care of first install / last update times.
6777            if (currentTime != 0) {
6778                if (pkgSetting.firstInstallTime == 0) {
6779                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6780                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6781                    pkgSetting.lastUpdateTime = currentTime;
6782                }
6783            } else if (pkgSetting.firstInstallTime == 0) {
6784                // We need *something*.  Take time time stamp of the file.
6785                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6786            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6787                if (scanFileTime != pkgSetting.timeStamp) {
6788                    // A package on the system image has changed; consider this
6789                    // to be an update.
6790                    pkgSetting.lastUpdateTime = scanFileTime;
6791                }
6792            }
6793
6794            // Add the package's KeySets to the global KeySetManagerService
6795            ksms.addScannedPackageLPw(pkg);
6796
6797            int N = pkg.providers.size();
6798            StringBuilder r = null;
6799            int i;
6800            for (i=0; i<N; i++) {
6801                PackageParser.Provider p = pkg.providers.get(i);
6802                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6803                        p.info.processName, pkg.applicationInfo.uid);
6804                mProviders.addProvider(p);
6805                p.syncable = p.info.isSyncable;
6806                if (p.info.authority != null) {
6807                    String names[] = p.info.authority.split(";");
6808                    p.info.authority = null;
6809                    for (int j = 0; j < names.length; j++) {
6810                        if (j == 1 && p.syncable) {
6811                            // We only want the first authority for a provider to possibly be
6812                            // syncable, so if we already added this provider using a different
6813                            // authority clear the syncable flag. We copy the provider before
6814                            // changing it because the mProviders object contains a reference
6815                            // to a provider that we don't want to change.
6816                            // Only do this for the second authority since the resulting provider
6817                            // object can be the same for all future authorities for this provider.
6818                            p = new PackageParser.Provider(p);
6819                            p.syncable = false;
6820                        }
6821                        if (!mProvidersByAuthority.containsKey(names[j])) {
6822                            mProvidersByAuthority.put(names[j], p);
6823                            if (p.info.authority == null) {
6824                                p.info.authority = names[j];
6825                            } else {
6826                                p.info.authority = p.info.authority + ";" + names[j];
6827                            }
6828                            if (DEBUG_PACKAGE_SCANNING) {
6829                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6830                                    Log.d(TAG, "Registered content provider: " + names[j]
6831                                            + ", className = " + p.info.name + ", isSyncable = "
6832                                            + p.info.isSyncable);
6833                            }
6834                        } else {
6835                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6836                            Slog.w(TAG, "Skipping provider name " + names[j] +
6837                                    " (in package " + pkg.applicationInfo.packageName +
6838                                    "): name already used by "
6839                                    + ((other != null && other.getComponentName() != null)
6840                                            ? other.getComponentName().getPackageName() : "?"));
6841                        }
6842                    }
6843                }
6844                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6845                    if (r == null) {
6846                        r = new StringBuilder(256);
6847                    } else {
6848                        r.append(' ');
6849                    }
6850                    r.append(p.info.name);
6851                }
6852            }
6853            if (r != null) {
6854                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6855            }
6856
6857            N = pkg.services.size();
6858            r = null;
6859            for (i=0; i<N; i++) {
6860                PackageParser.Service s = pkg.services.get(i);
6861                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6862                        s.info.processName, pkg.applicationInfo.uid);
6863                mServices.addService(s);
6864                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6865                    if (r == null) {
6866                        r = new StringBuilder(256);
6867                    } else {
6868                        r.append(' ');
6869                    }
6870                    r.append(s.info.name);
6871                }
6872            }
6873            if (r != null) {
6874                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6875            }
6876
6877            N = pkg.receivers.size();
6878            r = null;
6879            for (i=0; i<N; i++) {
6880                PackageParser.Activity a = pkg.receivers.get(i);
6881                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6882                        a.info.processName, pkg.applicationInfo.uid);
6883                mReceivers.addActivity(a, "receiver");
6884                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6885                    if (r == null) {
6886                        r = new StringBuilder(256);
6887                    } else {
6888                        r.append(' ');
6889                    }
6890                    r.append(a.info.name);
6891                }
6892            }
6893            if (r != null) {
6894                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6895            }
6896
6897            N = pkg.activities.size();
6898            r = null;
6899            for (i=0; i<N; i++) {
6900                PackageParser.Activity a = pkg.activities.get(i);
6901                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6902                        a.info.processName, pkg.applicationInfo.uid);
6903                mActivities.addActivity(a, "activity");
6904                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6905                    if (r == null) {
6906                        r = new StringBuilder(256);
6907                    } else {
6908                        r.append(' ');
6909                    }
6910                    r.append(a.info.name);
6911                }
6912            }
6913            if (r != null) {
6914                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6915            }
6916
6917            N = pkg.permissionGroups.size();
6918            r = null;
6919            for (i=0; i<N; i++) {
6920                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6921                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6922                if (cur == null) {
6923                    mPermissionGroups.put(pg.info.name, pg);
6924                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6925                        if (r == null) {
6926                            r = new StringBuilder(256);
6927                        } else {
6928                            r.append(' ');
6929                        }
6930                        r.append(pg.info.name);
6931                    }
6932                } else {
6933                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6934                            + pg.info.packageName + " ignored: original from "
6935                            + cur.info.packageName);
6936                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6937                        if (r == null) {
6938                            r = new StringBuilder(256);
6939                        } else {
6940                            r.append(' ');
6941                        }
6942                        r.append("DUP:");
6943                        r.append(pg.info.name);
6944                    }
6945                }
6946            }
6947            if (r != null) {
6948                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6949            }
6950
6951            N = pkg.permissions.size();
6952            r = null;
6953            for (i=0; i<N; i++) {
6954                PackageParser.Permission p = pkg.permissions.get(i);
6955
6956                // Now that permission groups have a special meaning, we ignore permission
6957                // groups for legacy apps to prevent unexpected behavior. In particular,
6958                // permissions for one app being granted to someone just becuase they happen
6959                // to be in a group defined by another app (before this had no implications).
6960                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6961                    p.group = mPermissionGroups.get(p.info.group);
6962                    // Warn for a permission in an unknown group.
6963                    if (p.info.group != null && p.group == null) {
6964                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6965                                + p.info.packageName + " in an unknown group " + p.info.group);
6966                    }
6967                }
6968
6969                ArrayMap<String, BasePermission> permissionMap =
6970                        p.tree ? mSettings.mPermissionTrees
6971                                : mSettings.mPermissions;
6972                BasePermission bp = permissionMap.get(p.info.name);
6973
6974                // Allow system apps to redefine non-system permissions
6975                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6976                    final boolean currentOwnerIsSystem = (bp.perm != null
6977                            && isSystemApp(bp.perm.owner));
6978                    if (isSystemApp(p.owner)) {
6979                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6980                            // It's a built-in permission and no owner, take ownership now
6981                            bp.packageSetting = pkgSetting;
6982                            bp.perm = p;
6983                            bp.uid = pkg.applicationInfo.uid;
6984                            bp.sourcePackage = p.info.packageName;
6985                        } else if (!currentOwnerIsSystem) {
6986                            String msg = "New decl " + p.owner + " of permission  "
6987                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6988                            reportSettingsProblem(Log.WARN, msg);
6989                            bp = null;
6990                        }
6991                    }
6992                }
6993
6994                if (bp == null) {
6995                    bp = new BasePermission(p.info.name, p.info.packageName,
6996                            BasePermission.TYPE_NORMAL);
6997                    permissionMap.put(p.info.name, bp);
6998                }
6999
7000                if (bp.perm == null) {
7001                    if (bp.sourcePackage == null
7002                            || bp.sourcePackage.equals(p.info.packageName)) {
7003                        BasePermission tree = findPermissionTreeLP(p.info.name);
7004                        if (tree == null
7005                                || tree.sourcePackage.equals(p.info.packageName)) {
7006                            bp.packageSetting = pkgSetting;
7007                            bp.perm = p;
7008                            bp.uid = pkg.applicationInfo.uid;
7009                            bp.sourcePackage = p.info.packageName;
7010                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7011                                if (r == null) {
7012                                    r = new StringBuilder(256);
7013                                } else {
7014                                    r.append(' ');
7015                                }
7016                                r.append(p.info.name);
7017                            }
7018                        } else {
7019                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7020                                    + p.info.packageName + " ignored: base tree "
7021                                    + tree.name + " is from package "
7022                                    + tree.sourcePackage);
7023                        }
7024                    } else {
7025                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7026                                + p.info.packageName + " ignored: original from "
7027                                + bp.sourcePackage);
7028                    }
7029                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7030                    if (r == null) {
7031                        r = new StringBuilder(256);
7032                    } else {
7033                        r.append(' ');
7034                    }
7035                    r.append("DUP:");
7036                    r.append(p.info.name);
7037                }
7038                if (bp.perm == p) {
7039                    bp.protectionLevel = p.info.protectionLevel;
7040                }
7041            }
7042
7043            if (r != null) {
7044                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7045            }
7046
7047            N = pkg.instrumentation.size();
7048            r = null;
7049            for (i=0; i<N; i++) {
7050                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7051                a.info.packageName = pkg.applicationInfo.packageName;
7052                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7053                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7054                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7055                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7056                a.info.dataDir = pkg.applicationInfo.dataDir;
7057
7058                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7059                // need other information about the application, like the ABI and what not ?
7060                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7061                mInstrumentation.put(a.getComponentName(), a);
7062                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7063                    if (r == null) {
7064                        r = new StringBuilder(256);
7065                    } else {
7066                        r.append(' ');
7067                    }
7068                    r.append(a.info.name);
7069                }
7070            }
7071            if (r != null) {
7072                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7073            }
7074
7075            if (pkg.protectedBroadcasts != null) {
7076                N = pkg.protectedBroadcasts.size();
7077                for (i=0; i<N; i++) {
7078                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7079                }
7080            }
7081
7082            pkgSetting.setTimeStamp(scanFileTime);
7083
7084            // Create idmap files for pairs of (packages, overlay packages).
7085            // Note: "android", ie framework-res.apk, is handled by native layers.
7086            if (pkg.mOverlayTarget != null) {
7087                // This is an overlay package.
7088                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7089                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7090                        mOverlays.put(pkg.mOverlayTarget,
7091                                new ArrayMap<String, PackageParser.Package>());
7092                    }
7093                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7094                    map.put(pkg.packageName, pkg);
7095                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7096                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7097                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7098                                "scanPackageLI failed to createIdmap");
7099                    }
7100                }
7101            } else if (mOverlays.containsKey(pkg.packageName) &&
7102                    !pkg.packageName.equals("android")) {
7103                // This is a regular package, with one or more known overlay packages.
7104                createIdmapsForPackageLI(pkg);
7105            }
7106        }
7107
7108        return pkg;
7109    }
7110
7111    /**
7112     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7113     * is derived purely on the basis of the contents of {@code scanFile} and
7114     * {@code cpuAbiOverride}.
7115     *
7116     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7117     */
7118    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7119                                 String cpuAbiOverride, boolean extractLibs)
7120            throws PackageManagerException {
7121        // TODO: We can probably be smarter about this stuff. For installed apps,
7122        // we can calculate this information at install time once and for all. For
7123        // system apps, we can probably assume that this information doesn't change
7124        // after the first boot scan. As things stand, we do lots of unnecessary work.
7125
7126        // Give ourselves some initial paths; we'll come back for another
7127        // pass once we've determined ABI below.
7128        setNativeLibraryPaths(pkg);
7129
7130        // We would never need to extract libs for forward-locked and external packages,
7131        // since the container service will do it for us. We shouldn't attempt to
7132        // extract libs from system app when it was not updated.
7133        if (pkg.isForwardLocked() || isExternal(pkg) ||
7134            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7135            extractLibs = false;
7136        }
7137
7138        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7139        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7140
7141        NativeLibraryHelper.Handle handle = null;
7142        try {
7143            handle = NativeLibraryHelper.Handle.create(scanFile);
7144            // TODO(multiArch): This can be null for apps that didn't go through the
7145            // usual installation process. We can calculate it again, like we
7146            // do during install time.
7147            //
7148            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7149            // unnecessary.
7150            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7151
7152            // Null out the abis so that they can be recalculated.
7153            pkg.applicationInfo.primaryCpuAbi = null;
7154            pkg.applicationInfo.secondaryCpuAbi = null;
7155            if (isMultiArch(pkg.applicationInfo)) {
7156                // Warn if we've set an abiOverride for multi-lib packages..
7157                // By definition, we need to copy both 32 and 64 bit libraries for
7158                // such packages.
7159                if (pkg.cpuAbiOverride != null
7160                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7161                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7162                }
7163
7164                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7165                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7166                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7167                    if (extractLibs) {
7168                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7169                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7170                                useIsaSpecificSubdirs);
7171                    } else {
7172                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7173                    }
7174                }
7175
7176                maybeThrowExceptionForMultiArchCopy(
7177                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7178
7179                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7180                    if (extractLibs) {
7181                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7182                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7183                                useIsaSpecificSubdirs);
7184                    } else {
7185                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7186                    }
7187                }
7188
7189                maybeThrowExceptionForMultiArchCopy(
7190                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7191
7192                if (abi64 >= 0) {
7193                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7194                }
7195
7196                if (abi32 >= 0) {
7197                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7198                    if (abi64 >= 0) {
7199                        pkg.applicationInfo.secondaryCpuAbi = abi;
7200                    } else {
7201                        pkg.applicationInfo.primaryCpuAbi = abi;
7202                    }
7203                }
7204            } else {
7205                String[] abiList = (cpuAbiOverride != null) ?
7206                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7207
7208                // Enable gross and lame hacks for apps that are built with old
7209                // SDK tools. We must scan their APKs for renderscript bitcode and
7210                // not launch them if it's present. Don't bother checking on devices
7211                // that don't have 64 bit support.
7212                boolean needsRenderScriptOverride = false;
7213                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7214                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7215                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7216                    needsRenderScriptOverride = true;
7217                }
7218
7219                final int copyRet;
7220                if (extractLibs) {
7221                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7222                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7223                } else {
7224                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7225                }
7226
7227                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7228                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7229                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7230                }
7231
7232                if (copyRet >= 0) {
7233                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7234                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7235                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7236                } else if (needsRenderScriptOverride) {
7237                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7238                }
7239            }
7240        } catch (IOException ioe) {
7241            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7242        } finally {
7243            IoUtils.closeQuietly(handle);
7244        }
7245
7246        // Now that we've calculated the ABIs and determined if it's an internal app,
7247        // we will go ahead and populate the nativeLibraryPath.
7248        setNativeLibraryPaths(pkg);
7249    }
7250
7251    /**
7252     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7253     * i.e, so that all packages can be run inside a single process if required.
7254     *
7255     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7256     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7257     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7258     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7259     * updating a package that belongs to a shared user.
7260     *
7261     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7262     * adds unnecessary complexity.
7263     */
7264    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7265            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7266        String requiredInstructionSet = null;
7267        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7268            requiredInstructionSet = VMRuntime.getInstructionSet(
7269                     scannedPackage.applicationInfo.primaryCpuAbi);
7270        }
7271
7272        PackageSetting requirer = null;
7273        for (PackageSetting ps : packagesForUser) {
7274            // If packagesForUser contains scannedPackage, we skip it. This will happen
7275            // when scannedPackage is an update of an existing package. Without this check,
7276            // we will never be able to change the ABI of any package belonging to a shared
7277            // user, even if it's compatible with other packages.
7278            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7279                if (ps.primaryCpuAbiString == null) {
7280                    continue;
7281                }
7282
7283                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7284                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7285                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7286                    // this but there's not much we can do.
7287                    String errorMessage = "Instruction set mismatch, "
7288                            + ((requirer == null) ? "[caller]" : requirer)
7289                            + " requires " + requiredInstructionSet + " whereas " + ps
7290                            + " requires " + instructionSet;
7291                    Slog.w(TAG, errorMessage);
7292                }
7293
7294                if (requiredInstructionSet == null) {
7295                    requiredInstructionSet = instructionSet;
7296                    requirer = ps;
7297                }
7298            }
7299        }
7300
7301        if (requiredInstructionSet != null) {
7302            String adjustedAbi;
7303            if (requirer != null) {
7304                // requirer != null implies that either scannedPackage was null or that scannedPackage
7305                // did not require an ABI, in which case we have to adjust scannedPackage to match
7306                // the ABI of the set (which is the same as requirer's ABI)
7307                adjustedAbi = requirer.primaryCpuAbiString;
7308                if (scannedPackage != null) {
7309                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7310                }
7311            } else {
7312                // requirer == null implies that we're updating all ABIs in the set to
7313                // match scannedPackage.
7314                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7315            }
7316
7317            for (PackageSetting ps : packagesForUser) {
7318                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7319                    if (ps.primaryCpuAbiString != null) {
7320                        continue;
7321                    }
7322
7323                    ps.primaryCpuAbiString = adjustedAbi;
7324                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7325                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7326                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7327
7328                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7329                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7330                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7331                            ps.primaryCpuAbiString = null;
7332                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7333                            return;
7334                        } else {
7335                            mInstaller.rmdex(ps.codePathString,
7336                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7337                        }
7338                    }
7339                }
7340            }
7341        }
7342    }
7343
7344    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7345        synchronized (mPackages) {
7346            mResolverReplaced = true;
7347            // Set up information for custom user intent resolution activity.
7348            mResolveActivity.applicationInfo = pkg.applicationInfo;
7349            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7350            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7351            mResolveActivity.processName = pkg.applicationInfo.packageName;
7352            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7353            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7354                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7355            mResolveActivity.theme = 0;
7356            mResolveActivity.exported = true;
7357            mResolveActivity.enabled = true;
7358            mResolveInfo.activityInfo = mResolveActivity;
7359            mResolveInfo.priority = 0;
7360            mResolveInfo.preferredOrder = 0;
7361            mResolveInfo.match = 0;
7362            mResolveComponentName = mCustomResolverComponentName;
7363            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7364                    mResolveComponentName);
7365        }
7366    }
7367
7368    private static String calculateBundledApkRoot(final String codePathString) {
7369        final File codePath = new File(codePathString);
7370        final File codeRoot;
7371        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7372            codeRoot = Environment.getRootDirectory();
7373        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7374            codeRoot = Environment.getOemDirectory();
7375        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7376            codeRoot = Environment.getVendorDirectory();
7377        } else {
7378            // Unrecognized code path; take its top real segment as the apk root:
7379            // e.g. /something/app/blah.apk => /something
7380            try {
7381                File f = codePath.getCanonicalFile();
7382                File parent = f.getParentFile();    // non-null because codePath is a file
7383                File tmp;
7384                while ((tmp = parent.getParentFile()) != null) {
7385                    f = parent;
7386                    parent = tmp;
7387                }
7388                codeRoot = f;
7389                Slog.w(TAG, "Unrecognized code path "
7390                        + codePath + " - using " + codeRoot);
7391            } catch (IOException e) {
7392                // Can't canonicalize the code path -- shenanigans?
7393                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7394                return Environment.getRootDirectory().getPath();
7395            }
7396        }
7397        return codeRoot.getPath();
7398    }
7399
7400    /**
7401     * Derive and set the location of native libraries for the given package,
7402     * which varies depending on where and how the package was installed.
7403     */
7404    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7405        final ApplicationInfo info = pkg.applicationInfo;
7406        final String codePath = pkg.codePath;
7407        final File codeFile = new File(codePath);
7408        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7409        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7410
7411        info.nativeLibraryRootDir = null;
7412        info.nativeLibraryRootRequiresIsa = false;
7413        info.nativeLibraryDir = null;
7414        info.secondaryNativeLibraryDir = null;
7415
7416        if (isApkFile(codeFile)) {
7417            // Monolithic install
7418            if (bundledApp) {
7419                // If "/system/lib64/apkname" exists, assume that is the per-package
7420                // native library directory to use; otherwise use "/system/lib/apkname".
7421                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7422                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7423                        getPrimaryInstructionSet(info));
7424
7425                // This is a bundled system app so choose the path based on the ABI.
7426                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7427                // is just the default path.
7428                final String apkName = deriveCodePathName(codePath);
7429                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7430                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7431                        apkName).getAbsolutePath();
7432
7433                if (info.secondaryCpuAbi != null) {
7434                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7435                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7436                            secondaryLibDir, apkName).getAbsolutePath();
7437                }
7438            } else if (asecApp) {
7439                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7440                        .getAbsolutePath();
7441            } else {
7442                final String apkName = deriveCodePathName(codePath);
7443                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7444                        .getAbsolutePath();
7445            }
7446
7447            info.nativeLibraryRootRequiresIsa = false;
7448            info.nativeLibraryDir = info.nativeLibraryRootDir;
7449        } else {
7450            // Cluster install
7451            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7452            info.nativeLibraryRootRequiresIsa = true;
7453
7454            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7455                    getPrimaryInstructionSet(info)).getAbsolutePath();
7456
7457            if (info.secondaryCpuAbi != null) {
7458                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7459                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7460            }
7461        }
7462    }
7463
7464    /**
7465     * Calculate the abis and roots for a bundled app. These can uniquely
7466     * be determined from the contents of the system partition, i.e whether
7467     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7468     * of this information, and instead assume that the system was built
7469     * sensibly.
7470     */
7471    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7472                                           PackageSetting pkgSetting) {
7473        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7474
7475        // If "/system/lib64/apkname" exists, assume that is the per-package
7476        // native library directory to use; otherwise use "/system/lib/apkname".
7477        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7478        setBundledAppAbi(pkg, apkRoot, apkName);
7479        // pkgSetting might be null during rescan following uninstall of updates
7480        // to a bundled app, so accommodate that possibility.  The settings in
7481        // that case will be established later from the parsed package.
7482        //
7483        // If the settings aren't null, sync them up with what we've just derived.
7484        // note that apkRoot isn't stored in the package settings.
7485        if (pkgSetting != null) {
7486            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7487            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7488        }
7489    }
7490
7491    /**
7492     * Deduces the ABI of a bundled app and sets the relevant fields on the
7493     * parsed pkg object.
7494     *
7495     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7496     *        under which system libraries are installed.
7497     * @param apkName the name of the installed package.
7498     */
7499    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7500        final File codeFile = new File(pkg.codePath);
7501
7502        final boolean has64BitLibs;
7503        final boolean has32BitLibs;
7504        if (isApkFile(codeFile)) {
7505            // Monolithic install
7506            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7507            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7508        } else {
7509            // Cluster install
7510            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7511            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7512                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7513                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7514                has64BitLibs = (new File(rootDir, isa)).exists();
7515            } else {
7516                has64BitLibs = false;
7517            }
7518            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7519                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7520                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7521                has32BitLibs = (new File(rootDir, isa)).exists();
7522            } else {
7523                has32BitLibs = false;
7524            }
7525        }
7526
7527        if (has64BitLibs && !has32BitLibs) {
7528            // The package has 64 bit libs, but not 32 bit libs. Its primary
7529            // ABI should be 64 bit. We can safely assume here that the bundled
7530            // native libraries correspond to the most preferred ABI in the list.
7531
7532            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7533            pkg.applicationInfo.secondaryCpuAbi = null;
7534        } else if (has32BitLibs && !has64BitLibs) {
7535            // The package has 32 bit libs but not 64 bit libs. Its primary
7536            // ABI should be 32 bit.
7537
7538            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7539            pkg.applicationInfo.secondaryCpuAbi = null;
7540        } else if (has32BitLibs && has64BitLibs) {
7541            // The application has both 64 and 32 bit bundled libraries. We check
7542            // here that the app declares multiArch support, and warn if it doesn't.
7543            //
7544            // We will be lenient here and record both ABIs. The primary will be the
7545            // ABI that's higher on the list, i.e, a device that's configured to prefer
7546            // 64 bit apps will see a 64 bit primary ABI,
7547
7548            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7549                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7550            }
7551
7552            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7553                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7554                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7555            } else {
7556                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7557                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7558            }
7559        } else {
7560            pkg.applicationInfo.primaryCpuAbi = null;
7561            pkg.applicationInfo.secondaryCpuAbi = null;
7562        }
7563    }
7564
7565    private void killApplication(String pkgName, int appId, String reason) {
7566        // Request the ActivityManager to kill the process(only for existing packages)
7567        // so that we do not end up in a confused state while the user is still using the older
7568        // version of the application while the new one gets installed.
7569        IActivityManager am = ActivityManagerNative.getDefault();
7570        if (am != null) {
7571            try {
7572                am.killApplicationWithAppId(pkgName, appId, reason);
7573            } catch (RemoteException e) {
7574            }
7575        }
7576    }
7577
7578    void removePackageLI(PackageSetting ps, boolean chatty) {
7579        if (DEBUG_INSTALL) {
7580            if (chatty)
7581                Log.d(TAG, "Removing package " + ps.name);
7582        }
7583
7584        // writer
7585        synchronized (mPackages) {
7586            mPackages.remove(ps.name);
7587            final PackageParser.Package pkg = ps.pkg;
7588            if (pkg != null) {
7589                cleanPackageDataStructuresLILPw(pkg, chatty);
7590            }
7591        }
7592    }
7593
7594    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7595        if (DEBUG_INSTALL) {
7596            if (chatty)
7597                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7598        }
7599
7600        // writer
7601        synchronized (mPackages) {
7602            mPackages.remove(pkg.applicationInfo.packageName);
7603            cleanPackageDataStructuresLILPw(pkg, chatty);
7604        }
7605    }
7606
7607    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7608        int N = pkg.providers.size();
7609        StringBuilder r = null;
7610        int i;
7611        for (i=0; i<N; i++) {
7612            PackageParser.Provider p = pkg.providers.get(i);
7613            mProviders.removeProvider(p);
7614            if (p.info.authority == null) {
7615
7616                /* There was another ContentProvider with this authority when
7617                 * this app was installed so this authority is null,
7618                 * Ignore it as we don't have to unregister the provider.
7619                 */
7620                continue;
7621            }
7622            String names[] = p.info.authority.split(";");
7623            for (int j = 0; j < names.length; j++) {
7624                if (mProvidersByAuthority.get(names[j]) == p) {
7625                    mProvidersByAuthority.remove(names[j]);
7626                    if (DEBUG_REMOVE) {
7627                        if (chatty)
7628                            Log.d(TAG, "Unregistered content provider: " + names[j]
7629                                    + ", className = " + p.info.name + ", isSyncable = "
7630                                    + p.info.isSyncable);
7631                    }
7632                }
7633            }
7634            if (DEBUG_REMOVE && chatty) {
7635                if (r == null) {
7636                    r = new StringBuilder(256);
7637                } else {
7638                    r.append(' ');
7639                }
7640                r.append(p.info.name);
7641            }
7642        }
7643        if (r != null) {
7644            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7645        }
7646
7647        N = pkg.services.size();
7648        r = null;
7649        for (i=0; i<N; i++) {
7650            PackageParser.Service s = pkg.services.get(i);
7651            mServices.removeService(s);
7652            if (chatty) {
7653                if (r == null) {
7654                    r = new StringBuilder(256);
7655                } else {
7656                    r.append(' ');
7657                }
7658                r.append(s.info.name);
7659            }
7660        }
7661        if (r != null) {
7662            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7663        }
7664
7665        N = pkg.receivers.size();
7666        r = null;
7667        for (i=0; i<N; i++) {
7668            PackageParser.Activity a = pkg.receivers.get(i);
7669            mReceivers.removeActivity(a, "receiver");
7670            if (DEBUG_REMOVE && chatty) {
7671                if (r == null) {
7672                    r = new StringBuilder(256);
7673                } else {
7674                    r.append(' ');
7675                }
7676                r.append(a.info.name);
7677            }
7678        }
7679        if (r != null) {
7680            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7681        }
7682
7683        N = pkg.activities.size();
7684        r = null;
7685        for (i=0; i<N; i++) {
7686            PackageParser.Activity a = pkg.activities.get(i);
7687            mActivities.removeActivity(a, "activity");
7688            if (DEBUG_REMOVE && chatty) {
7689                if (r == null) {
7690                    r = new StringBuilder(256);
7691                } else {
7692                    r.append(' ');
7693                }
7694                r.append(a.info.name);
7695            }
7696        }
7697        if (r != null) {
7698            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7699        }
7700
7701        N = pkg.permissions.size();
7702        r = null;
7703        for (i=0; i<N; i++) {
7704            PackageParser.Permission p = pkg.permissions.get(i);
7705            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7706            if (bp == null) {
7707                bp = mSettings.mPermissionTrees.get(p.info.name);
7708            }
7709            if (bp != null && bp.perm == p) {
7710                bp.perm = null;
7711                if (DEBUG_REMOVE && chatty) {
7712                    if (r == null) {
7713                        r = new StringBuilder(256);
7714                    } else {
7715                        r.append(' ');
7716                    }
7717                    r.append(p.info.name);
7718                }
7719            }
7720            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7721                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7722                if (appOpPerms != null) {
7723                    appOpPerms.remove(pkg.packageName);
7724                }
7725            }
7726        }
7727        if (r != null) {
7728            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7729        }
7730
7731        N = pkg.requestedPermissions.size();
7732        r = null;
7733        for (i=0; i<N; i++) {
7734            String perm = pkg.requestedPermissions.get(i);
7735            BasePermission bp = mSettings.mPermissions.get(perm);
7736            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7737                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7738                if (appOpPerms != null) {
7739                    appOpPerms.remove(pkg.packageName);
7740                    if (appOpPerms.isEmpty()) {
7741                        mAppOpPermissionPackages.remove(perm);
7742                    }
7743                }
7744            }
7745        }
7746        if (r != null) {
7747            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7748        }
7749
7750        N = pkg.instrumentation.size();
7751        r = null;
7752        for (i=0; i<N; i++) {
7753            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7754            mInstrumentation.remove(a.getComponentName());
7755            if (DEBUG_REMOVE && chatty) {
7756                if (r == null) {
7757                    r = new StringBuilder(256);
7758                } else {
7759                    r.append(' ');
7760                }
7761                r.append(a.info.name);
7762            }
7763        }
7764        if (r != null) {
7765            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7766        }
7767
7768        r = null;
7769        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7770            // Only system apps can hold shared libraries.
7771            if (pkg.libraryNames != null) {
7772                for (i=0; i<pkg.libraryNames.size(); i++) {
7773                    String name = pkg.libraryNames.get(i);
7774                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7775                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7776                        mSharedLibraries.remove(name);
7777                        if (DEBUG_REMOVE && chatty) {
7778                            if (r == null) {
7779                                r = new StringBuilder(256);
7780                            } else {
7781                                r.append(' ');
7782                            }
7783                            r.append(name);
7784                        }
7785                    }
7786                }
7787            }
7788        }
7789        if (r != null) {
7790            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7791        }
7792    }
7793
7794    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7795        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7796            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7797                return true;
7798            }
7799        }
7800        return false;
7801    }
7802
7803    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7804    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7805    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7806
7807    private void updatePermissionsLPw(String changingPkg,
7808            PackageParser.Package pkgInfo, int flags) {
7809        // Make sure there are no dangling permission trees.
7810        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7811        while (it.hasNext()) {
7812            final BasePermission bp = it.next();
7813            if (bp.packageSetting == null) {
7814                // We may not yet have parsed the package, so just see if
7815                // we still know about its settings.
7816                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7817            }
7818            if (bp.packageSetting == null) {
7819                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7820                        + " from package " + bp.sourcePackage);
7821                it.remove();
7822            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7823                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7824                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7825                            + " from package " + bp.sourcePackage);
7826                    flags |= UPDATE_PERMISSIONS_ALL;
7827                    it.remove();
7828                }
7829            }
7830        }
7831
7832        // Make sure all dynamic permissions have been assigned to a package,
7833        // and make sure there are no dangling permissions.
7834        it = mSettings.mPermissions.values().iterator();
7835        while (it.hasNext()) {
7836            final BasePermission bp = it.next();
7837            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7838                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7839                        + bp.name + " pkg=" + bp.sourcePackage
7840                        + " info=" + bp.pendingInfo);
7841                if (bp.packageSetting == null && bp.pendingInfo != null) {
7842                    final BasePermission tree = findPermissionTreeLP(bp.name);
7843                    if (tree != null && tree.perm != null) {
7844                        bp.packageSetting = tree.packageSetting;
7845                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7846                                new PermissionInfo(bp.pendingInfo));
7847                        bp.perm.info.packageName = tree.perm.info.packageName;
7848                        bp.perm.info.name = bp.name;
7849                        bp.uid = tree.uid;
7850                    }
7851                }
7852            }
7853            if (bp.packageSetting == null) {
7854                // We may not yet have parsed the package, so just see if
7855                // we still know about its settings.
7856                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7857            }
7858            if (bp.packageSetting == null) {
7859                Slog.w(TAG, "Removing dangling permission: " + bp.name
7860                        + " from package " + bp.sourcePackage);
7861                it.remove();
7862            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7863                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7864                    Slog.i(TAG, "Removing old permission: " + bp.name
7865                            + " from package " + bp.sourcePackage);
7866                    flags |= UPDATE_PERMISSIONS_ALL;
7867                    it.remove();
7868                }
7869            }
7870        }
7871
7872        // Now update the permissions for all packages, in particular
7873        // replace the granted permissions of the system packages.
7874        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7875            for (PackageParser.Package pkg : mPackages.values()) {
7876                if (pkg != pkgInfo) {
7877                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7878                            changingPkg);
7879                }
7880            }
7881        }
7882
7883        if (pkgInfo != null) {
7884            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7885        }
7886    }
7887
7888    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7889            String packageOfInterest) {
7890        // IMPORTANT: There are two types of permissions: install and runtime.
7891        // Install time permissions are granted when the app is installed to
7892        // all device users and users added in the future. Runtime permissions
7893        // are granted at runtime explicitly to specific users. Normal and signature
7894        // protected permissions are install time permissions. Dangerous permissions
7895        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7896        // otherwise they are runtime permissions. This function does not manage
7897        // runtime permissions except for the case an app targeting Lollipop MR1
7898        // being upgraded to target a newer SDK, in which case dangerous permissions
7899        // are transformed from install time to runtime ones.
7900
7901        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7902        if (ps == null) {
7903            return;
7904        }
7905
7906        PermissionsState permissionsState = ps.getPermissionsState();
7907        PermissionsState origPermissions = permissionsState;
7908
7909        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7910
7911        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7912
7913        boolean changedInstallPermission = false;
7914
7915        if (replace) {
7916            ps.installPermissionsFixed = false;
7917            if (!ps.isSharedUser()) {
7918                origPermissions = new PermissionsState(permissionsState);
7919                permissionsState.reset();
7920            }
7921        }
7922
7923        permissionsState.setGlobalGids(mGlobalGids);
7924
7925        final int N = pkg.requestedPermissions.size();
7926        for (int i=0; i<N; i++) {
7927            final String name = pkg.requestedPermissions.get(i);
7928            final BasePermission bp = mSettings.mPermissions.get(name);
7929
7930            if (DEBUG_INSTALL) {
7931                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7932            }
7933
7934            if (bp == null || bp.packageSetting == null) {
7935                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7936                    Slog.w(TAG, "Unknown permission " + name
7937                            + " in package " + pkg.packageName);
7938                }
7939                continue;
7940            }
7941
7942            final String perm = bp.name;
7943            boolean allowedSig = false;
7944            int grant = GRANT_DENIED;
7945
7946            // Keep track of app op permissions.
7947            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7948                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7949                if (pkgs == null) {
7950                    pkgs = new ArraySet<>();
7951                    mAppOpPermissionPackages.put(bp.name, pkgs);
7952                }
7953                pkgs.add(pkg.packageName);
7954            }
7955
7956            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7957            switch (level) {
7958                case PermissionInfo.PROTECTION_NORMAL: {
7959                    // For all apps normal permissions are install time ones.
7960                    grant = GRANT_INSTALL;
7961                } break;
7962
7963                case PermissionInfo.PROTECTION_DANGEROUS: {
7964                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7965                        // For legacy apps dangerous permissions are install time ones.
7966                        grant = GRANT_INSTALL_LEGACY;
7967                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7968                        // For legacy apps that became modern, install becomes runtime.
7969                        grant = GRANT_UPGRADE;
7970                    } else {
7971                        // For modern apps keep runtime permissions unchanged.
7972                        grant = GRANT_RUNTIME;
7973                    }
7974                } break;
7975
7976                case PermissionInfo.PROTECTION_SIGNATURE: {
7977                    // For all apps signature permissions are install time ones.
7978                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7979                    if (allowedSig) {
7980                        grant = GRANT_INSTALL;
7981                    }
7982                } break;
7983            }
7984
7985            if (DEBUG_INSTALL) {
7986                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7987            }
7988
7989            if (grant != GRANT_DENIED) {
7990                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7991                    // If this is an existing, non-system package, then
7992                    // we can't add any new permissions to it.
7993                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7994                        // Except...  if this is a permission that was added
7995                        // to the platform (note: need to only do this when
7996                        // updating the platform).
7997                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7998                            grant = GRANT_DENIED;
7999                        }
8000                    }
8001                }
8002
8003                switch (grant) {
8004                    case GRANT_INSTALL: {
8005                        // Revoke this as runtime permission to handle the case of
8006                        // a runtime permission being downgraded to an install one.
8007                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8008                            if (origPermissions.getRuntimePermissionState(
8009                                    bp.name, userId) != null) {
8010                                // Revoke the runtime permission and clear the flags.
8011                                origPermissions.revokeRuntimePermission(bp, userId);
8012                                origPermissions.updatePermissionFlags(bp, userId,
8013                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8014                                // If we revoked a permission permission, we have to write.
8015                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8016                                        changedRuntimePermissionUserIds, userId);
8017                            }
8018                        }
8019                        // Grant an install permission.
8020                        if (permissionsState.grantInstallPermission(bp) !=
8021                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8022                            changedInstallPermission = true;
8023                        }
8024                    } break;
8025
8026                    case GRANT_INSTALL_LEGACY: {
8027                        // Grant an install permission.
8028                        if (permissionsState.grantInstallPermission(bp) !=
8029                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8030                            changedInstallPermission = true;
8031                        }
8032                    } break;
8033
8034                    case GRANT_RUNTIME: {
8035                        // Grant previously granted runtime permissions.
8036                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8037                            PermissionState permissionState = origPermissions
8038                                    .getRuntimePermissionState(bp.name, userId);
8039                            final int flags = permissionState != null
8040                                    ? permissionState.getFlags() : 0;
8041                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8042                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8043                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8044                                    // If we cannot put the permission as it was, we have to write.
8045                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8046                                            changedRuntimePermissionUserIds, userId);
8047                                }
8048                            }
8049                            // Propagate the permission flags.
8050                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8051                        }
8052                    } break;
8053
8054                    case GRANT_UPGRADE: {
8055                        // Grant runtime permissions for a previously held install permission.
8056                        PermissionState permissionState = origPermissions
8057                                .getInstallPermissionState(bp.name);
8058                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8059
8060                        if (origPermissions.revokeInstallPermission(bp)
8061                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8062                            // We will be transferring the permission flags, so clear them.
8063                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8064                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8065                            changedInstallPermission = true;
8066                        }
8067
8068                        // If the permission is not to be promoted to runtime we ignore it and
8069                        // also its other flags as they are not applicable to install permissions.
8070                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8071                            for (int userId : currentUserIds) {
8072                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8073                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8074                                    // Transfer the permission flags.
8075                                    permissionsState.updatePermissionFlags(bp, userId,
8076                                            flags, flags);
8077                                    // If we granted the permission, we have to write.
8078                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8079                                            changedRuntimePermissionUserIds, userId);
8080                                }
8081                            }
8082                        }
8083                    } break;
8084
8085                    default: {
8086                        if (packageOfInterest == null
8087                                || packageOfInterest.equals(pkg.packageName)) {
8088                            Slog.w(TAG, "Not granting permission " + perm
8089                                    + " to package " + pkg.packageName
8090                                    + " because it was previously installed without");
8091                        }
8092                    } break;
8093                }
8094            } else {
8095                if (permissionsState.revokeInstallPermission(bp) !=
8096                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8097                    // Also drop the permission flags.
8098                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8099                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8100                    changedInstallPermission = true;
8101                    Slog.i(TAG, "Un-granting permission " + perm
8102                            + " from package " + pkg.packageName
8103                            + " (protectionLevel=" + bp.protectionLevel
8104                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8105                            + ")");
8106                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8107                    // Don't print warning for app op permissions, since it is fine for them
8108                    // not to be granted, there is a UI for the user to decide.
8109                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8110                        Slog.w(TAG, "Not granting permission " + perm
8111                                + " to package " + pkg.packageName
8112                                + " (protectionLevel=" + bp.protectionLevel
8113                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8114                                + ")");
8115                    }
8116                }
8117            }
8118        }
8119
8120        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8121                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8122            // This is the first that we have heard about this package, so the
8123            // permissions we have now selected are fixed until explicitly
8124            // changed.
8125            ps.installPermissionsFixed = true;
8126        }
8127
8128        // Persist the runtime permissions state for users with changes.
8129        for (int userId : changedRuntimePermissionUserIds) {
8130            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8131        }
8132    }
8133
8134    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8135        boolean allowed = false;
8136        final int NP = PackageParser.NEW_PERMISSIONS.length;
8137        for (int ip=0; ip<NP; ip++) {
8138            final PackageParser.NewPermissionInfo npi
8139                    = PackageParser.NEW_PERMISSIONS[ip];
8140            if (npi.name.equals(perm)
8141                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8142                allowed = true;
8143                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8144                        + pkg.packageName);
8145                break;
8146            }
8147        }
8148        return allowed;
8149    }
8150
8151    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8152            BasePermission bp, PermissionsState origPermissions) {
8153        boolean allowed;
8154        allowed = (compareSignatures(
8155                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8156                        == PackageManager.SIGNATURE_MATCH)
8157                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8158                        == PackageManager.SIGNATURE_MATCH);
8159        if (!allowed && (bp.protectionLevel
8160                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8161            if (isSystemApp(pkg)) {
8162                // For updated system applications, a system permission
8163                // is granted only if it had been defined by the original application.
8164                if (pkg.isUpdatedSystemApp()) {
8165                    final PackageSetting sysPs = mSettings
8166                            .getDisabledSystemPkgLPr(pkg.packageName);
8167                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8168                        // If the original was granted this permission, we take
8169                        // that grant decision as read and propagate it to the
8170                        // update.
8171                        if (sysPs.isPrivileged()) {
8172                            allowed = true;
8173                        }
8174                    } else {
8175                        // The system apk may have been updated with an older
8176                        // version of the one on the data partition, but which
8177                        // granted a new system permission that it didn't have
8178                        // before.  In this case we do want to allow the app to
8179                        // now get the new permission if the ancestral apk is
8180                        // privileged to get it.
8181                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8182                            for (int j=0;
8183                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8184                                if (perm.equals(
8185                                        sysPs.pkg.requestedPermissions.get(j))) {
8186                                    allowed = true;
8187                                    break;
8188                                }
8189                            }
8190                        }
8191                    }
8192                } else {
8193                    allowed = isPrivilegedApp(pkg);
8194                }
8195            }
8196        }
8197        if (!allowed && (bp.protectionLevel
8198                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8199            // For development permissions, a development permission
8200            // is granted only if it was already granted.
8201            allowed = origPermissions.hasInstallPermission(perm);
8202        }
8203        return allowed;
8204    }
8205
8206    final class ActivityIntentResolver
8207            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8208        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8209                boolean defaultOnly, int userId) {
8210            if (!sUserManager.exists(userId)) return null;
8211            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8212            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8213        }
8214
8215        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8216                int userId) {
8217            if (!sUserManager.exists(userId)) return null;
8218            mFlags = flags;
8219            return super.queryIntent(intent, resolvedType,
8220                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8221        }
8222
8223        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8224                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8225            if (!sUserManager.exists(userId)) return null;
8226            if (packageActivities == null) {
8227                return null;
8228            }
8229            mFlags = flags;
8230            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8231            final int N = packageActivities.size();
8232            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8233                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8234
8235            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8236            for (int i = 0; i < N; ++i) {
8237                intentFilters = packageActivities.get(i).intents;
8238                if (intentFilters != null && intentFilters.size() > 0) {
8239                    PackageParser.ActivityIntentInfo[] array =
8240                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8241                    intentFilters.toArray(array);
8242                    listCut.add(array);
8243                }
8244            }
8245            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8246        }
8247
8248        public final void addActivity(PackageParser.Activity a, String type) {
8249            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8250            mActivities.put(a.getComponentName(), a);
8251            if (DEBUG_SHOW_INFO)
8252                Log.v(
8253                TAG, "  " + type + " " +
8254                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8255            if (DEBUG_SHOW_INFO)
8256                Log.v(TAG, "    Class=" + a.info.name);
8257            final int NI = a.intents.size();
8258            for (int j=0; j<NI; j++) {
8259                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8260                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8261                    intent.setPriority(0);
8262                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8263                            + a.className + " with priority > 0, forcing to 0");
8264                }
8265                if (DEBUG_SHOW_INFO) {
8266                    Log.v(TAG, "    IntentFilter:");
8267                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8268                }
8269                if (!intent.debugCheck()) {
8270                    Log.w(TAG, "==> For Activity " + a.info.name);
8271                }
8272                addFilter(intent);
8273            }
8274        }
8275
8276        public final void removeActivity(PackageParser.Activity a, String type) {
8277            mActivities.remove(a.getComponentName());
8278            if (DEBUG_SHOW_INFO) {
8279                Log.v(TAG, "  " + type + " "
8280                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8281                                : a.info.name) + ":");
8282                Log.v(TAG, "    Class=" + a.info.name);
8283            }
8284            final int NI = a.intents.size();
8285            for (int j=0; j<NI; j++) {
8286                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8287                if (DEBUG_SHOW_INFO) {
8288                    Log.v(TAG, "    IntentFilter:");
8289                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8290                }
8291                removeFilter(intent);
8292            }
8293        }
8294
8295        @Override
8296        protected boolean allowFilterResult(
8297                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8298            ActivityInfo filterAi = filter.activity.info;
8299            for (int i=dest.size()-1; i>=0; i--) {
8300                ActivityInfo destAi = dest.get(i).activityInfo;
8301                if (destAi.name == filterAi.name
8302                        && destAi.packageName == filterAi.packageName) {
8303                    return false;
8304                }
8305            }
8306            return true;
8307        }
8308
8309        @Override
8310        protected ActivityIntentInfo[] newArray(int size) {
8311            return new ActivityIntentInfo[size];
8312        }
8313
8314        @Override
8315        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8316            if (!sUserManager.exists(userId)) return true;
8317            PackageParser.Package p = filter.activity.owner;
8318            if (p != null) {
8319                PackageSetting ps = (PackageSetting)p.mExtras;
8320                if (ps != null) {
8321                    // System apps are never considered stopped for purposes of
8322                    // filtering, because there may be no way for the user to
8323                    // actually re-launch them.
8324                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8325                            && ps.getStopped(userId);
8326                }
8327            }
8328            return false;
8329        }
8330
8331        @Override
8332        protected boolean isPackageForFilter(String packageName,
8333                PackageParser.ActivityIntentInfo info) {
8334            return packageName.equals(info.activity.owner.packageName);
8335        }
8336
8337        @Override
8338        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8339                int match, int userId) {
8340            if (!sUserManager.exists(userId)) return null;
8341            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8342                return null;
8343            }
8344            final PackageParser.Activity activity = info.activity;
8345            if (mSafeMode && (activity.info.applicationInfo.flags
8346                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8347                return null;
8348            }
8349            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8350            if (ps == null) {
8351                return null;
8352            }
8353            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8354                    ps.readUserState(userId), userId);
8355            if (ai == null) {
8356                return null;
8357            }
8358            final ResolveInfo res = new ResolveInfo();
8359            res.activityInfo = ai;
8360            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8361                res.filter = info;
8362            }
8363            if (info != null) {
8364                res.handleAllWebDataURI = info.handleAllWebDataURI();
8365            }
8366            res.priority = info.getPriority();
8367            res.preferredOrder = activity.owner.mPreferredOrder;
8368            //System.out.println("Result: " + res.activityInfo.className +
8369            //                   " = " + res.priority);
8370            res.match = match;
8371            res.isDefault = info.hasDefault;
8372            res.labelRes = info.labelRes;
8373            res.nonLocalizedLabel = info.nonLocalizedLabel;
8374            if (userNeedsBadging(userId)) {
8375                res.noResourceId = true;
8376            } else {
8377                res.icon = info.icon;
8378            }
8379            res.iconResourceId = info.icon;
8380            res.system = res.activityInfo.applicationInfo.isSystemApp();
8381            return res;
8382        }
8383
8384        @Override
8385        protected void sortResults(List<ResolveInfo> results) {
8386            Collections.sort(results, mResolvePrioritySorter);
8387        }
8388
8389        @Override
8390        protected void dumpFilter(PrintWriter out, String prefix,
8391                PackageParser.ActivityIntentInfo filter) {
8392            out.print(prefix); out.print(
8393                    Integer.toHexString(System.identityHashCode(filter.activity)));
8394                    out.print(' ');
8395                    filter.activity.printComponentShortName(out);
8396                    out.print(" filter ");
8397                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8398        }
8399
8400        @Override
8401        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8402            return filter.activity;
8403        }
8404
8405        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8406            PackageParser.Activity activity = (PackageParser.Activity)label;
8407            out.print(prefix); out.print(
8408                    Integer.toHexString(System.identityHashCode(activity)));
8409                    out.print(' ');
8410                    activity.printComponentShortName(out);
8411            if (count > 1) {
8412                out.print(" ("); out.print(count); out.print(" filters)");
8413            }
8414            out.println();
8415        }
8416
8417//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8418//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8419//            final List<ResolveInfo> retList = Lists.newArrayList();
8420//            while (i.hasNext()) {
8421//                final ResolveInfo resolveInfo = i.next();
8422//                if (isEnabledLP(resolveInfo.activityInfo)) {
8423//                    retList.add(resolveInfo);
8424//                }
8425//            }
8426//            return retList;
8427//        }
8428
8429        // Keys are String (activity class name), values are Activity.
8430        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8431                = new ArrayMap<ComponentName, PackageParser.Activity>();
8432        private int mFlags;
8433    }
8434
8435    private final class ServiceIntentResolver
8436            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8437        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8438                boolean defaultOnly, int userId) {
8439            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8440            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8441        }
8442
8443        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8444                int userId) {
8445            if (!sUserManager.exists(userId)) return null;
8446            mFlags = flags;
8447            return super.queryIntent(intent, resolvedType,
8448                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8449        }
8450
8451        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8452                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8453            if (!sUserManager.exists(userId)) return null;
8454            if (packageServices == null) {
8455                return null;
8456            }
8457            mFlags = flags;
8458            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8459            final int N = packageServices.size();
8460            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8461                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8462
8463            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8464            for (int i = 0; i < N; ++i) {
8465                intentFilters = packageServices.get(i).intents;
8466                if (intentFilters != null && intentFilters.size() > 0) {
8467                    PackageParser.ServiceIntentInfo[] array =
8468                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8469                    intentFilters.toArray(array);
8470                    listCut.add(array);
8471                }
8472            }
8473            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8474        }
8475
8476        public final void addService(PackageParser.Service s) {
8477            mServices.put(s.getComponentName(), s);
8478            if (DEBUG_SHOW_INFO) {
8479                Log.v(TAG, "  "
8480                        + (s.info.nonLocalizedLabel != null
8481                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8482                Log.v(TAG, "    Class=" + s.info.name);
8483            }
8484            final int NI = s.intents.size();
8485            int j;
8486            for (j=0; j<NI; j++) {
8487                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8488                if (DEBUG_SHOW_INFO) {
8489                    Log.v(TAG, "    IntentFilter:");
8490                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8491                }
8492                if (!intent.debugCheck()) {
8493                    Log.w(TAG, "==> For Service " + s.info.name);
8494                }
8495                addFilter(intent);
8496            }
8497        }
8498
8499        public final void removeService(PackageParser.Service s) {
8500            mServices.remove(s.getComponentName());
8501            if (DEBUG_SHOW_INFO) {
8502                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8503                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8504                Log.v(TAG, "    Class=" + s.info.name);
8505            }
8506            final int NI = s.intents.size();
8507            int j;
8508            for (j=0; j<NI; j++) {
8509                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8510                if (DEBUG_SHOW_INFO) {
8511                    Log.v(TAG, "    IntentFilter:");
8512                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8513                }
8514                removeFilter(intent);
8515            }
8516        }
8517
8518        @Override
8519        protected boolean allowFilterResult(
8520                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8521            ServiceInfo filterSi = filter.service.info;
8522            for (int i=dest.size()-1; i>=0; i--) {
8523                ServiceInfo destAi = dest.get(i).serviceInfo;
8524                if (destAi.name == filterSi.name
8525                        && destAi.packageName == filterSi.packageName) {
8526                    return false;
8527                }
8528            }
8529            return true;
8530        }
8531
8532        @Override
8533        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8534            return new PackageParser.ServiceIntentInfo[size];
8535        }
8536
8537        @Override
8538        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8539            if (!sUserManager.exists(userId)) return true;
8540            PackageParser.Package p = filter.service.owner;
8541            if (p != null) {
8542                PackageSetting ps = (PackageSetting)p.mExtras;
8543                if (ps != null) {
8544                    // System apps are never considered stopped for purposes of
8545                    // filtering, because there may be no way for the user to
8546                    // actually re-launch them.
8547                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8548                            && ps.getStopped(userId);
8549                }
8550            }
8551            return false;
8552        }
8553
8554        @Override
8555        protected boolean isPackageForFilter(String packageName,
8556                PackageParser.ServiceIntentInfo info) {
8557            return packageName.equals(info.service.owner.packageName);
8558        }
8559
8560        @Override
8561        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8562                int match, int userId) {
8563            if (!sUserManager.exists(userId)) return null;
8564            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8565            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8566                return null;
8567            }
8568            final PackageParser.Service service = info.service;
8569            if (mSafeMode && (service.info.applicationInfo.flags
8570                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8571                return null;
8572            }
8573            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8574            if (ps == null) {
8575                return null;
8576            }
8577            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8578                    ps.readUserState(userId), userId);
8579            if (si == null) {
8580                return null;
8581            }
8582            final ResolveInfo res = new ResolveInfo();
8583            res.serviceInfo = si;
8584            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8585                res.filter = filter;
8586            }
8587            res.priority = info.getPriority();
8588            res.preferredOrder = service.owner.mPreferredOrder;
8589            res.match = match;
8590            res.isDefault = info.hasDefault;
8591            res.labelRes = info.labelRes;
8592            res.nonLocalizedLabel = info.nonLocalizedLabel;
8593            res.icon = info.icon;
8594            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8595            return res;
8596        }
8597
8598        @Override
8599        protected void sortResults(List<ResolveInfo> results) {
8600            Collections.sort(results, mResolvePrioritySorter);
8601        }
8602
8603        @Override
8604        protected void dumpFilter(PrintWriter out, String prefix,
8605                PackageParser.ServiceIntentInfo filter) {
8606            out.print(prefix); out.print(
8607                    Integer.toHexString(System.identityHashCode(filter.service)));
8608                    out.print(' ');
8609                    filter.service.printComponentShortName(out);
8610                    out.print(" filter ");
8611                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8612        }
8613
8614        @Override
8615        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8616            return filter.service;
8617        }
8618
8619        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8620            PackageParser.Service service = (PackageParser.Service)label;
8621            out.print(prefix); out.print(
8622                    Integer.toHexString(System.identityHashCode(service)));
8623                    out.print(' ');
8624                    service.printComponentShortName(out);
8625            if (count > 1) {
8626                out.print(" ("); out.print(count); out.print(" filters)");
8627            }
8628            out.println();
8629        }
8630
8631//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8632//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8633//            final List<ResolveInfo> retList = Lists.newArrayList();
8634//            while (i.hasNext()) {
8635//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8636//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8637//                    retList.add(resolveInfo);
8638//                }
8639//            }
8640//            return retList;
8641//        }
8642
8643        // Keys are String (activity class name), values are Activity.
8644        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8645                = new ArrayMap<ComponentName, PackageParser.Service>();
8646        private int mFlags;
8647    };
8648
8649    private final class ProviderIntentResolver
8650            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8651        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8652                boolean defaultOnly, int userId) {
8653            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8654            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8655        }
8656
8657        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8658                int userId) {
8659            if (!sUserManager.exists(userId))
8660                return null;
8661            mFlags = flags;
8662            return super.queryIntent(intent, resolvedType,
8663                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8664        }
8665
8666        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8667                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8668            if (!sUserManager.exists(userId))
8669                return null;
8670            if (packageProviders == null) {
8671                return null;
8672            }
8673            mFlags = flags;
8674            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8675            final int N = packageProviders.size();
8676            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8677                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8678
8679            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8680            for (int i = 0; i < N; ++i) {
8681                intentFilters = packageProviders.get(i).intents;
8682                if (intentFilters != null && intentFilters.size() > 0) {
8683                    PackageParser.ProviderIntentInfo[] array =
8684                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8685                    intentFilters.toArray(array);
8686                    listCut.add(array);
8687                }
8688            }
8689            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8690        }
8691
8692        public final void addProvider(PackageParser.Provider p) {
8693            if (mProviders.containsKey(p.getComponentName())) {
8694                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8695                return;
8696            }
8697
8698            mProviders.put(p.getComponentName(), p);
8699            if (DEBUG_SHOW_INFO) {
8700                Log.v(TAG, "  "
8701                        + (p.info.nonLocalizedLabel != null
8702                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8703                Log.v(TAG, "    Class=" + p.info.name);
8704            }
8705            final int NI = p.intents.size();
8706            int j;
8707            for (j = 0; j < NI; j++) {
8708                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8709                if (DEBUG_SHOW_INFO) {
8710                    Log.v(TAG, "    IntentFilter:");
8711                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8712                }
8713                if (!intent.debugCheck()) {
8714                    Log.w(TAG, "==> For Provider " + p.info.name);
8715                }
8716                addFilter(intent);
8717            }
8718        }
8719
8720        public final void removeProvider(PackageParser.Provider p) {
8721            mProviders.remove(p.getComponentName());
8722            if (DEBUG_SHOW_INFO) {
8723                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8724                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8725                Log.v(TAG, "    Class=" + p.info.name);
8726            }
8727            final int NI = p.intents.size();
8728            int j;
8729            for (j = 0; j < NI; j++) {
8730                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8731                if (DEBUG_SHOW_INFO) {
8732                    Log.v(TAG, "    IntentFilter:");
8733                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8734                }
8735                removeFilter(intent);
8736            }
8737        }
8738
8739        @Override
8740        protected boolean allowFilterResult(
8741                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8742            ProviderInfo filterPi = filter.provider.info;
8743            for (int i = dest.size() - 1; i >= 0; i--) {
8744                ProviderInfo destPi = dest.get(i).providerInfo;
8745                if (destPi.name == filterPi.name
8746                        && destPi.packageName == filterPi.packageName) {
8747                    return false;
8748                }
8749            }
8750            return true;
8751        }
8752
8753        @Override
8754        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8755            return new PackageParser.ProviderIntentInfo[size];
8756        }
8757
8758        @Override
8759        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8760            if (!sUserManager.exists(userId))
8761                return true;
8762            PackageParser.Package p = filter.provider.owner;
8763            if (p != null) {
8764                PackageSetting ps = (PackageSetting) p.mExtras;
8765                if (ps != null) {
8766                    // System apps are never considered stopped for purposes of
8767                    // filtering, because there may be no way for the user to
8768                    // actually re-launch them.
8769                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8770                            && ps.getStopped(userId);
8771                }
8772            }
8773            return false;
8774        }
8775
8776        @Override
8777        protected boolean isPackageForFilter(String packageName,
8778                PackageParser.ProviderIntentInfo info) {
8779            return packageName.equals(info.provider.owner.packageName);
8780        }
8781
8782        @Override
8783        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8784                int match, int userId) {
8785            if (!sUserManager.exists(userId))
8786                return null;
8787            final PackageParser.ProviderIntentInfo info = filter;
8788            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8789                return null;
8790            }
8791            final PackageParser.Provider provider = info.provider;
8792            if (mSafeMode && (provider.info.applicationInfo.flags
8793                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8794                return null;
8795            }
8796            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8797            if (ps == null) {
8798                return null;
8799            }
8800            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8801                    ps.readUserState(userId), userId);
8802            if (pi == null) {
8803                return null;
8804            }
8805            final ResolveInfo res = new ResolveInfo();
8806            res.providerInfo = pi;
8807            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8808                res.filter = filter;
8809            }
8810            res.priority = info.getPriority();
8811            res.preferredOrder = provider.owner.mPreferredOrder;
8812            res.match = match;
8813            res.isDefault = info.hasDefault;
8814            res.labelRes = info.labelRes;
8815            res.nonLocalizedLabel = info.nonLocalizedLabel;
8816            res.icon = info.icon;
8817            res.system = res.providerInfo.applicationInfo.isSystemApp();
8818            return res;
8819        }
8820
8821        @Override
8822        protected void sortResults(List<ResolveInfo> results) {
8823            Collections.sort(results, mResolvePrioritySorter);
8824        }
8825
8826        @Override
8827        protected void dumpFilter(PrintWriter out, String prefix,
8828                PackageParser.ProviderIntentInfo filter) {
8829            out.print(prefix);
8830            out.print(
8831                    Integer.toHexString(System.identityHashCode(filter.provider)));
8832            out.print(' ');
8833            filter.provider.printComponentShortName(out);
8834            out.print(" filter ");
8835            out.println(Integer.toHexString(System.identityHashCode(filter)));
8836        }
8837
8838        @Override
8839        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8840            return filter.provider;
8841        }
8842
8843        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8844            PackageParser.Provider provider = (PackageParser.Provider)label;
8845            out.print(prefix); out.print(
8846                    Integer.toHexString(System.identityHashCode(provider)));
8847                    out.print(' ');
8848                    provider.printComponentShortName(out);
8849            if (count > 1) {
8850                out.print(" ("); out.print(count); out.print(" filters)");
8851            }
8852            out.println();
8853        }
8854
8855        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8856                = new ArrayMap<ComponentName, PackageParser.Provider>();
8857        private int mFlags;
8858    };
8859
8860    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8861            new Comparator<ResolveInfo>() {
8862        public int compare(ResolveInfo r1, ResolveInfo r2) {
8863            int v1 = r1.priority;
8864            int v2 = r2.priority;
8865            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8866            if (v1 != v2) {
8867                return (v1 > v2) ? -1 : 1;
8868            }
8869            v1 = r1.preferredOrder;
8870            v2 = r2.preferredOrder;
8871            if (v1 != v2) {
8872                return (v1 > v2) ? -1 : 1;
8873            }
8874            if (r1.isDefault != r2.isDefault) {
8875                return r1.isDefault ? -1 : 1;
8876            }
8877            v1 = r1.match;
8878            v2 = r2.match;
8879            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8880            if (v1 != v2) {
8881                return (v1 > v2) ? -1 : 1;
8882            }
8883            if (r1.system != r2.system) {
8884                return r1.system ? -1 : 1;
8885            }
8886            return 0;
8887        }
8888    };
8889
8890    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8891            new Comparator<ProviderInfo>() {
8892        public int compare(ProviderInfo p1, ProviderInfo p2) {
8893            final int v1 = p1.initOrder;
8894            final int v2 = p2.initOrder;
8895            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8896        }
8897    };
8898
8899    final void sendPackageBroadcast(final String action, final String pkg,
8900            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8901            final int[] userIds) {
8902        mHandler.post(new Runnable() {
8903            @Override
8904            public void run() {
8905                try {
8906                    final IActivityManager am = ActivityManagerNative.getDefault();
8907                    if (am == null) return;
8908                    final int[] resolvedUserIds;
8909                    if (userIds == null) {
8910                        resolvedUserIds = am.getRunningUserIds();
8911                    } else {
8912                        resolvedUserIds = userIds;
8913                    }
8914                    for (int id : resolvedUserIds) {
8915                        final Intent intent = new Intent(action,
8916                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8917                        if (extras != null) {
8918                            intent.putExtras(extras);
8919                        }
8920                        if (targetPkg != null) {
8921                            intent.setPackage(targetPkg);
8922                        }
8923                        // Modify the UID when posting to other users
8924                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8925                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8926                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8927                            intent.putExtra(Intent.EXTRA_UID, uid);
8928                        }
8929                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8930                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8931                        if (DEBUG_BROADCASTS) {
8932                            RuntimeException here = new RuntimeException("here");
8933                            here.fillInStackTrace();
8934                            Slog.d(TAG, "Sending to user " + id + ": "
8935                                    + intent.toShortString(false, true, false, false)
8936                                    + " " + intent.getExtras(), here);
8937                        }
8938                        am.broadcastIntent(null, intent, null, finishedReceiver,
8939                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8940                                null, finishedReceiver != null, false, id);
8941                    }
8942                } catch (RemoteException ex) {
8943                }
8944            }
8945        });
8946    }
8947
8948    /**
8949     * Check if the external storage media is available. This is true if there
8950     * is a mounted external storage medium or if the external storage is
8951     * emulated.
8952     */
8953    private boolean isExternalMediaAvailable() {
8954        return mMediaMounted || Environment.isExternalStorageEmulated();
8955    }
8956
8957    @Override
8958    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8959        // writer
8960        synchronized (mPackages) {
8961            if (!isExternalMediaAvailable()) {
8962                // If the external storage is no longer mounted at this point,
8963                // the caller may not have been able to delete all of this
8964                // packages files and can not delete any more.  Bail.
8965                return null;
8966            }
8967            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8968            if (lastPackage != null) {
8969                pkgs.remove(lastPackage);
8970            }
8971            if (pkgs.size() > 0) {
8972                return pkgs.get(0);
8973            }
8974        }
8975        return null;
8976    }
8977
8978    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8979        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8980                userId, andCode ? 1 : 0, packageName);
8981        if (mSystemReady) {
8982            msg.sendToTarget();
8983        } else {
8984            if (mPostSystemReadyMessages == null) {
8985                mPostSystemReadyMessages = new ArrayList<>();
8986            }
8987            mPostSystemReadyMessages.add(msg);
8988        }
8989    }
8990
8991    void startCleaningPackages() {
8992        // reader
8993        synchronized (mPackages) {
8994            if (!isExternalMediaAvailable()) {
8995                return;
8996            }
8997            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8998                return;
8999            }
9000        }
9001        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9002        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9003        IActivityManager am = ActivityManagerNative.getDefault();
9004        if (am != null) {
9005            try {
9006                am.startService(null, intent, null, UserHandle.USER_OWNER);
9007            } catch (RemoteException e) {
9008            }
9009        }
9010    }
9011
9012    @Override
9013    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9014            int installFlags, String installerPackageName, VerificationParams verificationParams,
9015            String packageAbiOverride) {
9016        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9017                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9018    }
9019
9020    @Override
9021    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9022            int installFlags, String installerPackageName, VerificationParams verificationParams,
9023            String packageAbiOverride, int userId) {
9024        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9025
9026        final int callingUid = Binder.getCallingUid();
9027        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9028
9029        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9030            try {
9031                if (observer != null) {
9032                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9033                }
9034            } catch (RemoteException re) {
9035            }
9036            return;
9037        }
9038
9039        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9040            installFlags |= PackageManager.INSTALL_FROM_ADB;
9041
9042        } else {
9043            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9044            // about installerPackageName.
9045
9046            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9047            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9048        }
9049
9050        UserHandle user;
9051        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9052            user = UserHandle.ALL;
9053        } else {
9054            user = new UserHandle(userId);
9055        }
9056
9057        // Only system components can circumvent runtime permissions when installing.
9058        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9059                && mContext.checkCallingOrSelfPermission(Manifest.permission
9060                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9061            throw new SecurityException("You need the "
9062                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9063                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9064        }
9065
9066        verificationParams.setInstallerUid(callingUid);
9067
9068        final File originFile = new File(originPath);
9069        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9070
9071        final Message msg = mHandler.obtainMessage(INIT_COPY);
9072        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9073                null, verificationParams, user, packageAbiOverride);
9074        mHandler.sendMessage(msg);
9075    }
9076
9077    void installStage(String packageName, File stagedDir, String stagedCid,
9078            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9079            String installerPackageName, int installerUid, UserHandle user) {
9080        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9081                params.referrerUri, installerUid, null);
9082        verifParams.setInstallerUid(installerUid);
9083
9084        final OriginInfo origin;
9085        if (stagedDir != null) {
9086            origin = OriginInfo.fromStagedFile(stagedDir);
9087        } else {
9088            origin = OriginInfo.fromStagedContainer(stagedCid);
9089        }
9090
9091        final Message msg = mHandler.obtainMessage(INIT_COPY);
9092        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9093                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9094        mHandler.sendMessage(msg);
9095    }
9096
9097    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9098        Bundle extras = new Bundle(1);
9099        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9100
9101        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9102                packageName, extras, null, null, new int[] {userId});
9103        try {
9104            IActivityManager am = ActivityManagerNative.getDefault();
9105            final boolean isSystem =
9106                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9107            if (isSystem && am.isUserRunning(userId, false)) {
9108                // The just-installed/enabled app is bundled on the system, so presumed
9109                // to be able to run automatically without needing an explicit launch.
9110                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9111                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9112                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9113                        .setPackage(packageName);
9114                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9115                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9116            }
9117        } catch (RemoteException e) {
9118            // shouldn't happen
9119            Slog.w(TAG, "Unable to bootstrap installed package", e);
9120        }
9121    }
9122
9123    @Override
9124    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9125            int userId) {
9126        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9127        PackageSetting pkgSetting;
9128        final int uid = Binder.getCallingUid();
9129        enforceCrossUserPermission(uid, userId, true, true,
9130                "setApplicationHiddenSetting for user " + userId);
9131
9132        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9133            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9134            return false;
9135        }
9136
9137        long callingId = Binder.clearCallingIdentity();
9138        try {
9139            boolean sendAdded = false;
9140            boolean sendRemoved = false;
9141            // writer
9142            synchronized (mPackages) {
9143                pkgSetting = mSettings.mPackages.get(packageName);
9144                if (pkgSetting == null) {
9145                    return false;
9146                }
9147                if (pkgSetting.getHidden(userId) != hidden) {
9148                    pkgSetting.setHidden(hidden, userId);
9149                    mSettings.writePackageRestrictionsLPr(userId);
9150                    if (hidden) {
9151                        sendRemoved = true;
9152                    } else {
9153                        sendAdded = true;
9154                    }
9155                }
9156            }
9157            if (sendAdded) {
9158                sendPackageAddedForUser(packageName, pkgSetting, userId);
9159                return true;
9160            }
9161            if (sendRemoved) {
9162                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9163                        "hiding pkg");
9164                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9165            }
9166        } finally {
9167            Binder.restoreCallingIdentity(callingId);
9168        }
9169        return false;
9170    }
9171
9172    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9173            int userId) {
9174        final PackageRemovedInfo info = new PackageRemovedInfo();
9175        info.removedPackage = packageName;
9176        info.removedUsers = new int[] {userId};
9177        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9178        info.sendBroadcast(false, false, false);
9179    }
9180
9181    /**
9182     * Returns true if application is not found or there was an error. Otherwise it returns
9183     * the hidden state of the package for the given user.
9184     */
9185    @Override
9186    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9187        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9188        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9189                false, "getApplicationHidden for user " + userId);
9190        PackageSetting pkgSetting;
9191        long callingId = Binder.clearCallingIdentity();
9192        try {
9193            // writer
9194            synchronized (mPackages) {
9195                pkgSetting = mSettings.mPackages.get(packageName);
9196                if (pkgSetting == null) {
9197                    return true;
9198                }
9199                return pkgSetting.getHidden(userId);
9200            }
9201        } finally {
9202            Binder.restoreCallingIdentity(callingId);
9203        }
9204    }
9205
9206    /**
9207     * @hide
9208     */
9209    @Override
9210    public int installExistingPackageAsUser(String packageName, int userId) {
9211        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9212                null);
9213        PackageSetting pkgSetting;
9214        final int uid = Binder.getCallingUid();
9215        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9216                + userId);
9217        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9218            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9219        }
9220
9221        long callingId = Binder.clearCallingIdentity();
9222        try {
9223            boolean sendAdded = false;
9224
9225            // writer
9226            synchronized (mPackages) {
9227                pkgSetting = mSettings.mPackages.get(packageName);
9228                if (pkgSetting == null) {
9229                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9230                }
9231                if (!pkgSetting.getInstalled(userId)) {
9232                    pkgSetting.setInstalled(true, userId);
9233                    pkgSetting.setHidden(false, userId);
9234                    mSettings.writePackageRestrictionsLPr(userId);
9235                    sendAdded = true;
9236                }
9237            }
9238
9239            if (sendAdded) {
9240                sendPackageAddedForUser(packageName, pkgSetting, userId);
9241            }
9242        } finally {
9243            Binder.restoreCallingIdentity(callingId);
9244        }
9245
9246        return PackageManager.INSTALL_SUCCEEDED;
9247    }
9248
9249    boolean isUserRestricted(int userId, String restrictionKey) {
9250        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9251        if (restrictions.getBoolean(restrictionKey, false)) {
9252            Log.w(TAG, "User is restricted: " + restrictionKey);
9253            return true;
9254        }
9255        return false;
9256    }
9257
9258    @Override
9259    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9260        mContext.enforceCallingOrSelfPermission(
9261                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9262                "Only package verification agents can verify applications");
9263
9264        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9265        final PackageVerificationResponse response = new PackageVerificationResponse(
9266                verificationCode, Binder.getCallingUid());
9267        msg.arg1 = id;
9268        msg.obj = response;
9269        mHandler.sendMessage(msg);
9270    }
9271
9272    @Override
9273    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9274            long millisecondsToDelay) {
9275        mContext.enforceCallingOrSelfPermission(
9276                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9277                "Only package verification agents can extend verification timeouts");
9278
9279        final PackageVerificationState state = mPendingVerification.get(id);
9280        final PackageVerificationResponse response = new PackageVerificationResponse(
9281                verificationCodeAtTimeout, Binder.getCallingUid());
9282
9283        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9284            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9285        }
9286        if (millisecondsToDelay < 0) {
9287            millisecondsToDelay = 0;
9288        }
9289        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9290                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9291            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9292        }
9293
9294        if ((state != null) && !state.timeoutExtended()) {
9295            state.extendTimeout();
9296
9297            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9298            msg.arg1 = id;
9299            msg.obj = response;
9300            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9301        }
9302    }
9303
9304    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9305            int verificationCode, UserHandle user) {
9306        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9307        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9308        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9309        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9310        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9311
9312        mContext.sendBroadcastAsUser(intent, user,
9313                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9314    }
9315
9316    private ComponentName matchComponentForVerifier(String packageName,
9317            List<ResolveInfo> receivers) {
9318        ActivityInfo targetReceiver = null;
9319
9320        final int NR = receivers.size();
9321        for (int i = 0; i < NR; i++) {
9322            final ResolveInfo info = receivers.get(i);
9323            if (info.activityInfo == null) {
9324                continue;
9325            }
9326
9327            if (packageName.equals(info.activityInfo.packageName)) {
9328                targetReceiver = info.activityInfo;
9329                break;
9330            }
9331        }
9332
9333        if (targetReceiver == null) {
9334            return null;
9335        }
9336
9337        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9338    }
9339
9340    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9341            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9342        if (pkgInfo.verifiers.length == 0) {
9343            return null;
9344        }
9345
9346        final int N = pkgInfo.verifiers.length;
9347        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9348        for (int i = 0; i < N; i++) {
9349            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9350
9351            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9352                    receivers);
9353            if (comp == null) {
9354                continue;
9355            }
9356
9357            final int verifierUid = getUidForVerifier(verifierInfo);
9358            if (verifierUid == -1) {
9359                continue;
9360            }
9361
9362            if (DEBUG_VERIFY) {
9363                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9364                        + " with the correct signature");
9365            }
9366            sufficientVerifiers.add(comp);
9367            verificationState.addSufficientVerifier(verifierUid);
9368        }
9369
9370        return sufficientVerifiers;
9371    }
9372
9373    private int getUidForVerifier(VerifierInfo verifierInfo) {
9374        synchronized (mPackages) {
9375            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9376            if (pkg == null) {
9377                return -1;
9378            } else if (pkg.mSignatures.length != 1) {
9379                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9380                        + " has more than one signature; ignoring");
9381                return -1;
9382            }
9383
9384            /*
9385             * If the public key of the package's signature does not match
9386             * our expected public key, then this is a different package and
9387             * we should skip.
9388             */
9389
9390            final byte[] expectedPublicKey;
9391            try {
9392                final Signature verifierSig = pkg.mSignatures[0];
9393                final PublicKey publicKey = verifierSig.getPublicKey();
9394                expectedPublicKey = publicKey.getEncoded();
9395            } catch (CertificateException e) {
9396                return -1;
9397            }
9398
9399            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9400
9401            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9402                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9403                        + " does not have the expected public key; ignoring");
9404                return -1;
9405            }
9406
9407            return pkg.applicationInfo.uid;
9408        }
9409    }
9410
9411    @Override
9412    public void finishPackageInstall(int token) {
9413        enforceSystemOrRoot("Only the system is allowed to finish installs");
9414
9415        if (DEBUG_INSTALL) {
9416            Slog.v(TAG, "BM finishing package install for " + token);
9417        }
9418
9419        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9420        mHandler.sendMessage(msg);
9421    }
9422
9423    /**
9424     * Get the verification agent timeout.
9425     *
9426     * @return verification timeout in milliseconds
9427     */
9428    private long getVerificationTimeout() {
9429        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9430                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9431                DEFAULT_VERIFICATION_TIMEOUT);
9432    }
9433
9434    /**
9435     * Get the default verification agent response code.
9436     *
9437     * @return default verification response code
9438     */
9439    private int getDefaultVerificationResponse() {
9440        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9441                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9442                DEFAULT_VERIFICATION_RESPONSE);
9443    }
9444
9445    /**
9446     * Check whether or not package verification has been enabled.
9447     *
9448     * @return true if verification should be performed
9449     */
9450    private boolean isVerificationEnabled(int userId, int installFlags) {
9451        if (!DEFAULT_VERIFY_ENABLE) {
9452            return false;
9453        }
9454
9455        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9456
9457        // Check if installing from ADB
9458        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9459            // Do not run verification in a test harness environment
9460            if (ActivityManager.isRunningInTestHarness()) {
9461                return false;
9462            }
9463            if (ensureVerifyAppsEnabled) {
9464                return true;
9465            }
9466            // Check if the developer does not want package verification for ADB installs
9467            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9468                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9469                return false;
9470            }
9471        }
9472
9473        if (ensureVerifyAppsEnabled) {
9474            return true;
9475        }
9476
9477        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9478                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9479    }
9480
9481    @Override
9482    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9483            throws RemoteException {
9484        mContext.enforceCallingOrSelfPermission(
9485                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9486                "Only intentfilter verification agents can verify applications");
9487
9488        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9489        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9490                Binder.getCallingUid(), verificationCode, failedDomains);
9491        msg.arg1 = id;
9492        msg.obj = response;
9493        mHandler.sendMessage(msg);
9494    }
9495
9496    @Override
9497    public int getIntentVerificationStatus(String packageName, int userId) {
9498        synchronized (mPackages) {
9499            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9500        }
9501    }
9502
9503    @Override
9504    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9505        boolean result = false;
9506        synchronized (mPackages) {
9507            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9508        }
9509        if (result) {
9510            scheduleWritePackageRestrictionsLocked(userId);
9511        }
9512        return result;
9513    }
9514
9515    @Override
9516    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9517        synchronized (mPackages) {
9518            return mSettings.getIntentFilterVerificationsLPr(packageName);
9519        }
9520    }
9521
9522    @Override
9523    public List<IntentFilter> getAllIntentFilters(String packageName) {
9524        if (TextUtils.isEmpty(packageName)) {
9525            return Collections.<IntentFilter>emptyList();
9526        }
9527        synchronized (mPackages) {
9528            PackageParser.Package pkg = mPackages.get(packageName);
9529            if (pkg == null || pkg.activities == null) {
9530                return Collections.<IntentFilter>emptyList();
9531            }
9532            final int count = pkg.activities.size();
9533            ArrayList<IntentFilter> result = new ArrayList<>();
9534            for (int n=0; n<count; n++) {
9535                PackageParser.Activity activity = pkg.activities.get(n);
9536                if (activity.intents != null || activity.intents.size() > 0) {
9537                    result.addAll(activity.intents);
9538                }
9539            }
9540            return result;
9541        }
9542    }
9543
9544    @Override
9545    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9546        synchronized (mPackages) {
9547            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9548            if (packageName != null) {
9549                result |= updateIntentVerificationStatus(packageName,
9550                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9551                        UserHandle.myUserId());
9552            }
9553            return result;
9554        }
9555    }
9556
9557    @Override
9558    public String getDefaultBrowserPackageName(int userId) {
9559        synchronized (mPackages) {
9560            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9561        }
9562    }
9563
9564    /**
9565     * Get the "allow unknown sources" setting.
9566     *
9567     * @return the current "allow unknown sources" setting
9568     */
9569    private int getUnknownSourcesSettings() {
9570        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9571                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9572                -1);
9573    }
9574
9575    @Override
9576    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9577        final int uid = Binder.getCallingUid();
9578        // writer
9579        synchronized (mPackages) {
9580            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9581            if (targetPackageSetting == null) {
9582                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9583            }
9584
9585            PackageSetting installerPackageSetting;
9586            if (installerPackageName != null) {
9587                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9588                if (installerPackageSetting == null) {
9589                    throw new IllegalArgumentException("Unknown installer package: "
9590                            + installerPackageName);
9591                }
9592            } else {
9593                installerPackageSetting = null;
9594            }
9595
9596            Signature[] callerSignature;
9597            Object obj = mSettings.getUserIdLPr(uid);
9598            if (obj != null) {
9599                if (obj instanceof SharedUserSetting) {
9600                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9601                } else if (obj instanceof PackageSetting) {
9602                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9603                } else {
9604                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9605                }
9606            } else {
9607                throw new SecurityException("Unknown calling uid " + uid);
9608            }
9609
9610            // Verify: can't set installerPackageName to a package that is
9611            // not signed with the same cert as the caller.
9612            if (installerPackageSetting != null) {
9613                if (compareSignatures(callerSignature,
9614                        installerPackageSetting.signatures.mSignatures)
9615                        != PackageManager.SIGNATURE_MATCH) {
9616                    throw new SecurityException(
9617                            "Caller does not have same cert as new installer package "
9618                            + installerPackageName);
9619                }
9620            }
9621
9622            // Verify: if target already has an installer package, it must
9623            // be signed with the same cert as the caller.
9624            if (targetPackageSetting.installerPackageName != null) {
9625                PackageSetting setting = mSettings.mPackages.get(
9626                        targetPackageSetting.installerPackageName);
9627                // If the currently set package isn't valid, then it's always
9628                // okay to change it.
9629                if (setting != null) {
9630                    if (compareSignatures(callerSignature,
9631                            setting.signatures.mSignatures)
9632                            != PackageManager.SIGNATURE_MATCH) {
9633                        throw new SecurityException(
9634                                "Caller does not have same cert as old installer package "
9635                                + targetPackageSetting.installerPackageName);
9636                    }
9637                }
9638            }
9639
9640            // Okay!
9641            targetPackageSetting.installerPackageName = installerPackageName;
9642            scheduleWriteSettingsLocked();
9643        }
9644    }
9645
9646    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9647        // Queue up an async operation since the package installation may take a little while.
9648        mHandler.post(new Runnable() {
9649            public void run() {
9650                mHandler.removeCallbacks(this);
9651                 // Result object to be returned
9652                PackageInstalledInfo res = new PackageInstalledInfo();
9653                res.returnCode = currentStatus;
9654                res.uid = -1;
9655                res.pkg = null;
9656                res.removedInfo = new PackageRemovedInfo();
9657                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9658                    args.doPreInstall(res.returnCode);
9659                    synchronized (mInstallLock) {
9660                        installPackageLI(args, res);
9661                    }
9662                    args.doPostInstall(res.returnCode, res.uid);
9663                }
9664
9665                // A restore should be performed at this point if (a) the install
9666                // succeeded, (b) the operation is not an update, and (c) the new
9667                // package has not opted out of backup participation.
9668                final boolean update = res.removedInfo.removedPackage != null;
9669                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9670                boolean doRestore = !update
9671                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9672
9673                // Set up the post-install work request bookkeeping.  This will be used
9674                // and cleaned up by the post-install event handling regardless of whether
9675                // there's a restore pass performed.  Token values are >= 1.
9676                int token;
9677                if (mNextInstallToken < 0) mNextInstallToken = 1;
9678                token = mNextInstallToken++;
9679
9680                PostInstallData data = new PostInstallData(args, res);
9681                mRunningInstalls.put(token, data);
9682                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9683
9684                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9685                    // Pass responsibility to the Backup Manager.  It will perform a
9686                    // restore if appropriate, then pass responsibility back to the
9687                    // Package Manager to run the post-install observer callbacks
9688                    // and broadcasts.
9689                    IBackupManager bm = IBackupManager.Stub.asInterface(
9690                            ServiceManager.getService(Context.BACKUP_SERVICE));
9691                    if (bm != null) {
9692                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9693                                + " to BM for possible restore");
9694                        try {
9695                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9696                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9697                            } else {
9698                                doRestore = false;
9699                            }
9700                        } catch (RemoteException e) {
9701                            // can't happen; the backup manager is local
9702                        } catch (Exception e) {
9703                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9704                            doRestore = false;
9705                        }
9706                    } else {
9707                        Slog.e(TAG, "Backup Manager not found!");
9708                        doRestore = false;
9709                    }
9710                }
9711
9712                if (!doRestore) {
9713                    // No restore possible, or the Backup Manager was mysteriously not
9714                    // available -- just fire the post-install work request directly.
9715                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9716                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9717                    mHandler.sendMessage(msg);
9718                }
9719            }
9720        });
9721    }
9722
9723    private abstract class HandlerParams {
9724        private static final int MAX_RETRIES = 4;
9725
9726        /**
9727         * Number of times startCopy() has been attempted and had a non-fatal
9728         * error.
9729         */
9730        private int mRetries = 0;
9731
9732        /** User handle for the user requesting the information or installation. */
9733        private final UserHandle mUser;
9734
9735        HandlerParams(UserHandle user) {
9736            mUser = user;
9737        }
9738
9739        UserHandle getUser() {
9740            return mUser;
9741        }
9742
9743        final boolean startCopy() {
9744            boolean res;
9745            try {
9746                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9747
9748                if (++mRetries > MAX_RETRIES) {
9749                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9750                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9751                    handleServiceError();
9752                    return false;
9753                } else {
9754                    handleStartCopy();
9755                    res = true;
9756                }
9757            } catch (RemoteException e) {
9758                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9759                mHandler.sendEmptyMessage(MCS_RECONNECT);
9760                res = false;
9761            }
9762            handleReturnCode();
9763            return res;
9764        }
9765
9766        final void serviceError() {
9767            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9768            handleServiceError();
9769            handleReturnCode();
9770        }
9771
9772        abstract void handleStartCopy() throws RemoteException;
9773        abstract void handleServiceError();
9774        abstract void handleReturnCode();
9775    }
9776
9777    class MeasureParams extends HandlerParams {
9778        private final PackageStats mStats;
9779        private boolean mSuccess;
9780
9781        private final IPackageStatsObserver mObserver;
9782
9783        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9784            super(new UserHandle(stats.userHandle));
9785            mObserver = observer;
9786            mStats = stats;
9787        }
9788
9789        @Override
9790        public String toString() {
9791            return "MeasureParams{"
9792                + Integer.toHexString(System.identityHashCode(this))
9793                + " " + mStats.packageName + "}";
9794        }
9795
9796        @Override
9797        void handleStartCopy() throws RemoteException {
9798            synchronized (mInstallLock) {
9799                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9800            }
9801
9802            if (mSuccess) {
9803                final boolean mounted;
9804                if (Environment.isExternalStorageEmulated()) {
9805                    mounted = true;
9806                } else {
9807                    final String status = Environment.getExternalStorageState();
9808                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9809                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9810                }
9811
9812                if (mounted) {
9813                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9814
9815                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9816                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9817
9818                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9819                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9820
9821                    // Always subtract cache size, since it's a subdirectory
9822                    mStats.externalDataSize -= mStats.externalCacheSize;
9823
9824                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9825                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9826
9827                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9828                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9829                }
9830            }
9831        }
9832
9833        @Override
9834        void handleReturnCode() {
9835            if (mObserver != null) {
9836                try {
9837                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9838                } catch (RemoteException e) {
9839                    Slog.i(TAG, "Observer no longer exists.");
9840                }
9841            }
9842        }
9843
9844        @Override
9845        void handleServiceError() {
9846            Slog.e(TAG, "Could not measure application " + mStats.packageName
9847                            + " external storage");
9848        }
9849    }
9850
9851    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9852            throws RemoteException {
9853        long result = 0;
9854        for (File path : paths) {
9855            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9856        }
9857        return result;
9858    }
9859
9860    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9861        for (File path : paths) {
9862            try {
9863                mcs.clearDirectory(path.getAbsolutePath());
9864            } catch (RemoteException e) {
9865            }
9866        }
9867    }
9868
9869    static class OriginInfo {
9870        /**
9871         * Location where install is coming from, before it has been
9872         * copied/renamed into place. This could be a single monolithic APK
9873         * file, or a cluster directory. This location may be untrusted.
9874         */
9875        final File file;
9876        final String cid;
9877
9878        /**
9879         * Flag indicating that {@link #file} or {@link #cid} has already been
9880         * staged, meaning downstream users don't need to defensively copy the
9881         * contents.
9882         */
9883        final boolean staged;
9884
9885        /**
9886         * Flag indicating that {@link #file} or {@link #cid} is an already
9887         * installed app that is being moved.
9888         */
9889        final boolean existing;
9890
9891        final String resolvedPath;
9892        final File resolvedFile;
9893
9894        static OriginInfo fromNothing() {
9895            return new OriginInfo(null, null, false, false);
9896        }
9897
9898        static OriginInfo fromUntrustedFile(File file) {
9899            return new OriginInfo(file, null, false, false);
9900        }
9901
9902        static OriginInfo fromExistingFile(File file) {
9903            return new OriginInfo(file, null, false, true);
9904        }
9905
9906        static OriginInfo fromStagedFile(File file) {
9907            return new OriginInfo(file, null, true, false);
9908        }
9909
9910        static OriginInfo fromStagedContainer(String cid) {
9911            return new OriginInfo(null, cid, true, false);
9912        }
9913
9914        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9915            this.file = file;
9916            this.cid = cid;
9917            this.staged = staged;
9918            this.existing = existing;
9919
9920            if (cid != null) {
9921                resolvedPath = PackageHelper.getSdDir(cid);
9922                resolvedFile = new File(resolvedPath);
9923            } else if (file != null) {
9924                resolvedPath = file.getAbsolutePath();
9925                resolvedFile = file;
9926            } else {
9927                resolvedPath = null;
9928                resolvedFile = null;
9929            }
9930        }
9931    }
9932
9933    class MoveInfo {
9934        final int moveId;
9935        final String fromUuid;
9936        final String toUuid;
9937        final String packageName;
9938        final String dataAppName;
9939        final int appId;
9940        final String seinfo;
9941
9942        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9943                String dataAppName, int appId, String seinfo) {
9944            this.moveId = moveId;
9945            this.fromUuid = fromUuid;
9946            this.toUuid = toUuid;
9947            this.packageName = packageName;
9948            this.dataAppName = dataAppName;
9949            this.appId = appId;
9950            this.seinfo = seinfo;
9951        }
9952    }
9953
9954    class InstallParams extends HandlerParams {
9955        final OriginInfo origin;
9956        final MoveInfo move;
9957        final IPackageInstallObserver2 observer;
9958        int installFlags;
9959        final String installerPackageName;
9960        final String volumeUuid;
9961        final VerificationParams verificationParams;
9962        private InstallArgs mArgs;
9963        private int mRet;
9964        final String packageAbiOverride;
9965
9966        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9967                int installFlags, String installerPackageName, String volumeUuid,
9968                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9969            super(user);
9970            this.origin = origin;
9971            this.move = move;
9972            this.observer = observer;
9973            this.installFlags = installFlags;
9974            this.installerPackageName = installerPackageName;
9975            this.volumeUuid = volumeUuid;
9976            this.verificationParams = verificationParams;
9977            this.packageAbiOverride = packageAbiOverride;
9978        }
9979
9980        @Override
9981        public String toString() {
9982            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9983                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9984        }
9985
9986        public ManifestDigest getManifestDigest() {
9987            if (verificationParams == null) {
9988                return null;
9989            }
9990            return verificationParams.getManifestDigest();
9991        }
9992
9993        private int installLocationPolicy(PackageInfoLite pkgLite) {
9994            String packageName = pkgLite.packageName;
9995            int installLocation = pkgLite.installLocation;
9996            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9997            // reader
9998            synchronized (mPackages) {
9999                PackageParser.Package pkg = mPackages.get(packageName);
10000                if (pkg != null) {
10001                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10002                        // Check for downgrading.
10003                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10004                            try {
10005                                checkDowngrade(pkg, pkgLite);
10006                            } catch (PackageManagerException e) {
10007                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10008                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10009                            }
10010                        }
10011                        // Check for updated system application.
10012                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10013                            if (onSd) {
10014                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10015                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10016                            }
10017                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10018                        } else {
10019                            if (onSd) {
10020                                // Install flag overrides everything.
10021                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10022                            }
10023                            // If current upgrade specifies particular preference
10024                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10025                                // Application explicitly specified internal.
10026                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10027                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10028                                // App explictly prefers external. Let policy decide
10029                            } else {
10030                                // Prefer previous location
10031                                if (isExternal(pkg)) {
10032                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10033                                }
10034                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10035                            }
10036                        }
10037                    } else {
10038                        // Invalid install. Return error code
10039                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10040                    }
10041                }
10042            }
10043            // All the special cases have been taken care of.
10044            // Return result based on recommended install location.
10045            if (onSd) {
10046                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10047            }
10048            return pkgLite.recommendedInstallLocation;
10049        }
10050
10051        /*
10052         * Invoke remote method to get package information and install
10053         * location values. Override install location based on default
10054         * policy if needed and then create install arguments based
10055         * on the install location.
10056         */
10057        public void handleStartCopy() throws RemoteException {
10058            int ret = PackageManager.INSTALL_SUCCEEDED;
10059
10060            // If we're already staged, we've firmly committed to an install location
10061            if (origin.staged) {
10062                if (origin.file != null) {
10063                    installFlags |= PackageManager.INSTALL_INTERNAL;
10064                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10065                } else if (origin.cid != null) {
10066                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10067                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10068                } else {
10069                    throw new IllegalStateException("Invalid stage location");
10070                }
10071            }
10072
10073            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10074            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10075
10076            PackageInfoLite pkgLite = null;
10077
10078            if (onInt && onSd) {
10079                // Check if both bits are set.
10080                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10081                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10082            } else {
10083                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10084                        packageAbiOverride);
10085
10086                /*
10087                 * If we have too little free space, try to free cache
10088                 * before giving up.
10089                 */
10090                if (!origin.staged && pkgLite.recommendedInstallLocation
10091                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10092                    // TODO: focus freeing disk space on the target device
10093                    final StorageManager storage = StorageManager.from(mContext);
10094                    final long lowThreshold = storage.getStorageLowBytes(
10095                            Environment.getDataDirectory());
10096
10097                    final long sizeBytes = mContainerService.calculateInstalledSize(
10098                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10099
10100                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10101                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10102                                installFlags, packageAbiOverride);
10103                    }
10104
10105                    /*
10106                     * The cache free must have deleted the file we
10107                     * downloaded to install.
10108                     *
10109                     * TODO: fix the "freeCache" call to not delete
10110                     *       the file we care about.
10111                     */
10112                    if (pkgLite.recommendedInstallLocation
10113                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10114                        pkgLite.recommendedInstallLocation
10115                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10116                    }
10117                }
10118            }
10119
10120            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10121                int loc = pkgLite.recommendedInstallLocation;
10122                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10123                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10124                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10125                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10126                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10127                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10128                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10129                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10130                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10131                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10132                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10133                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10134                } else {
10135                    // Override with defaults if needed.
10136                    loc = installLocationPolicy(pkgLite);
10137                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10138                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10139                    } else if (!onSd && !onInt) {
10140                        // Override install location with flags
10141                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10142                            // Set the flag to install on external media.
10143                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10144                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10145                        } else {
10146                            // Make sure the flag for installing on external
10147                            // media is unset
10148                            installFlags |= PackageManager.INSTALL_INTERNAL;
10149                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10150                        }
10151                    }
10152                }
10153            }
10154
10155            final InstallArgs args = createInstallArgs(this);
10156            mArgs = args;
10157
10158            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10159                 /*
10160                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10161                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10162                 */
10163                int userIdentifier = getUser().getIdentifier();
10164                if (userIdentifier == UserHandle.USER_ALL
10165                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10166                    userIdentifier = UserHandle.USER_OWNER;
10167                }
10168
10169                /*
10170                 * Determine if we have any installed package verifiers. If we
10171                 * do, then we'll defer to them to verify the packages.
10172                 */
10173                final int requiredUid = mRequiredVerifierPackage == null ? -1
10174                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10175                if (!origin.existing && requiredUid != -1
10176                        && isVerificationEnabled(userIdentifier, installFlags)) {
10177                    final Intent verification = new Intent(
10178                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10179                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10180                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10181                            PACKAGE_MIME_TYPE);
10182                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10183
10184                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10185                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10186                            0 /* TODO: Which userId? */);
10187
10188                    if (DEBUG_VERIFY) {
10189                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10190                                + verification.toString() + " with " + pkgLite.verifiers.length
10191                                + " optional verifiers");
10192                    }
10193
10194                    final int verificationId = mPendingVerificationToken++;
10195
10196                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10197
10198                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10199                            installerPackageName);
10200
10201                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10202                            installFlags);
10203
10204                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10205                            pkgLite.packageName);
10206
10207                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10208                            pkgLite.versionCode);
10209
10210                    if (verificationParams != null) {
10211                        if (verificationParams.getVerificationURI() != null) {
10212                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10213                                 verificationParams.getVerificationURI());
10214                        }
10215                        if (verificationParams.getOriginatingURI() != null) {
10216                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10217                                  verificationParams.getOriginatingURI());
10218                        }
10219                        if (verificationParams.getReferrer() != null) {
10220                            verification.putExtra(Intent.EXTRA_REFERRER,
10221                                  verificationParams.getReferrer());
10222                        }
10223                        if (verificationParams.getOriginatingUid() >= 0) {
10224                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10225                                  verificationParams.getOriginatingUid());
10226                        }
10227                        if (verificationParams.getInstallerUid() >= 0) {
10228                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10229                                  verificationParams.getInstallerUid());
10230                        }
10231                    }
10232
10233                    final PackageVerificationState verificationState = new PackageVerificationState(
10234                            requiredUid, args);
10235
10236                    mPendingVerification.append(verificationId, verificationState);
10237
10238                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10239                            receivers, verificationState);
10240
10241                    /*
10242                     * If any sufficient verifiers were listed in the package
10243                     * manifest, attempt to ask them.
10244                     */
10245                    if (sufficientVerifiers != null) {
10246                        final int N = sufficientVerifiers.size();
10247                        if (N == 0) {
10248                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10249                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10250                        } else {
10251                            for (int i = 0; i < N; i++) {
10252                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10253
10254                                final Intent sufficientIntent = new Intent(verification);
10255                                sufficientIntent.setComponent(verifierComponent);
10256
10257                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10258                            }
10259                        }
10260                    }
10261
10262                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10263                            mRequiredVerifierPackage, receivers);
10264                    if (ret == PackageManager.INSTALL_SUCCEEDED
10265                            && mRequiredVerifierPackage != null) {
10266                        /*
10267                         * Send the intent to the required verification agent,
10268                         * but only start the verification timeout after the
10269                         * target BroadcastReceivers have run.
10270                         */
10271                        verification.setComponent(requiredVerifierComponent);
10272                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10273                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10274                                new BroadcastReceiver() {
10275                                    @Override
10276                                    public void onReceive(Context context, Intent intent) {
10277                                        final Message msg = mHandler
10278                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10279                                        msg.arg1 = verificationId;
10280                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10281                                    }
10282                                }, null, 0, null, null);
10283
10284                        /*
10285                         * We don't want the copy to proceed until verification
10286                         * succeeds, so null out this field.
10287                         */
10288                        mArgs = null;
10289                    }
10290                } else {
10291                    /*
10292                     * No package verification is enabled, so immediately start
10293                     * the remote call to initiate copy using temporary file.
10294                     */
10295                    ret = args.copyApk(mContainerService, true);
10296                }
10297            }
10298
10299            mRet = ret;
10300        }
10301
10302        @Override
10303        void handleReturnCode() {
10304            // If mArgs is null, then MCS couldn't be reached. When it
10305            // reconnects, it will try again to install. At that point, this
10306            // will succeed.
10307            if (mArgs != null) {
10308                processPendingInstall(mArgs, mRet);
10309            }
10310        }
10311
10312        @Override
10313        void handleServiceError() {
10314            mArgs = createInstallArgs(this);
10315            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10316        }
10317
10318        public boolean isForwardLocked() {
10319            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10320        }
10321    }
10322
10323    /**
10324     * Used during creation of InstallArgs
10325     *
10326     * @param installFlags package installation flags
10327     * @return true if should be installed on external storage
10328     */
10329    private static boolean installOnExternalAsec(int installFlags) {
10330        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10331            return false;
10332        }
10333        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10334            return true;
10335        }
10336        return false;
10337    }
10338
10339    /**
10340     * Used during creation of InstallArgs
10341     *
10342     * @param installFlags package installation flags
10343     * @return true if should be installed as forward locked
10344     */
10345    private static boolean installForwardLocked(int installFlags) {
10346        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10347    }
10348
10349    private InstallArgs createInstallArgs(InstallParams params) {
10350        if (params.move != null) {
10351            return new MoveInstallArgs(params);
10352        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10353            return new AsecInstallArgs(params);
10354        } else {
10355            return new FileInstallArgs(params);
10356        }
10357    }
10358
10359    /**
10360     * Create args that describe an existing installed package. Typically used
10361     * when cleaning up old installs, or used as a move source.
10362     */
10363    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10364            String resourcePath, String[] instructionSets) {
10365        final boolean isInAsec;
10366        if (installOnExternalAsec(installFlags)) {
10367            /* Apps on SD card are always in ASEC containers. */
10368            isInAsec = true;
10369        } else if (installForwardLocked(installFlags)
10370                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10371            /*
10372             * Forward-locked apps are only in ASEC containers if they're the
10373             * new style
10374             */
10375            isInAsec = true;
10376        } else {
10377            isInAsec = false;
10378        }
10379
10380        if (isInAsec) {
10381            return new AsecInstallArgs(codePath, instructionSets,
10382                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10383        } else {
10384            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10385        }
10386    }
10387
10388    static abstract class InstallArgs {
10389        /** @see InstallParams#origin */
10390        final OriginInfo origin;
10391        /** @see InstallParams#move */
10392        final MoveInfo move;
10393
10394        final IPackageInstallObserver2 observer;
10395        // Always refers to PackageManager flags only
10396        final int installFlags;
10397        final String installerPackageName;
10398        final String volumeUuid;
10399        final ManifestDigest manifestDigest;
10400        final UserHandle user;
10401        final String abiOverride;
10402
10403        // The list of instruction sets supported by this app. This is currently
10404        // only used during the rmdex() phase to clean up resources. We can get rid of this
10405        // if we move dex files under the common app path.
10406        /* nullable */ String[] instructionSets;
10407
10408        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10409                int installFlags, String installerPackageName, String volumeUuid,
10410                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10411                String abiOverride) {
10412            this.origin = origin;
10413            this.move = move;
10414            this.installFlags = installFlags;
10415            this.observer = observer;
10416            this.installerPackageName = installerPackageName;
10417            this.volumeUuid = volumeUuid;
10418            this.manifestDigest = manifestDigest;
10419            this.user = user;
10420            this.instructionSets = instructionSets;
10421            this.abiOverride = abiOverride;
10422        }
10423
10424        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10425        abstract int doPreInstall(int status);
10426
10427        /**
10428         * Rename package into final resting place. All paths on the given
10429         * scanned package should be updated to reflect the rename.
10430         */
10431        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10432        abstract int doPostInstall(int status, int uid);
10433
10434        /** @see PackageSettingBase#codePathString */
10435        abstract String getCodePath();
10436        /** @see PackageSettingBase#resourcePathString */
10437        abstract String getResourcePath();
10438
10439        // Need installer lock especially for dex file removal.
10440        abstract void cleanUpResourcesLI();
10441        abstract boolean doPostDeleteLI(boolean delete);
10442
10443        /**
10444         * Called before the source arguments are copied. This is used mostly
10445         * for MoveParams when it needs to read the source file to put it in the
10446         * destination.
10447         */
10448        int doPreCopy() {
10449            return PackageManager.INSTALL_SUCCEEDED;
10450        }
10451
10452        /**
10453         * Called after the source arguments are copied. This is used mostly for
10454         * MoveParams when it needs to read the source file to put it in the
10455         * destination.
10456         *
10457         * @return
10458         */
10459        int doPostCopy(int uid) {
10460            return PackageManager.INSTALL_SUCCEEDED;
10461        }
10462
10463        protected boolean isFwdLocked() {
10464            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10465        }
10466
10467        protected boolean isExternalAsec() {
10468            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10469        }
10470
10471        UserHandle getUser() {
10472            return user;
10473        }
10474    }
10475
10476    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10477        if (!allCodePaths.isEmpty()) {
10478            if (instructionSets == null) {
10479                throw new IllegalStateException("instructionSet == null");
10480            }
10481            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10482            for (String codePath : allCodePaths) {
10483                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10484                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10485                    if (retCode < 0) {
10486                        Slog.w(TAG, "Couldn't remove dex file for package: "
10487                                + " at location " + codePath + ", retcode=" + retCode);
10488                        // we don't consider this to be a failure of the core package deletion
10489                    }
10490                }
10491            }
10492        }
10493    }
10494
10495    /**
10496     * Logic to handle installation of non-ASEC applications, including copying
10497     * and renaming logic.
10498     */
10499    class FileInstallArgs extends InstallArgs {
10500        private File codeFile;
10501        private File resourceFile;
10502
10503        // Example topology:
10504        // /data/app/com.example/base.apk
10505        // /data/app/com.example/split_foo.apk
10506        // /data/app/com.example/lib/arm/libfoo.so
10507        // /data/app/com.example/lib/arm64/libfoo.so
10508        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10509
10510        /** New install */
10511        FileInstallArgs(InstallParams params) {
10512            super(params.origin, params.move, params.observer, params.installFlags,
10513                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10514                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10515            if (isFwdLocked()) {
10516                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10517            }
10518        }
10519
10520        /** Existing install */
10521        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10522            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10523                    null);
10524            this.codeFile = (codePath != null) ? new File(codePath) : null;
10525            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10526        }
10527
10528        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10529            if (origin.staged) {
10530                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10531                codeFile = origin.file;
10532                resourceFile = origin.file;
10533                return PackageManager.INSTALL_SUCCEEDED;
10534            }
10535
10536            try {
10537                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10538                codeFile = tempDir;
10539                resourceFile = tempDir;
10540            } catch (IOException e) {
10541                Slog.w(TAG, "Failed to create copy file: " + e);
10542                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10543            }
10544
10545            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10546                @Override
10547                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10548                    if (!FileUtils.isValidExtFilename(name)) {
10549                        throw new IllegalArgumentException("Invalid filename: " + name);
10550                    }
10551                    try {
10552                        final File file = new File(codeFile, name);
10553                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10554                                O_RDWR | O_CREAT, 0644);
10555                        Os.chmod(file.getAbsolutePath(), 0644);
10556                        return new ParcelFileDescriptor(fd);
10557                    } catch (ErrnoException e) {
10558                        throw new RemoteException("Failed to open: " + e.getMessage());
10559                    }
10560                }
10561            };
10562
10563            int ret = PackageManager.INSTALL_SUCCEEDED;
10564            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10565            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10566                Slog.e(TAG, "Failed to copy package");
10567                return ret;
10568            }
10569
10570            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10571            NativeLibraryHelper.Handle handle = null;
10572            try {
10573                handle = NativeLibraryHelper.Handle.create(codeFile);
10574                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10575                        abiOverride);
10576            } catch (IOException e) {
10577                Slog.e(TAG, "Copying native libraries failed", e);
10578                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10579            } finally {
10580                IoUtils.closeQuietly(handle);
10581            }
10582
10583            return ret;
10584        }
10585
10586        int doPreInstall(int status) {
10587            if (status != PackageManager.INSTALL_SUCCEEDED) {
10588                cleanUp();
10589            }
10590            return status;
10591        }
10592
10593        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10594            if (status != PackageManager.INSTALL_SUCCEEDED) {
10595                cleanUp();
10596                return false;
10597            }
10598
10599            final File targetDir = codeFile.getParentFile();
10600            final File beforeCodeFile = codeFile;
10601            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10602
10603            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10604            try {
10605                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10606            } catch (ErrnoException e) {
10607                Slog.w(TAG, "Failed to rename", e);
10608                return false;
10609            }
10610
10611            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10612                Slog.w(TAG, "Failed to restorecon");
10613                return false;
10614            }
10615
10616            // Reflect the rename internally
10617            codeFile = afterCodeFile;
10618            resourceFile = afterCodeFile;
10619
10620            // Reflect the rename in scanned details
10621            pkg.codePath = afterCodeFile.getAbsolutePath();
10622            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10623                    pkg.baseCodePath);
10624            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10625                    pkg.splitCodePaths);
10626
10627            // Reflect the rename in app info
10628            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10629            pkg.applicationInfo.setCodePath(pkg.codePath);
10630            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10631            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10632            pkg.applicationInfo.setResourcePath(pkg.codePath);
10633            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10634            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10635
10636            return true;
10637        }
10638
10639        int doPostInstall(int status, int uid) {
10640            if (status != PackageManager.INSTALL_SUCCEEDED) {
10641                cleanUp();
10642            }
10643            return status;
10644        }
10645
10646        @Override
10647        String getCodePath() {
10648            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10649        }
10650
10651        @Override
10652        String getResourcePath() {
10653            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10654        }
10655
10656        private boolean cleanUp() {
10657            if (codeFile == null || !codeFile.exists()) {
10658                return false;
10659            }
10660
10661            if (codeFile.isDirectory()) {
10662                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10663            } else {
10664                codeFile.delete();
10665            }
10666
10667            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10668                resourceFile.delete();
10669            }
10670
10671            return true;
10672        }
10673
10674        void cleanUpResourcesLI() {
10675            // Try enumerating all code paths before deleting
10676            List<String> allCodePaths = Collections.EMPTY_LIST;
10677            if (codeFile != null && codeFile.exists()) {
10678                try {
10679                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10680                    allCodePaths = pkg.getAllCodePaths();
10681                } catch (PackageParserException e) {
10682                    // Ignored; we tried our best
10683                }
10684            }
10685
10686            cleanUp();
10687            removeDexFiles(allCodePaths, instructionSets);
10688        }
10689
10690        boolean doPostDeleteLI(boolean delete) {
10691            // XXX err, shouldn't we respect the delete flag?
10692            cleanUpResourcesLI();
10693            return true;
10694        }
10695    }
10696
10697    private boolean isAsecExternal(String cid) {
10698        final String asecPath = PackageHelper.getSdFilesystem(cid);
10699        return !asecPath.startsWith(mAsecInternalPath);
10700    }
10701
10702    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10703            PackageManagerException {
10704        if (copyRet < 0) {
10705            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10706                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10707                throw new PackageManagerException(copyRet, message);
10708            }
10709        }
10710    }
10711
10712    /**
10713     * Extract the MountService "container ID" from the full code path of an
10714     * .apk.
10715     */
10716    static String cidFromCodePath(String fullCodePath) {
10717        int eidx = fullCodePath.lastIndexOf("/");
10718        String subStr1 = fullCodePath.substring(0, eidx);
10719        int sidx = subStr1.lastIndexOf("/");
10720        return subStr1.substring(sidx+1, eidx);
10721    }
10722
10723    /**
10724     * Logic to handle installation of ASEC applications, including copying and
10725     * renaming logic.
10726     */
10727    class AsecInstallArgs extends InstallArgs {
10728        static final String RES_FILE_NAME = "pkg.apk";
10729        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10730
10731        String cid;
10732        String packagePath;
10733        String resourcePath;
10734
10735        /** New install */
10736        AsecInstallArgs(InstallParams params) {
10737            super(params.origin, params.move, params.observer, params.installFlags,
10738                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10739                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10740        }
10741
10742        /** Existing install */
10743        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10744                        boolean isExternal, boolean isForwardLocked) {
10745            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10746                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10747                    instructionSets, null);
10748            // Hackily pretend we're still looking at a full code path
10749            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10750                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10751            }
10752
10753            // Extract cid from fullCodePath
10754            int eidx = fullCodePath.lastIndexOf("/");
10755            String subStr1 = fullCodePath.substring(0, eidx);
10756            int sidx = subStr1.lastIndexOf("/");
10757            cid = subStr1.substring(sidx+1, eidx);
10758            setMountPath(subStr1);
10759        }
10760
10761        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10762            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10763                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10764                    instructionSets, null);
10765            this.cid = cid;
10766            setMountPath(PackageHelper.getSdDir(cid));
10767        }
10768
10769        void createCopyFile() {
10770            cid = mInstallerService.allocateExternalStageCidLegacy();
10771        }
10772
10773        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10774            if (origin.staged) {
10775                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10776                cid = origin.cid;
10777                setMountPath(PackageHelper.getSdDir(cid));
10778                return PackageManager.INSTALL_SUCCEEDED;
10779            }
10780
10781            if (temp) {
10782                createCopyFile();
10783            } else {
10784                /*
10785                 * Pre-emptively destroy the container since it's destroyed if
10786                 * copying fails due to it existing anyway.
10787                 */
10788                PackageHelper.destroySdDir(cid);
10789            }
10790
10791            final String newMountPath = imcs.copyPackageToContainer(
10792                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10793                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10794
10795            if (newMountPath != null) {
10796                setMountPath(newMountPath);
10797                return PackageManager.INSTALL_SUCCEEDED;
10798            } else {
10799                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10800            }
10801        }
10802
10803        @Override
10804        String getCodePath() {
10805            return packagePath;
10806        }
10807
10808        @Override
10809        String getResourcePath() {
10810            return resourcePath;
10811        }
10812
10813        int doPreInstall(int status) {
10814            if (status != PackageManager.INSTALL_SUCCEEDED) {
10815                // Destroy container
10816                PackageHelper.destroySdDir(cid);
10817            } else {
10818                boolean mounted = PackageHelper.isContainerMounted(cid);
10819                if (!mounted) {
10820                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10821                            Process.SYSTEM_UID);
10822                    if (newMountPath != null) {
10823                        setMountPath(newMountPath);
10824                    } else {
10825                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10826                    }
10827                }
10828            }
10829            return status;
10830        }
10831
10832        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10833            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10834            String newMountPath = null;
10835            if (PackageHelper.isContainerMounted(cid)) {
10836                // Unmount the container
10837                if (!PackageHelper.unMountSdDir(cid)) {
10838                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10839                    return false;
10840                }
10841            }
10842            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10843                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10844                        " which might be stale. Will try to clean up.");
10845                // Clean up the stale container and proceed to recreate.
10846                if (!PackageHelper.destroySdDir(newCacheId)) {
10847                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10848                    return false;
10849                }
10850                // Successfully cleaned up stale container. Try to rename again.
10851                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10852                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10853                            + " inspite of cleaning it up.");
10854                    return false;
10855                }
10856            }
10857            if (!PackageHelper.isContainerMounted(newCacheId)) {
10858                Slog.w(TAG, "Mounting container " + newCacheId);
10859                newMountPath = PackageHelper.mountSdDir(newCacheId,
10860                        getEncryptKey(), Process.SYSTEM_UID);
10861            } else {
10862                newMountPath = PackageHelper.getSdDir(newCacheId);
10863            }
10864            if (newMountPath == null) {
10865                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10866                return false;
10867            }
10868            Log.i(TAG, "Succesfully renamed " + cid +
10869                    " to " + newCacheId +
10870                    " at new path: " + newMountPath);
10871            cid = newCacheId;
10872
10873            final File beforeCodeFile = new File(packagePath);
10874            setMountPath(newMountPath);
10875            final File afterCodeFile = new File(packagePath);
10876
10877            // Reflect the rename in scanned details
10878            pkg.codePath = afterCodeFile.getAbsolutePath();
10879            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10880                    pkg.baseCodePath);
10881            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10882                    pkg.splitCodePaths);
10883
10884            // Reflect the rename in app info
10885            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10886            pkg.applicationInfo.setCodePath(pkg.codePath);
10887            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10888            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10889            pkg.applicationInfo.setResourcePath(pkg.codePath);
10890            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10891            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10892
10893            return true;
10894        }
10895
10896        private void setMountPath(String mountPath) {
10897            final File mountFile = new File(mountPath);
10898
10899            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10900            if (monolithicFile.exists()) {
10901                packagePath = monolithicFile.getAbsolutePath();
10902                if (isFwdLocked()) {
10903                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10904                } else {
10905                    resourcePath = packagePath;
10906                }
10907            } else {
10908                packagePath = mountFile.getAbsolutePath();
10909                resourcePath = packagePath;
10910            }
10911        }
10912
10913        int doPostInstall(int status, int uid) {
10914            if (status != PackageManager.INSTALL_SUCCEEDED) {
10915                cleanUp();
10916            } else {
10917                final int groupOwner;
10918                final String protectedFile;
10919                if (isFwdLocked()) {
10920                    groupOwner = UserHandle.getSharedAppGid(uid);
10921                    protectedFile = RES_FILE_NAME;
10922                } else {
10923                    groupOwner = -1;
10924                    protectedFile = null;
10925                }
10926
10927                if (uid < Process.FIRST_APPLICATION_UID
10928                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10929                    Slog.e(TAG, "Failed to finalize " + cid);
10930                    PackageHelper.destroySdDir(cid);
10931                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10932                }
10933
10934                boolean mounted = PackageHelper.isContainerMounted(cid);
10935                if (!mounted) {
10936                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10937                }
10938            }
10939            return status;
10940        }
10941
10942        private void cleanUp() {
10943            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10944
10945            // Destroy secure container
10946            PackageHelper.destroySdDir(cid);
10947        }
10948
10949        private List<String> getAllCodePaths() {
10950            final File codeFile = new File(getCodePath());
10951            if (codeFile != null && codeFile.exists()) {
10952                try {
10953                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10954                    return pkg.getAllCodePaths();
10955                } catch (PackageParserException e) {
10956                    // Ignored; we tried our best
10957                }
10958            }
10959            return Collections.EMPTY_LIST;
10960        }
10961
10962        void cleanUpResourcesLI() {
10963            // Enumerate all code paths before deleting
10964            cleanUpResourcesLI(getAllCodePaths());
10965        }
10966
10967        private void cleanUpResourcesLI(List<String> allCodePaths) {
10968            cleanUp();
10969            removeDexFiles(allCodePaths, instructionSets);
10970        }
10971
10972        String getPackageName() {
10973            return getAsecPackageName(cid);
10974        }
10975
10976        boolean doPostDeleteLI(boolean delete) {
10977            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10978            final List<String> allCodePaths = getAllCodePaths();
10979            boolean mounted = PackageHelper.isContainerMounted(cid);
10980            if (mounted) {
10981                // Unmount first
10982                if (PackageHelper.unMountSdDir(cid)) {
10983                    mounted = false;
10984                }
10985            }
10986            if (!mounted && delete) {
10987                cleanUpResourcesLI(allCodePaths);
10988            }
10989            return !mounted;
10990        }
10991
10992        @Override
10993        int doPreCopy() {
10994            if (isFwdLocked()) {
10995                if (!PackageHelper.fixSdPermissions(cid,
10996                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10997                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10998                }
10999            }
11000
11001            return PackageManager.INSTALL_SUCCEEDED;
11002        }
11003
11004        @Override
11005        int doPostCopy(int uid) {
11006            if (isFwdLocked()) {
11007                if (uid < Process.FIRST_APPLICATION_UID
11008                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11009                                RES_FILE_NAME)) {
11010                    Slog.e(TAG, "Failed to finalize " + cid);
11011                    PackageHelper.destroySdDir(cid);
11012                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11013                }
11014            }
11015
11016            return PackageManager.INSTALL_SUCCEEDED;
11017        }
11018    }
11019
11020    /**
11021     * Logic to handle movement of existing installed applications.
11022     */
11023    class MoveInstallArgs extends InstallArgs {
11024        private File codeFile;
11025        private File resourceFile;
11026
11027        /** New install */
11028        MoveInstallArgs(InstallParams params) {
11029            super(params.origin, params.move, params.observer, params.installFlags,
11030                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11031                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11032        }
11033
11034        int copyApk(IMediaContainerService imcs, boolean temp) {
11035            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11036                    + move.fromUuid + " to " + move.toUuid);
11037            synchronized (mInstaller) {
11038                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11039                        move.dataAppName, move.appId, move.seinfo) != 0) {
11040                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11041                }
11042            }
11043
11044            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11045            resourceFile = codeFile;
11046            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11047
11048            return PackageManager.INSTALL_SUCCEEDED;
11049        }
11050
11051        int doPreInstall(int status) {
11052            if (status != PackageManager.INSTALL_SUCCEEDED) {
11053                cleanUp();
11054            }
11055            return status;
11056        }
11057
11058        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11059            if (status != PackageManager.INSTALL_SUCCEEDED) {
11060                cleanUp();
11061                return false;
11062            }
11063
11064            // Reflect the move in app info
11065            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11066            pkg.applicationInfo.setCodePath(pkg.codePath);
11067            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11068            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11069            pkg.applicationInfo.setResourcePath(pkg.codePath);
11070            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11071            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11072
11073            return true;
11074        }
11075
11076        int doPostInstall(int status, int uid) {
11077            if (status != PackageManager.INSTALL_SUCCEEDED) {
11078                cleanUp();
11079            }
11080            return status;
11081        }
11082
11083        @Override
11084        String getCodePath() {
11085            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11086        }
11087
11088        @Override
11089        String getResourcePath() {
11090            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11091        }
11092
11093        private boolean cleanUp() {
11094            if (codeFile == null || !codeFile.exists()) {
11095                return false;
11096            }
11097
11098            if (codeFile.isDirectory()) {
11099                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11100            } else {
11101                codeFile.delete();
11102            }
11103
11104            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11105                resourceFile.delete();
11106            }
11107
11108            return true;
11109        }
11110
11111        void cleanUpResourcesLI() {
11112            cleanUp();
11113        }
11114
11115        boolean doPostDeleteLI(boolean delete) {
11116            // XXX err, shouldn't we respect the delete flag?
11117            cleanUpResourcesLI();
11118            return true;
11119        }
11120    }
11121
11122    static String getAsecPackageName(String packageCid) {
11123        int idx = packageCid.lastIndexOf("-");
11124        if (idx == -1) {
11125            return packageCid;
11126        }
11127        return packageCid.substring(0, idx);
11128    }
11129
11130    // Utility method used to create code paths based on package name and available index.
11131    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11132        String idxStr = "";
11133        int idx = 1;
11134        // Fall back to default value of idx=1 if prefix is not
11135        // part of oldCodePath
11136        if (oldCodePath != null) {
11137            String subStr = oldCodePath;
11138            // Drop the suffix right away
11139            if (suffix != null && subStr.endsWith(suffix)) {
11140                subStr = subStr.substring(0, subStr.length() - suffix.length());
11141            }
11142            // If oldCodePath already contains prefix find out the
11143            // ending index to either increment or decrement.
11144            int sidx = subStr.lastIndexOf(prefix);
11145            if (sidx != -1) {
11146                subStr = subStr.substring(sidx + prefix.length());
11147                if (subStr != null) {
11148                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11149                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11150                    }
11151                    try {
11152                        idx = Integer.parseInt(subStr);
11153                        if (idx <= 1) {
11154                            idx++;
11155                        } else {
11156                            idx--;
11157                        }
11158                    } catch(NumberFormatException e) {
11159                    }
11160                }
11161            }
11162        }
11163        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11164        return prefix + idxStr;
11165    }
11166
11167    private File getNextCodePath(File targetDir, String packageName) {
11168        int suffix = 1;
11169        File result;
11170        do {
11171            result = new File(targetDir, packageName + "-" + suffix);
11172            suffix++;
11173        } while (result.exists());
11174        return result;
11175    }
11176
11177    // Utility method that returns the relative package path with respect
11178    // to the installation directory. Like say for /data/data/com.test-1.apk
11179    // string com.test-1 is returned.
11180    static String deriveCodePathName(String codePath) {
11181        if (codePath == null) {
11182            return null;
11183        }
11184        final File codeFile = new File(codePath);
11185        final String name = codeFile.getName();
11186        if (codeFile.isDirectory()) {
11187            return name;
11188        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11189            final int lastDot = name.lastIndexOf('.');
11190            return name.substring(0, lastDot);
11191        } else {
11192            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11193            return null;
11194        }
11195    }
11196
11197    class PackageInstalledInfo {
11198        String name;
11199        int uid;
11200        // The set of users that originally had this package installed.
11201        int[] origUsers;
11202        // The set of users that now have this package installed.
11203        int[] newUsers;
11204        PackageParser.Package pkg;
11205        int returnCode;
11206        String returnMsg;
11207        PackageRemovedInfo removedInfo;
11208
11209        public void setError(int code, String msg) {
11210            returnCode = code;
11211            returnMsg = msg;
11212            Slog.w(TAG, msg);
11213        }
11214
11215        public void setError(String msg, PackageParserException e) {
11216            returnCode = e.error;
11217            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11218            Slog.w(TAG, msg, e);
11219        }
11220
11221        public void setError(String msg, PackageManagerException e) {
11222            returnCode = e.error;
11223            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11224            Slog.w(TAG, msg, e);
11225        }
11226
11227        // In some error cases we want to convey more info back to the observer
11228        String origPackage;
11229        String origPermission;
11230    }
11231
11232    /*
11233     * Install a non-existing package.
11234     */
11235    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11236            UserHandle user, String installerPackageName, String volumeUuid,
11237            PackageInstalledInfo res) {
11238        // Remember this for later, in case we need to rollback this install
11239        String pkgName = pkg.packageName;
11240
11241        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11242        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11243                UserHandle.USER_OWNER).exists();
11244        synchronized(mPackages) {
11245            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11246                // A package with the same name is already installed, though
11247                // it has been renamed to an older name.  The package we
11248                // are trying to install should be installed as an update to
11249                // the existing one, but that has not been requested, so bail.
11250                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11251                        + " without first uninstalling package running as "
11252                        + mSettings.mRenamedPackages.get(pkgName));
11253                return;
11254            }
11255            if (mPackages.containsKey(pkgName)) {
11256                // Don't allow installation over an existing package with the same name.
11257                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11258                        + " without first uninstalling.");
11259                return;
11260            }
11261        }
11262
11263        try {
11264            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11265                    System.currentTimeMillis(), user);
11266
11267            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11268            // delete the partially installed application. the data directory will have to be
11269            // restored if it was already existing
11270            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11271                // remove package from internal structures.  Note that we want deletePackageX to
11272                // delete the package data and cache directories that it created in
11273                // scanPackageLocked, unless those directories existed before we even tried to
11274                // install.
11275                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11276                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11277                                res.removedInfo, true);
11278            }
11279
11280        } catch (PackageManagerException e) {
11281            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11282        }
11283    }
11284
11285    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11286        // Can't rotate keys during boot or if sharedUser.
11287        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11288                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11289            return false;
11290        }
11291        // app is using upgradeKeySets; make sure all are valid
11292        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11293        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11294        for (int i = 0; i < upgradeKeySets.length; i++) {
11295            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11296                Slog.wtf(TAG, "Package "
11297                         + (oldPs.name != null ? oldPs.name : "<null>")
11298                         + " contains upgrade-key-set reference to unknown key-set: "
11299                         + upgradeKeySets[i]
11300                         + " reverting to signatures check.");
11301                return false;
11302            }
11303        }
11304        return true;
11305    }
11306
11307    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11308        // Upgrade keysets are being used.  Determine if new package has a superset of the
11309        // required keys.
11310        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11311        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11312        for (int i = 0; i < upgradeKeySets.length; i++) {
11313            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11314            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11315                return true;
11316            }
11317        }
11318        return false;
11319    }
11320
11321    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11322            UserHandle user, String installerPackageName, String volumeUuid,
11323            PackageInstalledInfo res) {
11324        final PackageParser.Package oldPackage;
11325        final String pkgName = pkg.packageName;
11326        final int[] allUsers;
11327        final boolean[] perUserInstalled;
11328        final boolean weFroze;
11329
11330        // First find the old package info and check signatures
11331        synchronized(mPackages) {
11332            oldPackage = mPackages.get(pkgName);
11333            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11334            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11335            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11336                if(!checkUpgradeKeySetLP(ps, pkg)) {
11337                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11338                            "New package not signed by keys specified by upgrade-keysets: "
11339                            + pkgName);
11340                    return;
11341                }
11342            } else {
11343                // default to original signature matching
11344                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11345                    != PackageManager.SIGNATURE_MATCH) {
11346                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11347                            "New package has a different signature: " + pkgName);
11348                    return;
11349                }
11350            }
11351
11352            // In case of rollback, remember per-user/profile install state
11353            allUsers = sUserManager.getUserIds();
11354            perUserInstalled = new boolean[allUsers.length];
11355            for (int i = 0; i < allUsers.length; i++) {
11356                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11357            }
11358
11359            // Mark the app as frozen to prevent launching during the upgrade
11360            // process, and then kill all running instances
11361            if (!ps.frozen) {
11362                ps.frozen = true;
11363                weFroze = true;
11364            } else {
11365                weFroze = false;
11366            }
11367        }
11368
11369        // Now that we're guarded by frozen state, kill app during upgrade
11370        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11371
11372        try {
11373            boolean sysPkg = (isSystemApp(oldPackage));
11374            if (sysPkg) {
11375                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11376                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11377            } else {
11378                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11379                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11380            }
11381        } finally {
11382            // Regardless of success or failure of upgrade steps above, always
11383            // unfreeze the package if we froze it
11384            if (weFroze) {
11385                unfreezePackage(pkgName);
11386            }
11387        }
11388    }
11389
11390    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11391            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11392            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11393            String volumeUuid, PackageInstalledInfo res) {
11394        String pkgName = deletedPackage.packageName;
11395        boolean deletedPkg = true;
11396        boolean updatedSettings = false;
11397
11398        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11399                + deletedPackage);
11400        long origUpdateTime;
11401        if (pkg.mExtras != null) {
11402            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11403        } else {
11404            origUpdateTime = 0;
11405        }
11406
11407        // First delete the existing package while retaining the data directory
11408        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11409                res.removedInfo, true)) {
11410            // If the existing package wasn't successfully deleted
11411            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11412            deletedPkg = false;
11413        } else {
11414            // Successfully deleted the old package; proceed with replace.
11415
11416            // If deleted package lived in a container, give users a chance to
11417            // relinquish resources before killing.
11418            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11419                if (DEBUG_INSTALL) {
11420                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11421                }
11422                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11423                final ArrayList<String> pkgList = new ArrayList<String>(1);
11424                pkgList.add(deletedPackage.applicationInfo.packageName);
11425                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11426            }
11427
11428            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11429            try {
11430                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11431                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11432                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11433                        perUserInstalled, res, user);
11434                updatedSettings = true;
11435            } catch (PackageManagerException e) {
11436                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11437            }
11438        }
11439
11440        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11441            // remove package from internal structures.  Note that we want deletePackageX to
11442            // delete the package data and cache directories that it created in
11443            // scanPackageLocked, unless those directories existed before we even tried to
11444            // install.
11445            if(updatedSettings) {
11446                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11447                deletePackageLI(
11448                        pkgName, null, true, allUsers, perUserInstalled,
11449                        PackageManager.DELETE_KEEP_DATA,
11450                                res.removedInfo, true);
11451            }
11452            // Since we failed to install the new package we need to restore the old
11453            // package that we deleted.
11454            if (deletedPkg) {
11455                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11456                File restoreFile = new File(deletedPackage.codePath);
11457                // Parse old package
11458                boolean oldExternal = isExternal(deletedPackage);
11459                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11460                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11461                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11462                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11463                try {
11464                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11465                } catch (PackageManagerException e) {
11466                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11467                            + e.getMessage());
11468                    return;
11469                }
11470                // Restore of old package succeeded. Update permissions.
11471                // writer
11472                synchronized (mPackages) {
11473                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11474                            UPDATE_PERMISSIONS_ALL);
11475                    // can downgrade to reader
11476                    mSettings.writeLPr();
11477                }
11478                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11479            }
11480        }
11481    }
11482
11483    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11484            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11485            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11486            String volumeUuid, PackageInstalledInfo res) {
11487        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11488                + ", old=" + deletedPackage);
11489        boolean disabledSystem = false;
11490        boolean updatedSettings = false;
11491        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11492        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11493                != 0) {
11494            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11495        }
11496        String packageName = deletedPackage.packageName;
11497        if (packageName == null) {
11498            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11499                    "Attempt to delete null packageName.");
11500            return;
11501        }
11502        PackageParser.Package oldPkg;
11503        PackageSetting oldPkgSetting;
11504        // reader
11505        synchronized (mPackages) {
11506            oldPkg = mPackages.get(packageName);
11507            oldPkgSetting = mSettings.mPackages.get(packageName);
11508            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11509                    (oldPkgSetting == null)) {
11510                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11511                        "Couldn't find package:" + packageName + " information");
11512                return;
11513            }
11514        }
11515
11516        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11517        res.removedInfo.removedPackage = packageName;
11518        // Remove existing system package
11519        removePackageLI(oldPkgSetting, true);
11520        // writer
11521        synchronized (mPackages) {
11522            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11523            if (!disabledSystem && deletedPackage != null) {
11524                // We didn't need to disable the .apk as a current system package,
11525                // which means we are replacing another update that is already
11526                // installed.  We need to make sure to delete the older one's .apk.
11527                res.removedInfo.args = createInstallArgsForExisting(0,
11528                        deletedPackage.applicationInfo.getCodePath(),
11529                        deletedPackage.applicationInfo.getResourcePath(),
11530                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11531            } else {
11532                res.removedInfo.args = null;
11533            }
11534        }
11535
11536        // Successfully disabled the old package. Now proceed with re-installation
11537        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11538
11539        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11540        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11541
11542        PackageParser.Package newPackage = null;
11543        try {
11544            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11545            if (newPackage.mExtras != null) {
11546                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11547                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11548                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11549
11550                // is the update attempting to change shared user? that isn't going to work...
11551                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11552                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11553                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11554                            + " to " + newPkgSetting.sharedUser);
11555                    updatedSettings = true;
11556                }
11557            }
11558
11559            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11560                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11561                        perUserInstalled, res, user);
11562                updatedSettings = true;
11563            }
11564
11565        } catch (PackageManagerException e) {
11566            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11567        }
11568
11569        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11570            // Re installation failed. Restore old information
11571            // Remove new pkg information
11572            if (newPackage != null) {
11573                removeInstalledPackageLI(newPackage, true);
11574            }
11575            // Add back the old system package
11576            try {
11577                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11578            } catch (PackageManagerException e) {
11579                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11580            }
11581            // Restore the old system information in Settings
11582            synchronized (mPackages) {
11583                if (disabledSystem) {
11584                    mSettings.enableSystemPackageLPw(packageName);
11585                }
11586                if (updatedSettings) {
11587                    mSettings.setInstallerPackageName(packageName,
11588                            oldPkgSetting.installerPackageName);
11589                }
11590                mSettings.writeLPr();
11591            }
11592        }
11593    }
11594
11595    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11596            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11597            UserHandle user) {
11598        String pkgName = newPackage.packageName;
11599        synchronized (mPackages) {
11600            //write settings. the installStatus will be incomplete at this stage.
11601            //note that the new package setting would have already been
11602            //added to mPackages. It hasn't been persisted yet.
11603            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11604            mSettings.writeLPr();
11605        }
11606
11607        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11608
11609        synchronized (mPackages) {
11610            updatePermissionsLPw(newPackage.packageName, newPackage,
11611                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11612                            ? UPDATE_PERMISSIONS_ALL : 0));
11613            // For system-bundled packages, we assume that installing an upgraded version
11614            // of the package implies that the user actually wants to run that new code,
11615            // so we enable the package.
11616            PackageSetting ps = mSettings.mPackages.get(pkgName);
11617            if (ps != null) {
11618                if (isSystemApp(newPackage)) {
11619                    // NB: implicit assumption that system package upgrades apply to all users
11620                    if (DEBUG_INSTALL) {
11621                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11622                    }
11623                    if (res.origUsers != null) {
11624                        for (int userHandle : res.origUsers) {
11625                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11626                                    userHandle, installerPackageName);
11627                        }
11628                    }
11629                    // Also convey the prior install/uninstall state
11630                    if (allUsers != null && perUserInstalled != null) {
11631                        for (int i = 0; i < allUsers.length; i++) {
11632                            if (DEBUG_INSTALL) {
11633                                Slog.d(TAG, "    user " + allUsers[i]
11634                                        + " => " + perUserInstalled[i]);
11635                            }
11636                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11637                        }
11638                        // these install state changes will be persisted in the
11639                        // upcoming call to mSettings.writeLPr().
11640                    }
11641                }
11642                // It's implied that when a user requests installation, they want the app to be
11643                // installed and enabled.
11644                int userId = user.getIdentifier();
11645                if (userId != UserHandle.USER_ALL) {
11646                    ps.setInstalled(true, userId);
11647                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11648                }
11649            }
11650            res.name = pkgName;
11651            res.uid = newPackage.applicationInfo.uid;
11652            res.pkg = newPackage;
11653            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11654            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11655            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11656            //to update install status
11657            mSettings.writeLPr();
11658        }
11659    }
11660
11661    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11662        final int installFlags = args.installFlags;
11663        final String installerPackageName = args.installerPackageName;
11664        final String volumeUuid = args.volumeUuid;
11665        final File tmpPackageFile = new File(args.getCodePath());
11666        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11667        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11668                || (args.volumeUuid != null));
11669        boolean replace = false;
11670        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11671        // Result object to be returned
11672        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11673
11674        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11675        // Retrieve PackageSettings and parse package
11676        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11677                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11678                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11679        PackageParser pp = new PackageParser();
11680        pp.setSeparateProcesses(mSeparateProcesses);
11681        pp.setDisplayMetrics(mMetrics);
11682
11683        final PackageParser.Package pkg;
11684        try {
11685            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11686        } catch (PackageParserException e) {
11687            res.setError("Failed parse during installPackageLI", e);
11688            return;
11689        }
11690
11691        // Mark that we have an install time CPU ABI override.
11692        pkg.cpuAbiOverride = args.abiOverride;
11693
11694        String pkgName = res.name = pkg.packageName;
11695        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11696            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11697                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11698                return;
11699            }
11700        }
11701
11702        try {
11703            pp.collectCertificates(pkg, parseFlags);
11704            pp.collectManifestDigest(pkg);
11705        } catch (PackageParserException e) {
11706            res.setError("Failed collect during installPackageLI", e);
11707            return;
11708        }
11709
11710        /* If the installer passed in a manifest digest, compare it now. */
11711        if (args.manifestDigest != null) {
11712            if (DEBUG_INSTALL) {
11713                final String parsedManifest = pkg.manifestDigest == null ? "null"
11714                        : pkg.manifestDigest.toString();
11715                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11716                        + parsedManifest);
11717            }
11718
11719            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11720                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11721                return;
11722            }
11723        } else if (DEBUG_INSTALL) {
11724            final String parsedManifest = pkg.manifestDigest == null
11725                    ? "null" : pkg.manifestDigest.toString();
11726            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11727        }
11728
11729        // Get rid of all references to package scan path via parser.
11730        pp = null;
11731        String oldCodePath = null;
11732        boolean systemApp = false;
11733        synchronized (mPackages) {
11734            // Check if installing already existing package
11735            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11736                String oldName = mSettings.mRenamedPackages.get(pkgName);
11737                if (pkg.mOriginalPackages != null
11738                        && pkg.mOriginalPackages.contains(oldName)
11739                        && mPackages.containsKey(oldName)) {
11740                    // This package is derived from an original package,
11741                    // and this device has been updating from that original
11742                    // name.  We must continue using the original name, so
11743                    // rename the new package here.
11744                    pkg.setPackageName(oldName);
11745                    pkgName = pkg.packageName;
11746                    replace = true;
11747                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11748                            + oldName + " pkgName=" + pkgName);
11749                } else if (mPackages.containsKey(pkgName)) {
11750                    // This package, under its official name, already exists
11751                    // on the device; we should replace it.
11752                    replace = true;
11753                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11754                }
11755
11756                // Prevent apps opting out from runtime permissions
11757                if (replace) {
11758                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11759                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11760                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11761                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11762                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11763                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11764                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11765                                        + " doesn't support runtime permissions but the old"
11766                                        + " target SDK " + oldTargetSdk + " does.");
11767                        return;
11768                    }
11769                }
11770            }
11771
11772            PackageSetting ps = mSettings.mPackages.get(pkgName);
11773            if (ps != null) {
11774                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11775
11776                // Quick sanity check that we're signed correctly if updating;
11777                // we'll check this again later when scanning, but we want to
11778                // bail early here before tripping over redefined permissions.
11779                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11780                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11781                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11782                                + pkg.packageName + " upgrade keys do not match the "
11783                                + "previously installed version");
11784                        return;
11785                    }
11786                } else {
11787                    try {
11788                        verifySignaturesLP(ps, pkg);
11789                    } catch (PackageManagerException e) {
11790                        res.setError(e.error, e.getMessage());
11791                        return;
11792                    }
11793                }
11794
11795                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11796                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11797                    systemApp = (ps.pkg.applicationInfo.flags &
11798                            ApplicationInfo.FLAG_SYSTEM) != 0;
11799                }
11800                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11801            }
11802
11803            // Check whether the newly-scanned package wants to define an already-defined perm
11804            int N = pkg.permissions.size();
11805            for (int i = N-1; i >= 0; i--) {
11806                PackageParser.Permission perm = pkg.permissions.get(i);
11807                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11808                if (bp != null) {
11809                    // If the defining package is signed with our cert, it's okay.  This
11810                    // also includes the "updating the same package" case, of course.
11811                    // "updating same package" could also involve key-rotation.
11812                    final boolean sigsOk;
11813                    if (bp.sourcePackage.equals(pkg.packageName)
11814                            && (bp.packageSetting instanceof PackageSetting)
11815                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11816                                    scanFlags))) {
11817                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11818                    } else {
11819                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11820                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11821                    }
11822                    if (!sigsOk) {
11823                        // If the owning package is the system itself, we log but allow
11824                        // install to proceed; we fail the install on all other permission
11825                        // redefinitions.
11826                        if (!bp.sourcePackage.equals("android")) {
11827                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11828                                    + pkg.packageName + " attempting to redeclare permission "
11829                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11830                            res.origPermission = perm.info.name;
11831                            res.origPackage = bp.sourcePackage;
11832                            return;
11833                        } else {
11834                            Slog.w(TAG, "Package " + pkg.packageName
11835                                    + " attempting to redeclare system permission "
11836                                    + perm.info.name + "; ignoring new declaration");
11837                            pkg.permissions.remove(i);
11838                        }
11839                    }
11840                }
11841            }
11842
11843        }
11844
11845        if (systemApp && onExternal) {
11846            // Disable updates to system apps on sdcard
11847            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11848                    "Cannot install updates to system apps on sdcard");
11849            return;
11850        }
11851
11852        if (args.move != null) {
11853            // We did an in-place move, so dex is ready to roll
11854            scanFlags |= SCAN_NO_DEX;
11855            scanFlags |= SCAN_MOVE;
11856        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11857            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11858            scanFlags |= SCAN_NO_DEX;
11859
11860            try {
11861                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11862                        true /* extract libs */);
11863            } catch (PackageManagerException pme) {
11864                Slog.e(TAG, "Error deriving application ABI", pme);
11865                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11866                return;
11867            }
11868
11869            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11870            int result = mPackageDexOptimizer
11871                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11872                            false /* defer */, false /* inclDependencies */);
11873            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11874                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11875                return;
11876            }
11877        }
11878
11879        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11880            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11881            return;
11882        }
11883
11884        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
11885
11886        if (replace) {
11887            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11888                    installerPackageName, volumeUuid, res);
11889        } else {
11890            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11891                    args.user, installerPackageName, volumeUuid, res);
11892        }
11893        synchronized (mPackages) {
11894            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11895            if (ps != null) {
11896                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11897            }
11898        }
11899    }
11900
11901    private void startIntentFilterVerifications(int userId, boolean replacing,
11902            PackageParser.Package pkg) {
11903        if (mIntentFilterVerifierComponent == null) {
11904            Slog.w(TAG, "No IntentFilter verification will not be done as "
11905                    + "there is no IntentFilterVerifier available!");
11906            return;
11907        }
11908
11909        final int verifierUid = getPackageUid(
11910                mIntentFilterVerifierComponent.getPackageName(),
11911                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11912
11913        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11914        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11915        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
11916        mHandler.sendMessage(msg);
11917    }
11918
11919    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
11920            PackageParser.Package pkg) {
11921        int size = pkg.activities.size();
11922        if (size == 0) {
11923            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11924                    "No activity, so no need to verify any IntentFilter!");
11925            return;
11926        }
11927
11928        final boolean hasDomainURLs = hasDomainURLs(pkg);
11929        if (!hasDomainURLs) {
11930            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11931                    "No domain URLs, so no need to verify any IntentFilter!");
11932            return;
11933        }
11934
11935        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11936                + " if any IntentFilter from the " + size
11937                + " Activities needs verification ...");
11938
11939        int count = 0;
11940        final String packageName = pkg.packageName;
11941
11942        synchronized (mPackages) {
11943            // If this is a new install and we see that we've already run verification for this
11944            // package, we have nothing to do: it means the state was restored from backup.
11945            if (!replacing) {
11946                IntentFilterVerificationInfo ivi =
11947                        mSettings.getIntentFilterVerificationLPr(packageName);
11948                if (ivi != null) {
11949                    if (DEBUG_DOMAIN_VERIFICATION) {
11950                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
11951                                + ivi.getStatusString());
11952                    }
11953                    return;
11954                }
11955            }
11956
11957            // If any filters need to be verified, then all need to be.
11958            boolean needToVerify = false;
11959            for (PackageParser.Activity a : pkg.activities) {
11960                for (ActivityIntentInfo filter : a.intents) {
11961                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11962                        if (DEBUG_DOMAIN_VERIFICATION) {
11963                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11964                        }
11965                        needToVerify = true;
11966                        break;
11967                    }
11968                }
11969            }
11970
11971            if (needToVerify) {
11972                final int verificationId = mIntentFilterVerificationToken++;
11973                for (PackageParser.Activity a : pkg.activities) {
11974                    for (ActivityIntentInfo filter : a.intents) {
11975                        boolean needsFilterVerification = filter.hasWebDataURI();
11976                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11977                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11978                                    "Verification needed for IntentFilter:" + filter.toString());
11979                            mIntentFilterVerifier.addOneIntentFilterVerification(
11980                                    verifierUid, userId, verificationId, filter, packageName);
11981                            count++;
11982                        }
11983                    }
11984                }
11985            }
11986        }
11987
11988        if (count > 0) {
11989            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11990                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11991                    +  " for userId:" + userId);
11992            mIntentFilterVerifier.startVerifications(userId);
11993        } else {
11994            if (DEBUG_DOMAIN_VERIFICATION) {
11995                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11996            }
11997        }
11998    }
11999
12000    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12001        final ComponentName cn  = filter.activity.getComponentName();
12002        final String packageName = cn.getPackageName();
12003
12004        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12005                packageName);
12006        if (ivi == null) {
12007            return true;
12008        }
12009        int status = ivi.getStatus();
12010        switch (status) {
12011            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12012            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12013                return true;
12014
12015            default:
12016                // Nothing to do
12017                return false;
12018        }
12019    }
12020
12021    private static boolean isMultiArch(PackageSetting ps) {
12022        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12023    }
12024
12025    private static boolean isMultiArch(ApplicationInfo info) {
12026        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12027    }
12028
12029    private static boolean isExternal(PackageParser.Package pkg) {
12030        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12031    }
12032
12033    private static boolean isExternal(PackageSetting ps) {
12034        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12035    }
12036
12037    private static boolean isExternal(ApplicationInfo info) {
12038        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12039    }
12040
12041    private static boolean isSystemApp(PackageParser.Package pkg) {
12042        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12043    }
12044
12045    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12046        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12047    }
12048
12049    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12050        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12051    }
12052
12053    private static boolean isSystemApp(PackageSetting ps) {
12054        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12055    }
12056
12057    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12058        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12059    }
12060
12061    private int packageFlagsToInstallFlags(PackageSetting ps) {
12062        int installFlags = 0;
12063        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12064            // This existing package was an external ASEC install when we have
12065            // the external flag without a UUID
12066            installFlags |= PackageManager.INSTALL_EXTERNAL;
12067        }
12068        if (ps.isForwardLocked()) {
12069            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12070        }
12071        return installFlags;
12072    }
12073
12074    private void deleteTempPackageFiles() {
12075        final FilenameFilter filter = new FilenameFilter() {
12076            public boolean accept(File dir, String name) {
12077                return name.startsWith("vmdl") && name.endsWith(".tmp");
12078            }
12079        };
12080        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12081            file.delete();
12082        }
12083    }
12084
12085    @Override
12086    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12087            int flags) {
12088        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12089                flags);
12090    }
12091
12092    @Override
12093    public void deletePackage(final String packageName,
12094            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12095        mContext.enforceCallingOrSelfPermission(
12096                android.Manifest.permission.DELETE_PACKAGES, null);
12097        final int uid = Binder.getCallingUid();
12098        if (UserHandle.getUserId(uid) != userId) {
12099            mContext.enforceCallingPermission(
12100                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12101                    "deletePackage for user " + userId);
12102        }
12103        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12104            try {
12105                observer.onPackageDeleted(packageName,
12106                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12107            } catch (RemoteException re) {
12108            }
12109            return;
12110        }
12111
12112        boolean uninstallBlocked = false;
12113        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12114            int[] users = sUserManager.getUserIds();
12115            for (int i = 0; i < users.length; ++i) {
12116                if (getBlockUninstallForUser(packageName, users[i])) {
12117                    uninstallBlocked = true;
12118                    break;
12119                }
12120            }
12121        } else {
12122            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12123        }
12124        if (uninstallBlocked) {
12125            try {
12126                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12127                        null);
12128            } catch (RemoteException re) {
12129            }
12130            return;
12131        }
12132
12133        if (DEBUG_REMOVE) {
12134            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12135        }
12136        // Queue up an async operation since the package deletion may take a little while.
12137        mHandler.post(new Runnable() {
12138            public void run() {
12139                mHandler.removeCallbacks(this);
12140                final int returnCode = deletePackageX(packageName, userId, flags);
12141                if (observer != null) {
12142                    try {
12143                        observer.onPackageDeleted(packageName, returnCode, null);
12144                    } catch (RemoteException e) {
12145                        Log.i(TAG, "Observer no longer exists.");
12146                    } //end catch
12147                } //end if
12148            } //end run
12149        });
12150    }
12151
12152    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12153        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12154                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12155        try {
12156            if (dpm != null) {
12157                if (dpm.isDeviceOwner(packageName)) {
12158                    return true;
12159                }
12160                int[] users;
12161                if (userId == UserHandle.USER_ALL) {
12162                    users = sUserManager.getUserIds();
12163                } else {
12164                    users = new int[]{userId};
12165                }
12166                for (int i = 0; i < users.length; ++i) {
12167                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12168                        return true;
12169                    }
12170                }
12171            }
12172        } catch (RemoteException e) {
12173        }
12174        return false;
12175    }
12176
12177    /**
12178     *  This method is an internal method that could be get invoked either
12179     *  to delete an installed package or to clean up a failed installation.
12180     *  After deleting an installed package, a broadcast is sent to notify any
12181     *  listeners that the package has been installed. For cleaning up a failed
12182     *  installation, the broadcast is not necessary since the package's
12183     *  installation wouldn't have sent the initial broadcast either
12184     *  The key steps in deleting a package are
12185     *  deleting the package information in internal structures like mPackages,
12186     *  deleting the packages base directories through installd
12187     *  updating mSettings to reflect current status
12188     *  persisting settings for later use
12189     *  sending a broadcast if necessary
12190     */
12191    private int deletePackageX(String packageName, int userId, int flags) {
12192        final PackageRemovedInfo info = new PackageRemovedInfo();
12193        final boolean res;
12194
12195        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12196                ? UserHandle.ALL : new UserHandle(userId);
12197
12198        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12199            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12200            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12201        }
12202
12203        boolean removedForAllUsers = false;
12204        boolean systemUpdate = false;
12205
12206        // for the uninstall-updates case and restricted profiles, remember the per-
12207        // userhandle installed state
12208        int[] allUsers;
12209        boolean[] perUserInstalled;
12210        synchronized (mPackages) {
12211            PackageSetting ps = mSettings.mPackages.get(packageName);
12212            allUsers = sUserManager.getUserIds();
12213            perUserInstalled = new boolean[allUsers.length];
12214            for (int i = 0; i < allUsers.length; i++) {
12215                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12216            }
12217        }
12218
12219        synchronized (mInstallLock) {
12220            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12221            res = deletePackageLI(packageName, removeForUser,
12222                    true, allUsers, perUserInstalled,
12223                    flags | REMOVE_CHATTY, info, true);
12224            systemUpdate = info.isRemovedPackageSystemUpdate;
12225            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12226                removedForAllUsers = true;
12227            }
12228            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12229                    + " removedForAllUsers=" + removedForAllUsers);
12230        }
12231
12232        if (res) {
12233            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12234
12235            // If the removed package was a system update, the old system package
12236            // was re-enabled; we need to broadcast this information
12237            if (systemUpdate) {
12238                Bundle extras = new Bundle(1);
12239                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12240                        ? info.removedAppId : info.uid);
12241                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12242
12243                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12244                        extras, null, null, null);
12245                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12246                        extras, null, null, null);
12247                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12248                        null, packageName, null, null);
12249            }
12250        }
12251        // Force a gc here.
12252        Runtime.getRuntime().gc();
12253        // Delete the resources here after sending the broadcast to let
12254        // other processes clean up before deleting resources.
12255        if (info.args != null) {
12256            synchronized (mInstallLock) {
12257                info.args.doPostDeleteLI(true);
12258            }
12259        }
12260
12261        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12262    }
12263
12264    class PackageRemovedInfo {
12265        String removedPackage;
12266        int uid = -1;
12267        int removedAppId = -1;
12268        int[] removedUsers = null;
12269        boolean isRemovedPackageSystemUpdate = false;
12270        // Clean up resources deleted packages.
12271        InstallArgs args = null;
12272
12273        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12274            Bundle extras = new Bundle(1);
12275            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12276            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12277            if (replacing) {
12278                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12279            }
12280            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12281            if (removedPackage != null) {
12282                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12283                        extras, null, null, removedUsers);
12284                if (fullRemove && !replacing) {
12285                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12286                            extras, null, null, removedUsers);
12287                }
12288            }
12289            if (removedAppId >= 0) {
12290                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12291                        removedUsers);
12292            }
12293        }
12294    }
12295
12296    /*
12297     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12298     * flag is not set, the data directory is removed as well.
12299     * make sure this flag is set for partially installed apps. If not its meaningless to
12300     * delete a partially installed application.
12301     */
12302    private void removePackageDataLI(PackageSetting ps,
12303            int[] allUserHandles, boolean[] perUserInstalled,
12304            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12305        String packageName = ps.name;
12306        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12307        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12308        // Retrieve object to delete permissions for shared user later on
12309        final PackageSetting deletedPs;
12310        // reader
12311        synchronized (mPackages) {
12312            deletedPs = mSettings.mPackages.get(packageName);
12313            if (outInfo != null) {
12314                outInfo.removedPackage = packageName;
12315                outInfo.removedUsers = deletedPs != null
12316                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12317                        : null;
12318            }
12319        }
12320        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12321            removeDataDirsLI(ps.volumeUuid, packageName);
12322            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12323        }
12324        // writer
12325        synchronized (mPackages) {
12326            if (deletedPs != null) {
12327                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12328                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12329                    clearDefaultBrowserIfNeeded(packageName);
12330                    if (outInfo != null) {
12331                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12332                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12333                    }
12334                    updatePermissionsLPw(deletedPs.name, null, 0);
12335                    if (deletedPs.sharedUser != null) {
12336                        // Remove permissions associated with package. Since runtime
12337                        // permissions are per user we have to kill the removed package
12338                        // or packages running under the shared user of the removed
12339                        // package if revoking the permissions requested only by the removed
12340                        // package is successful and this causes a change in gids.
12341                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12342                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12343                                    userId);
12344                            if (userIdToKill == UserHandle.USER_ALL
12345                                    || userIdToKill >= UserHandle.USER_OWNER) {
12346                                // If gids changed for this user, kill all affected packages.
12347                                mHandler.post(new Runnable() {
12348                                    @Override
12349                                    public void run() {
12350                                        // This has to happen with no lock held.
12351                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12352                                                KILL_APP_REASON_GIDS_CHANGED);
12353                                    }
12354                                });
12355                            break;
12356                            }
12357                        }
12358                    }
12359                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12360                }
12361                // make sure to preserve per-user disabled state if this removal was just
12362                // a downgrade of a system app to the factory package
12363                if (allUserHandles != null && perUserInstalled != null) {
12364                    if (DEBUG_REMOVE) {
12365                        Slog.d(TAG, "Propagating install state across downgrade");
12366                    }
12367                    for (int i = 0; i < allUserHandles.length; i++) {
12368                        if (DEBUG_REMOVE) {
12369                            Slog.d(TAG, "    user " + allUserHandles[i]
12370                                    + " => " + perUserInstalled[i]);
12371                        }
12372                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12373                    }
12374                }
12375            }
12376            // can downgrade to reader
12377            if (writeSettings) {
12378                // Save settings now
12379                mSettings.writeLPr();
12380            }
12381        }
12382        if (outInfo != null) {
12383            // A user ID was deleted here. Go through all users and remove it
12384            // from KeyStore.
12385            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12386        }
12387    }
12388
12389    static boolean locationIsPrivileged(File path) {
12390        try {
12391            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12392                    .getCanonicalPath();
12393            return path.getCanonicalPath().startsWith(privilegedAppDir);
12394        } catch (IOException e) {
12395            Slog.e(TAG, "Unable to access code path " + path);
12396        }
12397        return false;
12398    }
12399
12400    /*
12401     * Tries to delete system package.
12402     */
12403    private boolean deleteSystemPackageLI(PackageSetting newPs,
12404            int[] allUserHandles, boolean[] perUserInstalled,
12405            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12406        final boolean applyUserRestrictions
12407                = (allUserHandles != null) && (perUserInstalled != null);
12408        PackageSetting disabledPs = null;
12409        // Confirm if the system package has been updated
12410        // An updated system app can be deleted. This will also have to restore
12411        // the system pkg from system partition
12412        // reader
12413        synchronized (mPackages) {
12414            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12415        }
12416        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12417                + " disabledPs=" + disabledPs);
12418        if (disabledPs == null) {
12419            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12420            return false;
12421        } else if (DEBUG_REMOVE) {
12422            Slog.d(TAG, "Deleting system pkg from data partition");
12423        }
12424        if (DEBUG_REMOVE) {
12425            if (applyUserRestrictions) {
12426                Slog.d(TAG, "Remembering install states:");
12427                for (int i = 0; i < allUserHandles.length; i++) {
12428                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12429                }
12430            }
12431        }
12432        // Delete the updated package
12433        outInfo.isRemovedPackageSystemUpdate = true;
12434        if (disabledPs.versionCode < newPs.versionCode) {
12435            // Delete data for downgrades
12436            flags &= ~PackageManager.DELETE_KEEP_DATA;
12437        } else {
12438            // Preserve data by setting flag
12439            flags |= PackageManager.DELETE_KEEP_DATA;
12440        }
12441        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12442                allUserHandles, perUserInstalled, outInfo, writeSettings);
12443        if (!ret) {
12444            return false;
12445        }
12446        // writer
12447        synchronized (mPackages) {
12448            // Reinstate the old system package
12449            mSettings.enableSystemPackageLPw(newPs.name);
12450            // Remove any native libraries from the upgraded package.
12451            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12452        }
12453        // Install the system package
12454        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12455        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12456        if (locationIsPrivileged(disabledPs.codePath)) {
12457            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12458        }
12459
12460        final PackageParser.Package newPkg;
12461        try {
12462            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12463        } catch (PackageManagerException e) {
12464            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12465            return false;
12466        }
12467
12468        // writer
12469        synchronized (mPackages) {
12470            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12471            updatePermissionsLPw(newPkg.packageName, newPkg,
12472                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12473            if (applyUserRestrictions) {
12474                if (DEBUG_REMOVE) {
12475                    Slog.d(TAG, "Propagating install state across reinstall");
12476                }
12477                for (int i = 0; i < allUserHandles.length; i++) {
12478                    if (DEBUG_REMOVE) {
12479                        Slog.d(TAG, "    user " + allUserHandles[i]
12480                                + " => " + perUserInstalled[i]);
12481                    }
12482                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12483                }
12484                // Regardless of writeSettings we need to ensure that this restriction
12485                // state propagation is persisted
12486                mSettings.writeAllUsersPackageRestrictionsLPr();
12487            }
12488            // can downgrade to reader here
12489            if (writeSettings) {
12490                mSettings.writeLPr();
12491            }
12492        }
12493        return true;
12494    }
12495
12496    private boolean deleteInstalledPackageLI(PackageSetting ps,
12497            boolean deleteCodeAndResources, int flags,
12498            int[] allUserHandles, boolean[] perUserInstalled,
12499            PackageRemovedInfo outInfo, boolean writeSettings) {
12500        if (outInfo != null) {
12501            outInfo.uid = ps.appId;
12502        }
12503
12504        // Delete package data from internal structures and also remove data if flag is set
12505        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12506
12507        // Delete application code and resources
12508        if (deleteCodeAndResources && (outInfo != null)) {
12509            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12510                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12511            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12512        }
12513        return true;
12514    }
12515
12516    @Override
12517    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12518            int userId) {
12519        mContext.enforceCallingOrSelfPermission(
12520                android.Manifest.permission.DELETE_PACKAGES, null);
12521        synchronized (mPackages) {
12522            PackageSetting ps = mSettings.mPackages.get(packageName);
12523            if (ps == null) {
12524                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12525                return false;
12526            }
12527            if (!ps.getInstalled(userId)) {
12528                // Can't block uninstall for an app that is not installed or enabled.
12529                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12530                return false;
12531            }
12532            ps.setBlockUninstall(blockUninstall, userId);
12533            mSettings.writePackageRestrictionsLPr(userId);
12534        }
12535        return true;
12536    }
12537
12538    @Override
12539    public boolean getBlockUninstallForUser(String packageName, int userId) {
12540        synchronized (mPackages) {
12541            PackageSetting ps = mSettings.mPackages.get(packageName);
12542            if (ps == null) {
12543                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12544                return false;
12545            }
12546            return ps.getBlockUninstall(userId);
12547        }
12548    }
12549
12550    /*
12551     * This method handles package deletion in general
12552     */
12553    private boolean deletePackageLI(String packageName, UserHandle user,
12554            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12555            int flags, PackageRemovedInfo outInfo,
12556            boolean writeSettings) {
12557        if (packageName == null) {
12558            Slog.w(TAG, "Attempt to delete null packageName.");
12559            return false;
12560        }
12561        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12562        PackageSetting ps;
12563        boolean dataOnly = false;
12564        int removeUser = -1;
12565        int appId = -1;
12566        synchronized (mPackages) {
12567            ps = mSettings.mPackages.get(packageName);
12568            if (ps == null) {
12569                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12570                return false;
12571            }
12572            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12573                    && user.getIdentifier() != UserHandle.USER_ALL) {
12574                // The caller is asking that the package only be deleted for a single
12575                // user.  To do this, we just mark its uninstalled state and delete
12576                // its data.  If this is a system app, we only allow this to happen if
12577                // they have set the special DELETE_SYSTEM_APP which requests different
12578                // semantics than normal for uninstalling system apps.
12579                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12580                ps.setUserState(user.getIdentifier(),
12581                        COMPONENT_ENABLED_STATE_DEFAULT,
12582                        false, //installed
12583                        true,  //stopped
12584                        true,  //notLaunched
12585                        false, //hidden
12586                        null, null, null,
12587                        false, // blockUninstall
12588                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12589                if (!isSystemApp(ps)) {
12590                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12591                        // Other user still have this package installed, so all
12592                        // we need to do is clear this user's data and save that
12593                        // it is uninstalled.
12594                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12595                        removeUser = user.getIdentifier();
12596                        appId = ps.appId;
12597                        scheduleWritePackageRestrictionsLocked(removeUser);
12598                    } else {
12599                        // We need to set it back to 'installed' so the uninstall
12600                        // broadcasts will be sent correctly.
12601                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12602                        ps.setInstalled(true, user.getIdentifier());
12603                    }
12604                } else {
12605                    // This is a system app, so we assume that the
12606                    // other users still have this package installed, so all
12607                    // we need to do is clear this user's data and save that
12608                    // it is uninstalled.
12609                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12610                    removeUser = user.getIdentifier();
12611                    appId = ps.appId;
12612                    scheduleWritePackageRestrictionsLocked(removeUser);
12613                }
12614            }
12615        }
12616
12617        if (removeUser >= 0) {
12618            // From above, we determined that we are deleting this only
12619            // for a single user.  Continue the work here.
12620            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12621            if (outInfo != null) {
12622                outInfo.removedPackage = packageName;
12623                outInfo.removedAppId = appId;
12624                outInfo.removedUsers = new int[] {removeUser};
12625            }
12626            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12627            removeKeystoreDataIfNeeded(removeUser, appId);
12628            schedulePackageCleaning(packageName, removeUser, false);
12629            synchronized (mPackages) {
12630                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12631                    scheduleWritePackageRestrictionsLocked(removeUser);
12632                }
12633                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12634                        removeUser);
12635            }
12636            return true;
12637        }
12638
12639        if (dataOnly) {
12640            // Delete application data first
12641            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12642            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12643            return true;
12644        }
12645
12646        boolean ret = false;
12647        if (isSystemApp(ps)) {
12648            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12649            // When an updated system application is deleted we delete the existing resources as well and
12650            // fall back to existing code in system partition
12651            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12652                    flags, outInfo, writeSettings);
12653        } else {
12654            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12655            // Kill application pre-emptively especially for apps on sd.
12656            killApplication(packageName, ps.appId, "uninstall pkg");
12657            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12658                    allUserHandles, perUserInstalled,
12659                    outInfo, writeSettings);
12660        }
12661
12662        return ret;
12663    }
12664
12665    private final class ClearStorageConnection implements ServiceConnection {
12666        IMediaContainerService mContainerService;
12667
12668        @Override
12669        public void onServiceConnected(ComponentName name, IBinder service) {
12670            synchronized (this) {
12671                mContainerService = IMediaContainerService.Stub.asInterface(service);
12672                notifyAll();
12673            }
12674        }
12675
12676        @Override
12677        public void onServiceDisconnected(ComponentName name) {
12678        }
12679    }
12680
12681    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12682        final boolean mounted;
12683        if (Environment.isExternalStorageEmulated()) {
12684            mounted = true;
12685        } else {
12686            final String status = Environment.getExternalStorageState();
12687
12688            mounted = status.equals(Environment.MEDIA_MOUNTED)
12689                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12690        }
12691
12692        if (!mounted) {
12693            return;
12694        }
12695
12696        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12697        int[] users;
12698        if (userId == UserHandle.USER_ALL) {
12699            users = sUserManager.getUserIds();
12700        } else {
12701            users = new int[] { userId };
12702        }
12703        final ClearStorageConnection conn = new ClearStorageConnection();
12704        if (mContext.bindServiceAsUser(
12705                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12706            try {
12707                for (int curUser : users) {
12708                    long timeout = SystemClock.uptimeMillis() + 5000;
12709                    synchronized (conn) {
12710                        long now = SystemClock.uptimeMillis();
12711                        while (conn.mContainerService == null && now < timeout) {
12712                            try {
12713                                conn.wait(timeout - now);
12714                            } catch (InterruptedException e) {
12715                            }
12716                        }
12717                    }
12718                    if (conn.mContainerService == null) {
12719                        return;
12720                    }
12721
12722                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12723                    clearDirectory(conn.mContainerService,
12724                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12725                    if (allData) {
12726                        clearDirectory(conn.mContainerService,
12727                                userEnv.buildExternalStorageAppDataDirs(packageName));
12728                        clearDirectory(conn.mContainerService,
12729                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12730                    }
12731                }
12732            } finally {
12733                mContext.unbindService(conn);
12734            }
12735        }
12736    }
12737
12738    @Override
12739    public void clearApplicationUserData(final String packageName,
12740            final IPackageDataObserver observer, final int userId) {
12741        mContext.enforceCallingOrSelfPermission(
12742                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12743        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12744        // Queue up an async operation since the package deletion may take a little while.
12745        mHandler.post(new Runnable() {
12746            public void run() {
12747                mHandler.removeCallbacks(this);
12748                final boolean succeeded;
12749                synchronized (mInstallLock) {
12750                    succeeded = clearApplicationUserDataLI(packageName, userId);
12751                }
12752                clearExternalStorageDataSync(packageName, userId, true);
12753                if (succeeded) {
12754                    // invoke DeviceStorageMonitor's update method to clear any notifications
12755                    DeviceStorageMonitorInternal
12756                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12757                    if (dsm != null) {
12758                        dsm.checkMemory();
12759                    }
12760                }
12761                if(observer != null) {
12762                    try {
12763                        observer.onRemoveCompleted(packageName, succeeded);
12764                    } catch (RemoteException e) {
12765                        Log.i(TAG, "Observer no longer exists.");
12766                    }
12767                } //end if observer
12768            } //end run
12769        });
12770    }
12771
12772    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12773        if (packageName == null) {
12774            Slog.w(TAG, "Attempt to delete null packageName.");
12775            return false;
12776        }
12777
12778        // Try finding details about the requested package
12779        PackageParser.Package pkg;
12780        synchronized (mPackages) {
12781            pkg = mPackages.get(packageName);
12782            if (pkg == null) {
12783                final PackageSetting ps = mSettings.mPackages.get(packageName);
12784                if (ps != null) {
12785                    pkg = ps.pkg;
12786                }
12787            }
12788
12789            if (pkg == null) {
12790                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12791                return false;
12792            }
12793
12794            PackageSetting ps = (PackageSetting) pkg.mExtras;
12795            PermissionsState permissionsState = ps.getPermissionsState();
12796            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12797        }
12798
12799        // Always delete data directories for package, even if we found no other
12800        // record of app. This helps users recover from UID mismatches without
12801        // resorting to a full data wipe.
12802        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12803        if (retCode < 0) {
12804            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12805            return false;
12806        }
12807
12808        final int appId = pkg.applicationInfo.uid;
12809        removeKeystoreDataIfNeeded(userId, appId);
12810
12811        // Create a native library symlink only if we have native libraries
12812        // and if the native libraries are 32 bit libraries. We do not provide
12813        // this symlink for 64 bit libraries.
12814        if (pkg.applicationInfo.primaryCpuAbi != null &&
12815                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12816            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12817            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12818                    nativeLibPath, userId) < 0) {
12819                Slog.w(TAG, "Failed linking native library dir");
12820                return false;
12821            }
12822        }
12823
12824        return true;
12825    }
12826
12827
12828    /**
12829     * Revokes granted runtime permissions and clears resettable flags
12830     * which are flags that can be set by a user interaction.
12831     *
12832     * @param permissionsState The permission state to reset.
12833     * @param userId The device user for which to do a reset.
12834     */
12835    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12836            PermissionsState permissionsState, int userId) {
12837        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12838                | PackageManager.FLAG_PERMISSION_USER_FIXED
12839                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12840
12841        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12842    }
12843
12844    /**
12845     * Revokes granted runtime permissions and clears all flags.
12846     *
12847     * @param permissionsState The permission state to reset.
12848     * @param userId The device user for which to do a reset.
12849     */
12850    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12851            PermissionsState permissionsState, int userId) {
12852        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12853                PackageManager.MASK_PERMISSION_FLAGS);
12854    }
12855
12856    /**
12857     * Revokes granted runtime permissions and clears certain flags.
12858     *
12859     * @param permissionsState The permission state to reset.
12860     * @param userId The device user for which to do a reset.
12861     * @param flags The flags that is going to be reset.
12862     */
12863    private void revokeRuntimePermissionsAndClearFlagsLocked(
12864            PermissionsState permissionsState, int userId, int flags) {
12865        boolean needsWrite = false;
12866
12867        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12868            BasePermission bp = mSettings.mPermissions.get(state.getName());
12869            if (bp != null) {
12870                permissionsState.revokeRuntimePermission(bp, userId);
12871                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12872                needsWrite = true;
12873            }
12874        }
12875
12876        // Ensure default permissions are never cleared.
12877        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
12878
12879        if (needsWrite) {
12880            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12881        }
12882    }
12883
12884    /**
12885     * Remove entries from the keystore daemon. Will only remove it if the
12886     * {@code appId} is valid.
12887     */
12888    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12889        if (appId < 0) {
12890            return;
12891        }
12892
12893        final KeyStore keyStore = KeyStore.getInstance();
12894        if (keyStore != null) {
12895            if (userId == UserHandle.USER_ALL) {
12896                for (final int individual : sUserManager.getUserIds()) {
12897                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12898                }
12899            } else {
12900                keyStore.clearUid(UserHandle.getUid(userId, appId));
12901            }
12902        } else {
12903            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12904        }
12905    }
12906
12907    @Override
12908    public void deleteApplicationCacheFiles(final String packageName,
12909            final IPackageDataObserver observer) {
12910        mContext.enforceCallingOrSelfPermission(
12911                android.Manifest.permission.DELETE_CACHE_FILES, null);
12912        // Queue up an async operation since the package deletion may take a little while.
12913        final int userId = UserHandle.getCallingUserId();
12914        mHandler.post(new Runnable() {
12915            public void run() {
12916                mHandler.removeCallbacks(this);
12917                final boolean succeded;
12918                synchronized (mInstallLock) {
12919                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12920                }
12921                clearExternalStorageDataSync(packageName, userId, false);
12922                if (observer != null) {
12923                    try {
12924                        observer.onRemoveCompleted(packageName, succeded);
12925                    } catch (RemoteException e) {
12926                        Log.i(TAG, "Observer no longer exists.");
12927                    }
12928                } //end if observer
12929            } //end run
12930        });
12931    }
12932
12933    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12934        if (packageName == null) {
12935            Slog.w(TAG, "Attempt to delete null packageName.");
12936            return false;
12937        }
12938        PackageParser.Package p;
12939        synchronized (mPackages) {
12940            p = mPackages.get(packageName);
12941        }
12942        if (p == null) {
12943            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12944            return false;
12945        }
12946        final ApplicationInfo applicationInfo = p.applicationInfo;
12947        if (applicationInfo == null) {
12948            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12949            return false;
12950        }
12951        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12952        if (retCode < 0) {
12953            Slog.w(TAG, "Couldn't remove cache files for package: "
12954                       + packageName + " u" + userId);
12955            return false;
12956        }
12957        return true;
12958    }
12959
12960    @Override
12961    public void getPackageSizeInfo(final String packageName, int userHandle,
12962            final IPackageStatsObserver observer) {
12963        mContext.enforceCallingOrSelfPermission(
12964                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12965        if (packageName == null) {
12966            throw new IllegalArgumentException("Attempt to get size of null packageName");
12967        }
12968
12969        PackageStats stats = new PackageStats(packageName, userHandle);
12970
12971        /*
12972         * Queue up an async operation since the package measurement may take a
12973         * little while.
12974         */
12975        Message msg = mHandler.obtainMessage(INIT_COPY);
12976        msg.obj = new MeasureParams(stats, observer);
12977        mHandler.sendMessage(msg);
12978    }
12979
12980    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12981            PackageStats pStats) {
12982        if (packageName == null) {
12983            Slog.w(TAG, "Attempt to get size of null packageName.");
12984            return false;
12985        }
12986        PackageParser.Package p;
12987        boolean dataOnly = false;
12988        String libDirRoot = null;
12989        String asecPath = null;
12990        PackageSetting ps = null;
12991        synchronized (mPackages) {
12992            p = mPackages.get(packageName);
12993            ps = mSettings.mPackages.get(packageName);
12994            if(p == null) {
12995                dataOnly = true;
12996                if((ps == null) || (ps.pkg == null)) {
12997                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12998                    return false;
12999                }
13000                p = ps.pkg;
13001            }
13002            if (ps != null) {
13003                libDirRoot = ps.legacyNativeLibraryPathString;
13004            }
13005            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13006                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13007                if (secureContainerId != null) {
13008                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13009                }
13010            }
13011        }
13012        String publicSrcDir = null;
13013        if(!dataOnly) {
13014            final ApplicationInfo applicationInfo = p.applicationInfo;
13015            if (applicationInfo == null) {
13016                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13017                return false;
13018            }
13019            if (p.isForwardLocked()) {
13020                publicSrcDir = applicationInfo.getBaseResourcePath();
13021            }
13022        }
13023        // TODO: extend to measure size of split APKs
13024        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13025        // not just the first level.
13026        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13027        // just the primary.
13028        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13029        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13030                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13031        if (res < 0) {
13032            return false;
13033        }
13034
13035        // Fix-up for forward-locked applications in ASEC containers.
13036        if (!isExternal(p)) {
13037            pStats.codeSize += pStats.externalCodeSize;
13038            pStats.externalCodeSize = 0L;
13039        }
13040
13041        return true;
13042    }
13043
13044
13045    @Override
13046    public void addPackageToPreferred(String packageName) {
13047        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13048    }
13049
13050    @Override
13051    public void removePackageFromPreferred(String packageName) {
13052        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13053    }
13054
13055    @Override
13056    public List<PackageInfo> getPreferredPackages(int flags) {
13057        return new ArrayList<PackageInfo>();
13058    }
13059
13060    private int getUidTargetSdkVersionLockedLPr(int uid) {
13061        Object obj = mSettings.getUserIdLPr(uid);
13062        if (obj instanceof SharedUserSetting) {
13063            final SharedUserSetting sus = (SharedUserSetting) obj;
13064            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13065            final Iterator<PackageSetting> it = sus.packages.iterator();
13066            while (it.hasNext()) {
13067                final PackageSetting ps = it.next();
13068                if (ps.pkg != null) {
13069                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13070                    if (v < vers) vers = v;
13071                }
13072            }
13073            return vers;
13074        } else if (obj instanceof PackageSetting) {
13075            final PackageSetting ps = (PackageSetting) obj;
13076            if (ps.pkg != null) {
13077                return ps.pkg.applicationInfo.targetSdkVersion;
13078            }
13079        }
13080        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13081    }
13082
13083    @Override
13084    public void addPreferredActivity(IntentFilter filter, int match,
13085            ComponentName[] set, ComponentName activity, int userId) {
13086        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13087                "Adding preferred");
13088    }
13089
13090    private void addPreferredActivityInternal(IntentFilter filter, int match,
13091            ComponentName[] set, ComponentName activity, boolean always, int userId,
13092            String opname) {
13093        // writer
13094        int callingUid = Binder.getCallingUid();
13095        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13096        if (filter.countActions() == 0) {
13097            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13098            return;
13099        }
13100        synchronized (mPackages) {
13101            if (mContext.checkCallingOrSelfPermission(
13102                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13103                    != PackageManager.PERMISSION_GRANTED) {
13104                if (getUidTargetSdkVersionLockedLPr(callingUid)
13105                        < Build.VERSION_CODES.FROYO) {
13106                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13107                            + callingUid);
13108                    return;
13109                }
13110                mContext.enforceCallingOrSelfPermission(
13111                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13112            }
13113
13114            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13115            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13116                    + userId + ":");
13117            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13118            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13119            scheduleWritePackageRestrictionsLocked(userId);
13120        }
13121    }
13122
13123    @Override
13124    public void replacePreferredActivity(IntentFilter filter, int match,
13125            ComponentName[] set, ComponentName activity, int userId) {
13126        if (filter.countActions() != 1) {
13127            throw new IllegalArgumentException(
13128                    "replacePreferredActivity expects filter to have only 1 action.");
13129        }
13130        if (filter.countDataAuthorities() != 0
13131                || filter.countDataPaths() != 0
13132                || filter.countDataSchemes() > 1
13133                || filter.countDataTypes() != 0) {
13134            throw new IllegalArgumentException(
13135                    "replacePreferredActivity expects filter to have no data authorities, " +
13136                    "paths, or types; and at most one scheme.");
13137        }
13138
13139        final int callingUid = Binder.getCallingUid();
13140        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13141        synchronized (mPackages) {
13142            if (mContext.checkCallingOrSelfPermission(
13143                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13144                    != PackageManager.PERMISSION_GRANTED) {
13145                if (getUidTargetSdkVersionLockedLPr(callingUid)
13146                        < Build.VERSION_CODES.FROYO) {
13147                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13148                            + Binder.getCallingUid());
13149                    return;
13150                }
13151                mContext.enforceCallingOrSelfPermission(
13152                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13153            }
13154
13155            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13156            if (pir != null) {
13157                // Get all of the existing entries that exactly match this filter.
13158                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13159                if (existing != null && existing.size() == 1) {
13160                    PreferredActivity cur = existing.get(0);
13161                    if (DEBUG_PREFERRED) {
13162                        Slog.i(TAG, "Checking replace of preferred:");
13163                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13164                        if (!cur.mPref.mAlways) {
13165                            Slog.i(TAG, "  -- CUR; not mAlways!");
13166                        } else {
13167                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13168                            Slog.i(TAG, "  -- CUR: mSet="
13169                                    + Arrays.toString(cur.mPref.mSetComponents));
13170                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13171                            Slog.i(TAG, "  -- NEW: mMatch="
13172                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13173                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13174                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13175                        }
13176                    }
13177                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13178                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13179                            && cur.mPref.sameSet(set)) {
13180                        // Setting the preferred activity to what it happens to be already
13181                        if (DEBUG_PREFERRED) {
13182                            Slog.i(TAG, "Replacing with same preferred activity "
13183                                    + cur.mPref.mShortComponent + " for user "
13184                                    + userId + ":");
13185                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13186                        }
13187                        return;
13188                    }
13189                }
13190
13191                if (existing != null) {
13192                    if (DEBUG_PREFERRED) {
13193                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13194                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13195                    }
13196                    for (int i = 0; i < existing.size(); i++) {
13197                        PreferredActivity pa = existing.get(i);
13198                        if (DEBUG_PREFERRED) {
13199                            Slog.i(TAG, "Removing existing preferred activity "
13200                                    + pa.mPref.mComponent + ":");
13201                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13202                        }
13203                        pir.removeFilter(pa);
13204                    }
13205                }
13206            }
13207            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13208                    "Replacing preferred");
13209        }
13210    }
13211
13212    @Override
13213    public void clearPackagePreferredActivities(String packageName) {
13214        final int uid = Binder.getCallingUid();
13215        // writer
13216        synchronized (mPackages) {
13217            PackageParser.Package pkg = mPackages.get(packageName);
13218            if (pkg == null || pkg.applicationInfo.uid != uid) {
13219                if (mContext.checkCallingOrSelfPermission(
13220                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13221                        != PackageManager.PERMISSION_GRANTED) {
13222                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13223                            < Build.VERSION_CODES.FROYO) {
13224                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13225                                + Binder.getCallingUid());
13226                        return;
13227                    }
13228                    mContext.enforceCallingOrSelfPermission(
13229                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13230                }
13231            }
13232
13233            int user = UserHandle.getCallingUserId();
13234            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13235                scheduleWritePackageRestrictionsLocked(user);
13236            }
13237        }
13238    }
13239
13240    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13241    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13242        ArrayList<PreferredActivity> removed = null;
13243        boolean changed = false;
13244        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13245            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13246            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13247            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13248                continue;
13249            }
13250            Iterator<PreferredActivity> it = pir.filterIterator();
13251            while (it.hasNext()) {
13252                PreferredActivity pa = it.next();
13253                // Mark entry for removal only if it matches the package name
13254                // and the entry is of type "always".
13255                if (packageName == null ||
13256                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13257                                && pa.mPref.mAlways)) {
13258                    if (removed == null) {
13259                        removed = new ArrayList<PreferredActivity>();
13260                    }
13261                    removed.add(pa);
13262                }
13263            }
13264            if (removed != null) {
13265                for (int j=0; j<removed.size(); j++) {
13266                    PreferredActivity pa = removed.get(j);
13267                    pir.removeFilter(pa);
13268                }
13269                changed = true;
13270            }
13271        }
13272        return changed;
13273    }
13274
13275    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13276    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13277        if (userId == UserHandle.USER_ALL) {
13278            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13279                    sUserManager.getUserIds())) {
13280                for (int oneUserId : sUserManager.getUserIds()) {
13281                    scheduleWritePackageRestrictionsLocked(oneUserId);
13282                }
13283            }
13284        } else {
13285            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13286                scheduleWritePackageRestrictionsLocked(userId);
13287            }
13288        }
13289    }
13290
13291
13292    void clearDefaultBrowserIfNeeded(String packageName) {
13293        for (int oneUserId : sUserManager.getUserIds()) {
13294            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13295            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13296            if (packageName.equals(defaultBrowserPackageName)) {
13297                setDefaultBrowserPackageName(null, oneUserId);
13298            }
13299        }
13300    }
13301
13302    @Override
13303    public void resetPreferredActivities(int userId) {
13304        /* TODO: Actually use userId. Why is it being passed in? */
13305        mContext.enforceCallingOrSelfPermission(
13306                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13307        // writer
13308        synchronized (mPackages) {
13309            int user = UserHandle.getCallingUserId();
13310            clearPackagePreferredActivitiesLPw(null, user);
13311            mSettings.readDefaultPreferredAppsLPw(this, user);
13312            scheduleWritePackageRestrictionsLocked(user);
13313        }
13314    }
13315
13316    @Override
13317    public int getPreferredActivities(List<IntentFilter> outFilters,
13318            List<ComponentName> outActivities, String packageName) {
13319
13320        int num = 0;
13321        final int userId = UserHandle.getCallingUserId();
13322        // reader
13323        synchronized (mPackages) {
13324            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13325            if (pir != null) {
13326                final Iterator<PreferredActivity> it = pir.filterIterator();
13327                while (it.hasNext()) {
13328                    final PreferredActivity pa = it.next();
13329                    if (packageName == null
13330                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13331                                    && pa.mPref.mAlways)) {
13332                        if (outFilters != null) {
13333                            outFilters.add(new IntentFilter(pa));
13334                        }
13335                        if (outActivities != null) {
13336                            outActivities.add(pa.mPref.mComponent);
13337                        }
13338                    }
13339                }
13340            }
13341        }
13342
13343        return num;
13344    }
13345
13346    @Override
13347    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13348            int userId) {
13349        int callingUid = Binder.getCallingUid();
13350        if (callingUid != Process.SYSTEM_UID) {
13351            throw new SecurityException(
13352                    "addPersistentPreferredActivity can only be run by the system");
13353        }
13354        if (filter.countActions() == 0) {
13355            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13356            return;
13357        }
13358        synchronized (mPackages) {
13359            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13360                    " :");
13361            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13362            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13363                    new PersistentPreferredActivity(filter, activity));
13364            scheduleWritePackageRestrictionsLocked(userId);
13365        }
13366    }
13367
13368    @Override
13369    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13370        int callingUid = Binder.getCallingUid();
13371        if (callingUid != Process.SYSTEM_UID) {
13372            throw new SecurityException(
13373                    "clearPackagePersistentPreferredActivities can only be run by the system");
13374        }
13375        ArrayList<PersistentPreferredActivity> removed = null;
13376        boolean changed = false;
13377        synchronized (mPackages) {
13378            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13379                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13380                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13381                        .valueAt(i);
13382                if (userId != thisUserId) {
13383                    continue;
13384                }
13385                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13386                while (it.hasNext()) {
13387                    PersistentPreferredActivity ppa = it.next();
13388                    // Mark entry for removal only if it matches the package name.
13389                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13390                        if (removed == null) {
13391                            removed = new ArrayList<PersistentPreferredActivity>();
13392                        }
13393                        removed.add(ppa);
13394                    }
13395                }
13396                if (removed != null) {
13397                    for (int j=0; j<removed.size(); j++) {
13398                        PersistentPreferredActivity ppa = removed.get(j);
13399                        ppir.removeFilter(ppa);
13400                    }
13401                    changed = true;
13402                }
13403            }
13404
13405            if (changed) {
13406                scheduleWritePackageRestrictionsLocked(userId);
13407            }
13408        }
13409    }
13410
13411    /**
13412     * Common machinery for picking apart a restored XML blob and passing
13413     * it to a caller-supplied functor to be applied to the running system.
13414     */
13415    private void restoreFromXml(XmlPullParser parser, int userId,
13416            String expectedStartTag, BlobXmlRestorer functor)
13417            throws IOException, XmlPullParserException {
13418        int type;
13419        while ((type = parser.next()) != XmlPullParser.START_TAG
13420                && type != XmlPullParser.END_DOCUMENT) {
13421        }
13422        if (type != XmlPullParser.START_TAG) {
13423            // oops didn't find a start tag?!
13424            if (DEBUG_BACKUP) {
13425                Slog.e(TAG, "Didn't find start tag during restore");
13426            }
13427            return;
13428        }
13429
13430        // this is supposed to be TAG_PREFERRED_BACKUP
13431        if (!expectedStartTag.equals(parser.getName())) {
13432            if (DEBUG_BACKUP) {
13433                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13434            }
13435            return;
13436        }
13437
13438        // skip interfering stuff, then we're aligned with the backing implementation
13439        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13440        functor.apply(parser, userId);
13441    }
13442
13443    private interface BlobXmlRestorer {
13444        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13445    }
13446
13447    /**
13448     * Non-Binder method, support for the backup/restore mechanism: write the
13449     * full set of preferred activities in its canonical XML format.  Returns the
13450     * XML output as a byte array, or null if there is none.
13451     */
13452    @Override
13453    public byte[] getPreferredActivityBackup(int userId) {
13454        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13455            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13456        }
13457
13458        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13459        try {
13460            final XmlSerializer serializer = new FastXmlSerializer();
13461            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13462            serializer.startDocument(null, true);
13463            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13464
13465            synchronized (mPackages) {
13466                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13467            }
13468
13469            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13470            serializer.endDocument();
13471            serializer.flush();
13472        } catch (Exception e) {
13473            if (DEBUG_BACKUP) {
13474                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13475            }
13476            return null;
13477        }
13478
13479        return dataStream.toByteArray();
13480    }
13481
13482    @Override
13483    public void restorePreferredActivities(byte[] backup, int userId) {
13484        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13485            throw new SecurityException("Only the system may call restorePreferredActivities()");
13486        }
13487
13488        try {
13489            final XmlPullParser parser = Xml.newPullParser();
13490            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13491            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13492                    new BlobXmlRestorer() {
13493                        @Override
13494                        public void apply(XmlPullParser parser, int userId)
13495                                throws XmlPullParserException, IOException {
13496                            synchronized (mPackages) {
13497                                mSettings.readPreferredActivitiesLPw(parser, userId);
13498                            }
13499                        }
13500                    } );
13501        } catch (Exception e) {
13502            if (DEBUG_BACKUP) {
13503                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13504            }
13505        }
13506    }
13507
13508    /**
13509     * Non-Binder method, support for the backup/restore mechanism: write the
13510     * default browser (etc) settings in its canonical XML format.  Returns the default
13511     * browser XML representation as a byte array, or null if there is none.
13512     */
13513    @Override
13514    public byte[] getDefaultAppsBackup(int userId) {
13515        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13516            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13517        }
13518
13519        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13520        try {
13521            final XmlSerializer serializer = new FastXmlSerializer();
13522            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13523            serializer.startDocument(null, true);
13524            serializer.startTag(null, TAG_DEFAULT_APPS);
13525
13526            synchronized (mPackages) {
13527                mSettings.writeDefaultAppsLPr(serializer, userId);
13528            }
13529
13530            serializer.endTag(null, TAG_DEFAULT_APPS);
13531            serializer.endDocument();
13532            serializer.flush();
13533        } catch (Exception e) {
13534            if (DEBUG_BACKUP) {
13535                Slog.e(TAG, "Unable to write default apps for backup", e);
13536            }
13537            return null;
13538        }
13539
13540        return dataStream.toByteArray();
13541    }
13542
13543    @Override
13544    public void restoreDefaultApps(byte[] backup, int userId) {
13545        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13546            throw new SecurityException("Only the system may call restoreDefaultApps()");
13547        }
13548
13549        try {
13550            final XmlPullParser parser = Xml.newPullParser();
13551            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13552            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13553                    new BlobXmlRestorer() {
13554                        @Override
13555                        public void apply(XmlPullParser parser, int userId)
13556                                throws XmlPullParserException, IOException {
13557                            synchronized (mPackages) {
13558                                mSettings.readDefaultAppsLPw(parser, userId);
13559                            }
13560                        }
13561                    } );
13562        } catch (Exception e) {
13563            if (DEBUG_BACKUP) {
13564                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13565            }
13566        }
13567    }
13568
13569    @Override
13570    public byte[] getIntentFilterVerificationBackup(int userId) {
13571        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13572            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13573        }
13574
13575        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13576        try {
13577            final XmlSerializer serializer = new FastXmlSerializer();
13578            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13579            serializer.startDocument(null, true);
13580            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13581
13582            synchronized (mPackages) {
13583                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13584            }
13585
13586            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13587            serializer.endDocument();
13588            serializer.flush();
13589        } catch (Exception e) {
13590            if (DEBUG_BACKUP) {
13591                Slog.e(TAG, "Unable to write default apps for backup", e);
13592            }
13593            return null;
13594        }
13595
13596        return dataStream.toByteArray();
13597    }
13598
13599    @Override
13600    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13601        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13602            throw new SecurityException("Only the system may call restorePreferredActivities()");
13603        }
13604
13605        try {
13606            final XmlPullParser parser = Xml.newPullParser();
13607            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13608            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13609                    new BlobXmlRestorer() {
13610                        @Override
13611                        public void apply(XmlPullParser parser, int userId)
13612                                throws XmlPullParserException, IOException {
13613                            synchronized (mPackages) {
13614                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13615                                mSettings.writeLPr();
13616                            }
13617                        }
13618                    } );
13619        } catch (Exception e) {
13620            if (DEBUG_BACKUP) {
13621                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13622            }
13623        }
13624    }
13625
13626    @Override
13627    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13628            int sourceUserId, int targetUserId, int flags) {
13629        mContext.enforceCallingOrSelfPermission(
13630                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13631        int callingUid = Binder.getCallingUid();
13632        enforceOwnerRights(ownerPackage, callingUid);
13633        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13634        if (intentFilter.countActions() == 0) {
13635            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13636            return;
13637        }
13638        synchronized (mPackages) {
13639            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13640                    ownerPackage, targetUserId, flags);
13641            CrossProfileIntentResolver resolver =
13642                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13643            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13644            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13645            if (existing != null) {
13646                int size = existing.size();
13647                for (int i = 0; i < size; i++) {
13648                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13649                        return;
13650                    }
13651                }
13652            }
13653            resolver.addFilter(newFilter);
13654            scheduleWritePackageRestrictionsLocked(sourceUserId);
13655        }
13656    }
13657
13658    @Override
13659    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13660        mContext.enforceCallingOrSelfPermission(
13661                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13662        int callingUid = Binder.getCallingUid();
13663        enforceOwnerRights(ownerPackage, callingUid);
13664        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13665        synchronized (mPackages) {
13666            CrossProfileIntentResolver resolver =
13667                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13668            ArraySet<CrossProfileIntentFilter> set =
13669                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13670            for (CrossProfileIntentFilter filter : set) {
13671                if (filter.getOwnerPackage().equals(ownerPackage)) {
13672                    resolver.removeFilter(filter);
13673                }
13674            }
13675            scheduleWritePackageRestrictionsLocked(sourceUserId);
13676        }
13677    }
13678
13679    // Enforcing that callingUid is owning pkg on userId
13680    private void enforceOwnerRights(String pkg, int callingUid) {
13681        // The system owns everything.
13682        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13683            return;
13684        }
13685        int callingUserId = UserHandle.getUserId(callingUid);
13686        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13687        if (pi == null) {
13688            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13689                    + callingUserId);
13690        }
13691        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13692            throw new SecurityException("Calling uid " + callingUid
13693                    + " does not own package " + pkg);
13694        }
13695    }
13696
13697    @Override
13698    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13699        Intent intent = new Intent(Intent.ACTION_MAIN);
13700        intent.addCategory(Intent.CATEGORY_HOME);
13701
13702        final int callingUserId = UserHandle.getCallingUserId();
13703        List<ResolveInfo> list = queryIntentActivities(intent, null,
13704                PackageManager.GET_META_DATA, callingUserId);
13705        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13706                true, false, false, callingUserId);
13707
13708        allHomeCandidates.clear();
13709        if (list != null) {
13710            for (ResolveInfo ri : list) {
13711                allHomeCandidates.add(ri);
13712            }
13713        }
13714        return (preferred == null || preferred.activityInfo == null)
13715                ? null
13716                : new ComponentName(preferred.activityInfo.packageName,
13717                        preferred.activityInfo.name);
13718    }
13719
13720    @Override
13721    public void setApplicationEnabledSetting(String appPackageName,
13722            int newState, int flags, int userId, String callingPackage) {
13723        if (!sUserManager.exists(userId)) return;
13724        if (callingPackage == null) {
13725            callingPackage = Integer.toString(Binder.getCallingUid());
13726        }
13727        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13728    }
13729
13730    @Override
13731    public void setComponentEnabledSetting(ComponentName componentName,
13732            int newState, int flags, int userId) {
13733        if (!sUserManager.exists(userId)) return;
13734        setEnabledSetting(componentName.getPackageName(),
13735                componentName.getClassName(), newState, flags, userId, null);
13736    }
13737
13738    private void setEnabledSetting(final String packageName, String className, int newState,
13739            final int flags, int userId, String callingPackage) {
13740        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13741              || newState == COMPONENT_ENABLED_STATE_ENABLED
13742              || newState == COMPONENT_ENABLED_STATE_DISABLED
13743              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13744              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13745            throw new IllegalArgumentException("Invalid new component state: "
13746                    + newState);
13747        }
13748        PackageSetting pkgSetting;
13749        final int uid = Binder.getCallingUid();
13750        final int permission = mContext.checkCallingOrSelfPermission(
13751                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13752        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13753        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13754        boolean sendNow = false;
13755        boolean isApp = (className == null);
13756        String componentName = isApp ? packageName : className;
13757        int packageUid = -1;
13758        ArrayList<String> components;
13759
13760        // writer
13761        synchronized (mPackages) {
13762            pkgSetting = mSettings.mPackages.get(packageName);
13763            if (pkgSetting == null) {
13764                if (className == null) {
13765                    throw new IllegalArgumentException(
13766                            "Unknown package: " + packageName);
13767                }
13768                throw new IllegalArgumentException(
13769                        "Unknown component: " + packageName
13770                        + "/" + className);
13771            }
13772            // Allow root and verify that userId is not being specified by a different user
13773            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13774                throw new SecurityException(
13775                        "Permission Denial: attempt to change component state from pid="
13776                        + Binder.getCallingPid()
13777                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13778            }
13779            if (className == null) {
13780                // We're dealing with an application/package level state change
13781                if (pkgSetting.getEnabled(userId) == newState) {
13782                    // Nothing to do
13783                    return;
13784                }
13785                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13786                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13787                    // Don't care about who enables an app.
13788                    callingPackage = null;
13789                }
13790                pkgSetting.setEnabled(newState, userId, callingPackage);
13791                // pkgSetting.pkg.mSetEnabled = newState;
13792            } else {
13793                // We're dealing with a component level state change
13794                // First, verify that this is a valid class name.
13795                PackageParser.Package pkg = pkgSetting.pkg;
13796                if (pkg == null || !pkg.hasComponentClassName(className)) {
13797                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13798                        throw new IllegalArgumentException("Component class " + className
13799                                + " does not exist in " + packageName);
13800                    } else {
13801                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13802                                + className + " does not exist in " + packageName);
13803                    }
13804                }
13805                switch (newState) {
13806                case COMPONENT_ENABLED_STATE_ENABLED:
13807                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13808                        return;
13809                    }
13810                    break;
13811                case COMPONENT_ENABLED_STATE_DISABLED:
13812                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13813                        return;
13814                    }
13815                    break;
13816                case COMPONENT_ENABLED_STATE_DEFAULT:
13817                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13818                        return;
13819                    }
13820                    break;
13821                default:
13822                    Slog.e(TAG, "Invalid new component state: " + newState);
13823                    return;
13824                }
13825            }
13826            scheduleWritePackageRestrictionsLocked(userId);
13827            components = mPendingBroadcasts.get(userId, packageName);
13828            final boolean newPackage = components == null;
13829            if (newPackage) {
13830                components = new ArrayList<String>();
13831            }
13832            if (!components.contains(componentName)) {
13833                components.add(componentName);
13834            }
13835            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13836                sendNow = true;
13837                // Purge entry from pending broadcast list if another one exists already
13838                // since we are sending one right away.
13839                mPendingBroadcasts.remove(userId, packageName);
13840            } else {
13841                if (newPackage) {
13842                    mPendingBroadcasts.put(userId, packageName, components);
13843                }
13844                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13845                    // Schedule a message
13846                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13847                }
13848            }
13849        }
13850
13851        long callingId = Binder.clearCallingIdentity();
13852        try {
13853            if (sendNow) {
13854                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13855                sendPackageChangedBroadcast(packageName,
13856                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13857            }
13858        } finally {
13859            Binder.restoreCallingIdentity(callingId);
13860        }
13861    }
13862
13863    private void sendPackageChangedBroadcast(String packageName,
13864            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13865        if (DEBUG_INSTALL)
13866            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13867                    + componentNames);
13868        Bundle extras = new Bundle(4);
13869        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13870        String nameList[] = new String[componentNames.size()];
13871        componentNames.toArray(nameList);
13872        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13873        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13874        extras.putInt(Intent.EXTRA_UID, packageUid);
13875        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13876                new int[] {UserHandle.getUserId(packageUid)});
13877    }
13878
13879    @Override
13880    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13881        if (!sUserManager.exists(userId)) return;
13882        final int uid = Binder.getCallingUid();
13883        final int permission = mContext.checkCallingOrSelfPermission(
13884                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13885        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13886        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13887        // writer
13888        synchronized (mPackages) {
13889            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13890                    allowedByPermission, uid, userId)) {
13891                scheduleWritePackageRestrictionsLocked(userId);
13892            }
13893        }
13894    }
13895
13896    @Override
13897    public String getInstallerPackageName(String packageName) {
13898        // reader
13899        synchronized (mPackages) {
13900            return mSettings.getInstallerPackageNameLPr(packageName);
13901        }
13902    }
13903
13904    @Override
13905    public int getApplicationEnabledSetting(String packageName, int userId) {
13906        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13907        int uid = Binder.getCallingUid();
13908        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13909        // reader
13910        synchronized (mPackages) {
13911            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13912        }
13913    }
13914
13915    @Override
13916    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13917        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13918        int uid = Binder.getCallingUid();
13919        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13920        // reader
13921        synchronized (mPackages) {
13922            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13923        }
13924    }
13925
13926    @Override
13927    public void enterSafeMode() {
13928        enforceSystemOrRoot("Only the system can request entering safe mode");
13929
13930        if (!mSystemReady) {
13931            mSafeMode = true;
13932        }
13933    }
13934
13935    @Override
13936    public void systemReady() {
13937        mSystemReady = true;
13938
13939        // Read the compatibilty setting when the system is ready.
13940        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13941                mContext.getContentResolver(),
13942                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13943        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13944        if (DEBUG_SETTINGS) {
13945            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13946        }
13947
13948        synchronized (mPackages) {
13949            // Verify that all of the preferred activity components actually
13950            // exist.  It is possible for applications to be updated and at
13951            // that point remove a previously declared activity component that
13952            // had been set as a preferred activity.  We try to clean this up
13953            // the next time we encounter that preferred activity, but it is
13954            // possible for the user flow to never be able to return to that
13955            // situation so here we do a sanity check to make sure we haven't
13956            // left any junk around.
13957            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13958            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13959                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13960                removed.clear();
13961                for (PreferredActivity pa : pir.filterSet()) {
13962                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13963                        removed.add(pa);
13964                    }
13965                }
13966                if (removed.size() > 0) {
13967                    for (int r=0; r<removed.size(); r++) {
13968                        PreferredActivity pa = removed.get(r);
13969                        Slog.w(TAG, "Removing dangling preferred activity: "
13970                                + pa.mPref.mComponent);
13971                        pir.removeFilter(pa);
13972                    }
13973                    mSettings.writePackageRestrictionsLPr(
13974                            mSettings.mPreferredActivities.keyAt(i));
13975                }
13976            }
13977        }
13978        sUserManager.systemReady();
13979
13980        // If we upgraded grant all default permissions before kicking off.
13981        if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) {
13982            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
13983            for (int userId : UserManagerService.getInstance().getUserIds()) {
13984                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13985            }
13986        }
13987
13988        // Kick off any messages waiting for system ready
13989        if (mPostSystemReadyMessages != null) {
13990            for (Message msg : mPostSystemReadyMessages) {
13991                msg.sendToTarget();
13992            }
13993            mPostSystemReadyMessages = null;
13994        }
13995
13996        // Watch for external volumes that come and go over time
13997        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13998        storage.registerListener(mStorageListener);
13999
14000        mInstallerService.systemReady();
14001        mPackageDexOptimizer.systemReady();
14002    }
14003
14004    @Override
14005    public boolean isSafeMode() {
14006        return mSafeMode;
14007    }
14008
14009    @Override
14010    public boolean hasSystemUidErrors() {
14011        return mHasSystemUidErrors;
14012    }
14013
14014    static String arrayToString(int[] array) {
14015        StringBuffer buf = new StringBuffer(128);
14016        buf.append('[');
14017        if (array != null) {
14018            for (int i=0; i<array.length; i++) {
14019                if (i > 0) buf.append(", ");
14020                buf.append(array[i]);
14021            }
14022        }
14023        buf.append(']');
14024        return buf.toString();
14025    }
14026
14027    static class DumpState {
14028        public static final int DUMP_LIBS = 1 << 0;
14029        public static final int DUMP_FEATURES = 1 << 1;
14030        public static final int DUMP_RESOLVERS = 1 << 2;
14031        public static final int DUMP_PERMISSIONS = 1 << 3;
14032        public static final int DUMP_PACKAGES = 1 << 4;
14033        public static final int DUMP_SHARED_USERS = 1 << 5;
14034        public static final int DUMP_MESSAGES = 1 << 6;
14035        public static final int DUMP_PROVIDERS = 1 << 7;
14036        public static final int DUMP_VERIFIERS = 1 << 8;
14037        public static final int DUMP_PREFERRED = 1 << 9;
14038        public static final int DUMP_PREFERRED_XML = 1 << 10;
14039        public static final int DUMP_KEYSETS = 1 << 11;
14040        public static final int DUMP_VERSION = 1 << 12;
14041        public static final int DUMP_INSTALLS = 1 << 13;
14042        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14043        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14044
14045        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14046
14047        private int mTypes;
14048
14049        private int mOptions;
14050
14051        private boolean mTitlePrinted;
14052
14053        private SharedUserSetting mSharedUser;
14054
14055        public boolean isDumping(int type) {
14056            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14057                return true;
14058            }
14059
14060            return (mTypes & type) != 0;
14061        }
14062
14063        public void setDump(int type) {
14064            mTypes |= type;
14065        }
14066
14067        public boolean isOptionEnabled(int option) {
14068            return (mOptions & option) != 0;
14069        }
14070
14071        public void setOptionEnabled(int option) {
14072            mOptions |= option;
14073        }
14074
14075        public boolean onTitlePrinted() {
14076            final boolean printed = mTitlePrinted;
14077            mTitlePrinted = true;
14078            return printed;
14079        }
14080
14081        public boolean getTitlePrinted() {
14082            return mTitlePrinted;
14083        }
14084
14085        public void setTitlePrinted(boolean enabled) {
14086            mTitlePrinted = enabled;
14087        }
14088
14089        public SharedUserSetting getSharedUser() {
14090            return mSharedUser;
14091        }
14092
14093        public void setSharedUser(SharedUserSetting user) {
14094            mSharedUser = user;
14095        }
14096    }
14097
14098    @Override
14099    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14100        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14101                != PackageManager.PERMISSION_GRANTED) {
14102            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14103                    + Binder.getCallingPid()
14104                    + ", uid=" + Binder.getCallingUid()
14105                    + " without permission "
14106                    + android.Manifest.permission.DUMP);
14107            return;
14108        }
14109
14110        DumpState dumpState = new DumpState();
14111        boolean fullPreferred = false;
14112        boolean checkin = false;
14113
14114        String packageName = null;
14115
14116        int opti = 0;
14117        while (opti < args.length) {
14118            String opt = args[opti];
14119            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14120                break;
14121            }
14122            opti++;
14123
14124            if ("-a".equals(opt)) {
14125                // Right now we only know how to print all.
14126            } else if ("-h".equals(opt)) {
14127                pw.println("Package manager dump options:");
14128                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14129                pw.println("    --checkin: dump for a checkin");
14130                pw.println("    -f: print details of intent filters");
14131                pw.println("    -h: print this help");
14132                pw.println("  cmd may be one of:");
14133                pw.println("    l[ibraries]: list known shared libraries");
14134                pw.println("    f[ibraries]: list device features");
14135                pw.println("    k[eysets]: print known keysets");
14136                pw.println("    r[esolvers]: dump intent resolvers");
14137                pw.println("    perm[issions]: dump permissions");
14138                pw.println("    pref[erred]: print preferred package settings");
14139                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14140                pw.println("    prov[iders]: dump content providers");
14141                pw.println("    p[ackages]: dump installed packages");
14142                pw.println("    s[hared-users]: dump shared user IDs");
14143                pw.println("    m[essages]: print collected runtime messages");
14144                pw.println("    v[erifiers]: print package verifier info");
14145                pw.println("    version: print database version info");
14146                pw.println("    write: write current settings now");
14147                pw.println("    <package.name>: info about given package");
14148                pw.println("    installs: details about install sessions");
14149                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14150                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14151                return;
14152            } else if ("--checkin".equals(opt)) {
14153                checkin = true;
14154            } else if ("-f".equals(opt)) {
14155                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14156            } else {
14157                pw.println("Unknown argument: " + opt + "; use -h for help");
14158            }
14159        }
14160
14161        // Is the caller requesting to dump a particular piece of data?
14162        if (opti < args.length) {
14163            String cmd = args[opti];
14164            opti++;
14165            // Is this a package name?
14166            if ("android".equals(cmd) || cmd.contains(".")) {
14167                packageName = cmd;
14168                // When dumping a single package, we always dump all of its
14169                // filter information since the amount of data will be reasonable.
14170                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14171            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14172                dumpState.setDump(DumpState.DUMP_LIBS);
14173            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14174                dumpState.setDump(DumpState.DUMP_FEATURES);
14175            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14176                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14177            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14178                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14179            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14180                dumpState.setDump(DumpState.DUMP_PREFERRED);
14181            } else if ("preferred-xml".equals(cmd)) {
14182                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14183                if (opti < args.length && "--full".equals(args[opti])) {
14184                    fullPreferred = true;
14185                    opti++;
14186                }
14187            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14188                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14189            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14190                dumpState.setDump(DumpState.DUMP_PACKAGES);
14191            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14192                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14193            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14194                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14195            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14196                dumpState.setDump(DumpState.DUMP_MESSAGES);
14197            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14198                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14199            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14200                    || "intent-filter-verifiers".equals(cmd)) {
14201                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14202            } else if ("version".equals(cmd)) {
14203                dumpState.setDump(DumpState.DUMP_VERSION);
14204            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14205                dumpState.setDump(DumpState.DUMP_KEYSETS);
14206            } else if ("installs".equals(cmd)) {
14207                dumpState.setDump(DumpState.DUMP_INSTALLS);
14208            } else if ("write".equals(cmd)) {
14209                synchronized (mPackages) {
14210                    mSettings.writeLPr();
14211                    pw.println("Settings written.");
14212                    return;
14213                }
14214            }
14215        }
14216
14217        if (checkin) {
14218            pw.println("vers,1");
14219        }
14220
14221        // reader
14222        synchronized (mPackages) {
14223            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14224                if (!checkin) {
14225                    if (dumpState.onTitlePrinted())
14226                        pw.println();
14227                    pw.println("Database versions:");
14228                    pw.print("  SDK Version:");
14229                    pw.print(" internal=");
14230                    pw.print(mSettings.mInternalSdkPlatform);
14231                    pw.print(" external=");
14232                    pw.println(mSettings.mExternalSdkPlatform);
14233                    pw.print("  DB Version:");
14234                    pw.print(" internal=");
14235                    pw.print(mSettings.mInternalDatabaseVersion);
14236                    pw.print(" external=");
14237                    pw.println(mSettings.mExternalDatabaseVersion);
14238                }
14239            }
14240
14241            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14242                if (!checkin) {
14243                    if (dumpState.onTitlePrinted())
14244                        pw.println();
14245                    pw.println("Verifiers:");
14246                    pw.print("  Required: ");
14247                    pw.print(mRequiredVerifierPackage);
14248                    pw.print(" (uid=");
14249                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14250                    pw.println(")");
14251                } else if (mRequiredVerifierPackage != null) {
14252                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14253                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14254                }
14255            }
14256
14257            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14258                    packageName == null) {
14259                if (mIntentFilterVerifierComponent != null) {
14260                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14261                    if (!checkin) {
14262                        if (dumpState.onTitlePrinted())
14263                            pw.println();
14264                        pw.println("Intent Filter Verifier:");
14265                        pw.print("  Using: ");
14266                        pw.print(verifierPackageName);
14267                        pw.print(" (uid=");
14268                        pw.print(getPackageUid(verifierPackageName, 0));
14269                        pw.println(")");
14270                    } else if (verifierPackageName != null) {
14271                        pw.print("ifv,"); pw.print(verifierPackageName);
14272                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14273                    }
14274                } else {
14275                    pw.println();
14276                    pw.println("No Intent Filter Verifier available!");
14277                }
14278            }
14279
14280            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14281                boolean printedHeader = false;
14282                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14283                while (it.hasNext()) {
14284                    String name = it.next();
14285                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14286                    if (!checkin) {
14287                        if (!printedHeader) {
14288                            if (dumpState.onTitlePrinted())
14289                                pw.println();
14290                            pw.println("Libraries:");
14291                            printedHeader = true;
14292                        }
14293                        pw.print("  ");
14294                    } else {
14295                        pw.print("lib,");
14296                    }
14297                    pw.print(name);
14298                    if (!checkin) {
14299                        pw.print(" -> ");
14300                    }
14301                    if (ent.path != null) {
14302                        if (!checkin) {
14303                            pw.print("(jar) ");
14304                            pw.print(ent.path);
14305                        } else {
14306                            pw.print(",jar,");
14307                            pw.print(ent.path);
14308                        }
14309                    } else {
14310                        if (!checkin) {
14311                            pw.print("(apk) ");
14312                            pw.print(ent.apk);
14313                        } else {
14314                            pw.print(",apk,");
14315                            pw.print(ent.apk);
14316                        }
14317                    }
14318                    pw.println();
14319                }
14320            }
14321
14322            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14323                if (dumpState.onTitlePrinted())
14324                    pw.println();
14325                if (!checkin) {
14326                    pw.println("Features:");
14327                }
14328                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14329                while (it.hasNext()) {
14330                    String name = it.next();
14331                    if (!checkin) {
14332                        pw.print("  ");
14333                    } else {
14334                        pw.print("feat,");
14335                    }
14336                    pw.println(name);
14337                }
14338            }
14339
14340            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14341                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14342                        : "Activity Resolver Table:", "  ", packageName,
14343                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14344                    dumpState.setTitlePrinted(true);
14345                }
14346                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14347                        : "Receiver Resolver Table:", "  ", packageName,
14348                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14349                    dumpState.setTitlePrinted(true);
14350                }
14351                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14352                        : "Service Resolver Table:", "  ", packageName,
14353                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14354                    dumpState.setTitlePrinted(true);
14355                }
14356                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14357                        : "Provider Resolver Table:", "  ", packageName,
14358                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14359                    dumpState.setTitlePrinted(true);
14360                }
14361            }
14362
14363            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14364                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14365                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14366                    int user = mSettings.mPreferredActivities.keyAt(i);
14367                    if (pir.dump(pw,
14368                            dumpState.getTitlePrinted()
14369                                ? "\nPreferred Activities User " + user + ":"
14370                                : "Preferred Activities User " + user + ":", "  ",
14371                            packageName, true, false)) {
14372                        dumpState.setTitlePrinted(true);
14373                    }
14374                }
14375            }
14376
14377            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14378                pw.flush();
14379                FileOutputStream fout = new FileOutputStream(fd);
14380                BufferedOutputStream str = new BufferedOutputStream(fout);
14381                XmlSerializer serializer = new FastXmlSerializer();
14382                try {
14383                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14384                    serializer.startDocument(null, true);
14385                    serializer.setFeature(
14386                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14387                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14388                    serializer.endDocument();
14389                    serializer.flush();
14390                } catch (IllegalArgumentException e) {
14391                    pw.println("Failed writing: " + e);
14392                } catch (IllegalStateException e) {
14393                    pw.println("Failed writing: " + e);
14394                } catch (IOException e) {
14395                    pw.println("Failed writing: " + e);
14396                }
14397            }
14398
14399            if (!checkin
14400                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14401                    && packageName == null) {
14402                pw.println();
14403                int count = mSettings.mPackages.size();
14404                if (count == 0) {
14405                    pw.println("No domain preferred apps!");
14406                    pw.println();
14407                } else {
14408                    final String prefix = "  ";
14409                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14410                    if (allPackageSettings.size() == 0) {
14411                        pw.println("No domain preferred apps!");
14412                        pw.println();
14413                    } else {
14414                        pw.println("Domain preferred apps status:");
14415                        pw.println();
14416                        count = 0;
14417                        for (PackageSetting ps : allPackageSettings) {
14418                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14419                            if (ivi == null || ivi.getPackageName() == null) continue;
14420                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14421                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14422                            pw.println(prefix + "Status: " + ivi.getStatusString());
14423                            pw.println();
14424                            count++;
14425                        }
14426                        if (count == 0) {
14427                            pw.println(prefix + "No domain preferred app status!");
14428                            pw.println();
14429                        }
14430                        for (int userId : sUserManager.getUserIds()) {
14431                            pw.println("Domain preferred apps for User " + userId + ":");
14432                            pw.println();
14433                            count = 0;
14434                            for (PackageSetting ps : allPackageSettings) {
14435                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14436                                if (ivi == null || ivi.getPackageName() == null) {
14437                                    continue;
14438                                }
14439                                final int status = ps.getDomainVerificationStatusForUser(userId);
14440                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14441                                    continue;
14442                                }
14443                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14444                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14445                                String statusStr = IntentFilterVerificationInfo.
14446                                        getStatusStringFromValue(status);
14447                                pw.println(prefix + "Status: " + statusStr);
14448                                pw.println();
14449                                count++;
14450                            }
14451                            if (count == 0) {
14452                                pw.println(prefix + "No domain preferred apps!");
14453                                pw.println();
14454                            }
14455                        }
14456                    }
14457                }
14458            }
14459
14460            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14461                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14462                if (packageName == null) {
14463                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14464                        if (iperm == 0) {
14465                            if (dumpState.onTitlePrinted())
14466                                pw.println();
14467                            pw.println("AppOp Permissions:");
14468                        }
14469                        pw.print("  AppOp Permission ");
14470                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14471                        pw.println(":");
14472                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14473                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14474                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14475                        }
14476                    }
14477                }
14478            }
14479
14480            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14481                boolean printedSomething = false;
14482                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14483                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14484                        continue;
14485                    }
14486                    if (!printedSomething) {
14487                        if (dumpState.onTitlePrinted())
14488                            pw.println();
14489                        pw.println("Registered ContentProviders:");
14490                        printedSomething = true;
14491                    }
14492                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14493                    pw.print("    "); pw.println(p.toString());
14494                }
14495                printedSomething = false;
14496                for (Map.Entry<String, PackageParser.Provider> entry :
14497                        mProvidersByAuthority.entrySet()) {
14498                    PackageParser.Provider p = entry.getValue();
14499                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14500                        continue;
14501                    }
14502                    if (!printedSomething) {
14503                        if (dumpState.onTitlePrinted())
14504                            pw.println();
14505                        pw.println("ContentProvider Authorities:");
14506                        printedSomething = true;
14507                    }
14508                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14509                    pw.print("    "); pw.println(p.toString());
14510                    if (p.info != null && p.info.applicationInfo != null) {
14511                        final String appInfo = p.info.applicationInfo.toString();
14512                        pw.print("      applicationInfo="); pw.println(appInfo);
14513                    }
14514                }
14515            }
14516
14517            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14518                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14519            }
14520
14521            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14522                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14523            }
14524
14525            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14526                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14527            }
14528
14529            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14530                // XXX should handle packageName != null by dumping only install data that
14531                // the given package is involved with.
14532                if (dumpState.onTitlePrinted()) pw.println();
14533                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14534            }
14535
14536            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14537                if (dumpState.onTitlePrinted()) pw.println();
14538                mSettings.dumpReadMessagesLPr(pw, dumpState);
14539
14540                pw.println();
14541                pw.println("Package warning messages:");
14542                BufferedReader in = null;
14543                String line = null;
14544                try {
14545                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14546                    while ((line = in.readLine()) != null) {
14547                        if (line.contains("ignored: updated version")) continue;
14548                        pw.println(line);
14549                    }
14550                } catch (IOException ignored) {
14551                } finally {
14552                    IoUtils.closeQuietly(in);
14553                }
14554            }
14555
14556            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14557                BufferedReader in = null;
14558                String line = null;
14559                try {
14560                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14561                    while ((line = in.readLine()) != null) {
14562                        if (line.contains("ignored: updated version")) continue;
14563                        pw.print("msg,");
14564                        pw.println(line);
14565                    }
14566                } catch (IOException ignored) {
14567                } finally {
14568                    IoUtils.closeQuietly(in);
14569                }
14570            }
14571        }
14572    }
14573
14574    // ------- apps on sdcard specific code -------
14575    static final boolean DEBUG_SD_INSTALL = false;
14576
14577    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14578
14579    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14580
14581    private boolean mMediaMounted = false;
14582
14583    static String getEncryptKey() {
14584        try {
14585            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14586                    SD_ENCRYPTION_KEYSTORE_NAME);
14587            if (sdEncKey == null) {
14588                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14589                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14590                if (sdEncKey == null) {
14591                    Slog.e(TAG, "Failed to create encryption keys");
14592                    return null;
14593                }
14594            }
14595            return sdEncKey;
14596        } catch (NoSuchAlgorithmException nsae) {
14597            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14598            return null;
14599        } catch (IOException ioe) {
14600            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14601            return null;
14602        }
14603    }
14604
14605    /*
14606     * Update media status on PackageManager.
14607     */
14608    @Override
14609    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14610        int callingUid = Binder.getCallingUid();
14611        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14612            throw new SecurityException("Media status can only be updated by the system");
14613        }
14614        // reader; this apparently protects mMediaMounted, but should probably
14615        // be a different lock in that case.
14616        synchronized (mPackages) {
14617            Log.i(TAG, "Updating external media status from "
14618                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14619                    + (mediaStatus ? "mounted" : "unmounted"));
14620            if (DEBUG_SD_INSTALL)
14621                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14622                        + ", mMediaMounted=" + mMediaMounted);
14623            if (mediaStatus == mMediaMounted) {
14624                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14625                        : 0, -1);
14626                mHandler.sendMessage(msg);
14627                return;
14628            }
14629            mMediaMounted = mediaStatus;
14630        }
14631        // Queue up an async operation since the package installation may take a
14632        // little while.
14633        mHandler.post(new Runnable() {
14634            public void run() {
14635                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14636            }
14637        });
14638    }
14639
14640    /**
14641     * Called by MountService when the initial ASECs to scan are available.
14642     * Should block until all the ASEC containers are finished being scanned.
14643     */
14644    public void scanAvailableAsecs() {
14645        updateExternalMediaStatusInner(true, false, false);
14646        if (mShouldRestoreconData) {
14647            SELinuxMMAC.setRestoreconDone();
14648            mShouldRestoreconData = false;
14649        }
14650    }
14651
14652    /*
14653     * Collect information of applications on external media, map them against
14654     * existing containers and update information based on current mount status.
14655     * Please note that we always have to report status if reportStatus has been
14656     * set to true especially when unloading packages.
14657     */
14658    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14659            boolean externalStorage) {
14660        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14661        int[] uidArr = EmptyArray.INT;
14662
14663        final String[] list = PackageHelper.getSecureContainerList();
14664        if (ArrayUtils.isEmpty(list)) {
14665            Log.i(TAG, "No secure containers found");
14666        } else {
14667            // Process list of secure containers and categorize them
14668            // as active or stale based on their package internal state.
14669
14670            // reader
14671            synchronized (mPackages) {
14672                for (String cid : list) {
14673                    // Leave stages untouched for now; installer service owns them
14674                    if (PackageInstallerService.isStageName(cid)) continue;
14675
14676                    if (DEBUG_SD_INSTALL)
14677                        Log.i(TAG, "Processing container " + cid);
14678                    String pkgName = getAsecPackageName(cid);
14679                    if (pkgName == null) {
14680                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14681                        continue;
14682                    }
14683                    if (DEBUG_SD_INSTALL)
14684                        Log.i(TAG, "Looking for pkg : " + pkgName);
14685
14686                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14687                    if (ps == null) {
14688                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14689                        continue;
14690                    }
14691
14692                    /*
14693                     * Skip packages that are not external if we're unmounting
14694                     * external storage.
14695                     */
14696                    if (externalStorage && !isMounted && !isExternal(ps)) {
14697                        continue;
14698                    }
14699
14700                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14701                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14702                    // The package status is changed only if the code path
14703                    // matches between settings and the container id.
14704                    if (ps.codePathString != null
14705                            && ps.codePathString.startsWith(args.getCodePath())) {
14706                        if (DEBUG_SD_INSTALL) {
14707                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14708                                    + " at code path: " + ps.codePathString);
14709                        }
14710
14711                        // We do have a valid package installed on sdcard
14712                        processCids.put(args, ps.codePathString);
14713                        final int uid = ps.appId;
14714                        if (uid != -1) {
14715                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14716                        }
14717                    } else {
14718                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14719                                + ps.codePathString);
14720                    }
14721                }
14722            }
14723
14724            Arrays.sort(uidArr);
14725        }
14726
14727        // Process packages with valid entries.
14728        if (isMounted) {
14729            if (DEBUG_SD_INSTALL)
14730                Log.i(TAG, "Loading packages");
14731            loadMediaPackages(processCids, uidArr);
14732            startCleaningPackages();
14733            mInstallerService.onSecureContainersAvailable();
14734        } else {
14735            if (DEBUG_SD_INSTALL)
14736                Log.i(TAG, "Unloading packages");
14737            unloadMediaPackages(processCids, uidArr, reportStatus);
14738        }
14739    }
14740
14741    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14742            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14743        final int size = infos.size();
14744        final String[] packageNames = new String[size];
14745        final int[] packageUids = new int[size];
14746        for (int i = 0; i < size; i++) {
14747            final ApplicationInfo info = infos.get(i);
14748            packageNames[i] = info.packageName;
14749            packageUids[i] = info.uid;
14750        }
14751        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14752                finishedReceiver);
14753    }
14754
14755    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14756            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14757        sendResourcesChangedBroadcast(mediaStatus, replacing,
14758                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14759    }
14760
14761    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14762            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14763        int size = pkgList.length;
14764        if (size > 0) {
14765            // Send broadcasts here
14766            Bundle extras = new Bundle();
14767            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14768            if (uidArr != null) {
14769                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14770            }
14771            if (replacing) {
14772                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14773            }
14774            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14775                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14776            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14777        }
14778    }
14779
14780   /*
14781     * Look at potentially valid container ids from processCids If package
14782     * information doesn't match the one on record or package scanning fails,
14783     * the cid is added to list of removeCids. We currently don't delete stale
14784     * containers.
14785     */
14786    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14787        ArrayList<String> pkgList = new ArrayList<String>();
14788        Set<AsecInstallArgs> keys = processCids.keySet();
14789
14790        for (AsecInstallArgs args : keys) {
14791            String codePath = processCids.get(args);
14792            if (DEBUG_SD_INSTALL)
14793                Log.i(TAG, "Loading container : " + args.cid);
14794            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14795            try {
14796                // Make sure there are no container errors first.
14797                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14798                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14799                            + " when installing from sdcard");
14800                    continue;
14801                }
14802                // Check code path here.
14803                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14804                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14805                            + " does not match one in settings " + codePath);
14806                    continue;
14807                }
14808                // Parse package
14809                int parseFlags = mDefParseFlags;
14810                if (args.isExternalAsec()) {
14811                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14812                }
14813                if (args.isFwdLocked()) {
14814                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14815                }
14816
14817                synchronized (mInstallLock) {
14818                    PackageParser.Package pkg = null;
14819                    try {
14820                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14821                    } catch (PackageManagerException e) {
14822                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14823                    }
14824                    // Scan the package
14825                    if (pkg != null) {
14826                        /*
14827                         * TODO why is the lock being held? doPostInstall is
14828                         * called in other places without the lock. This needs
14829                         * to be straightened out.
14830                         */
14831                        // writer
14832                        synchronized (mPackages) {
14833                            retCode = PackageManager.INSTALL_SUCCEEDED;
14834                            pkgList.add(pkg.packageName);
14835                            // Post process args
14836                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14837                                    pkg.applicationInfo.uid);
14838                        }
14839                    } else {
14840                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14841                    }
14842                }
14843
14844            } finally {
14845                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14846                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14847                }
14848            }
14849        }
14850        // writer
14851        synchronized (mPackages) {
14852            // If the platform SDK has changed since the last time we booted,
14853            // we need to re-grant app permission to catch any new ones that
14854            // appear. This is really a hack, and means that apps can in some
14855            // cases get permissions that the user didn't initially explicitly
14856            // allow... it would be nice to have some better way to handle
14857            // this situation.
14858            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14859            if (regrantPermissions)
14860                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14861                        + mSdkVersion + "; regranting permissions for external storage");
14862            mSettings.mExternalSdkPlatform = mSdkVersion;
14863
14864            // Make sure group IDs have been assigned, and any permission
14865            // changes in other apps are accounted for
14866            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14867                    | (regrantPermissions
14868                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14869                            : 0));
14870
14871            mSettings.updateExternalDatabaseVersion();
14872
14873            // can downgrade to reader
14874            // Persist settings
14875            mSettings.writeLPr();
14876        }
14877        // Send a broadcast to let everyone know we are done processing
14878        if (pkgList.size() > 0) {
14879            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14880        }
14881    }
14882
14883   /*
14884     * Utility method to unload a list of specified containers
14885     */
14886    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14887        // Just unmount all valid containers.
14888        for (AsecInstallArgs arg : cidArgs) {
14889            synchronized (mInstallLock) {
14890                arg.doPostDeleteLI(false);
14891           }
14892       }
14893   }
14894
14895    /*
14896     * Unload packages mounted on external media. This involves deleting package
14897     * data from internal structures, sending broadcasts about diabled packages,
14898     * gc'ing to free up references, unmounting all secure containers
14899     * corresponding to packages on external media, and posting a
14900     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14901     * that we always have to post this message if status has been requested no
14902     * matter what.
14903     */
14904    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14905            final boolean reportStatus) {
14906        if (DEBUG_SD_INSTALL)
14907            Log.i(TAG, "unloading media packages");
14908        ArrayList<String> pkgList = new ArrayList<String>();
14909        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14910        final Set<AsecInstallArgs> keys = processCids.keySet();
14911        for (AsecInstallArgs args : keys) {
14912            String pkgName = args.getPackageName();
14913            if (DEBUG_SD_INSTALL)
14914                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14915            // Delete package internally
14916            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14917            synchronized (mInstallLock) {
14918                boolean res = deletePackageLI(pkgName, null, false, null, null,
14919                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14920                if (res) {
14921                    pkgList.add(pkgName);
14922                } else {
14923                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14924                    failedList.add(args);
14925                }
14926            }
14927        }
14928
14929        // reader
14930        synchronized (mPackages) {
14931            // We didn't update the settings after removing each package;
14932            // write them now for all packages.
14933            mSettings.writeLPr();
14934        }
14935
14936        // We have to absolutely send UPDATED_MEDIA_STATUS only
14937        // after confirming that all the receivers processed the ordered
14938        // broadcast when packages get disabled, force a gc to clean things up.
14939        // and unload all the containers.
14940        if (pkgList.size() > 0) {
14941            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14942                    new IIntentReceiver.Stub() {
14943                public void performReceive(Intent intent, int resultCode, String data,
14944                        Bundle extras, boolean ordered, boolean sticky,
14945                        int sendingUser) throws RemoteException {
14946                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14947                            reportStatus ? 1 : 0, 1, keys);
14948                    mHandler.sendMessage(msg);
14949                }
14950            });
14951        } else {
14952            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14953                    keys);
14954            mHandler.sendMessage(msg);
14955        }
14956    }
14957
14958    private void loadPrivatePackages(VolumeInfo vol) {
14959        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14960        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14961        synchronized (mInstallLock) {
14962        synchronized (mPackages) {
14963            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14964            for (PackageSetting ps : packages) {
14965                final PackageParser.Package pkg;
14966                try {
14967                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14968                    loaded.add(pkg.applicationInfo);
14969                } catch (PackageManagerException e) {
14970                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14971                }
14972            }
14973
14974            // TODO: regrant any permissions that changed based since original install
14975
14976            mSettings.writeLPr();
14977        }
14978        }
14979
14980        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14981        sendResourcesChangedBroadcast(true, false, loaded, null);
14982    }
14983
14984    private void unloadPrivatePackages(VolumeInfo vol) {
14985        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14986        synchronized (mInstallLock) {
14987        synchronized (mPackages) {
14988            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14989            for (PackageSetting ps : packages) {
14990                if (ps.pkg == null) continue;
14991
14992                final ApplicationInfo info = ps.pkg.applicationInfo;
14993                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14994                if (deletePackageLI(ps.name, null, false, null, null,
14995                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14996                    unloaded.add(info);
14997                } else {
14998                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14999                }
15000            }
15001
15002            mSettings.writeLPr();
15003        }
15004        }
15005
15006        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15007        sendResourcesChangedBroadcast(false, false, unloaded, null);
15008    }
15009
15010    private void unfreezePackage(String packageName) {
15011        synchronized (mPackages) {
15012            final PackageSetting ps = mSettings.mPackages.get(packageName);
15013            if (ps != null) {
15014                ps.frozen = false;
15015            }
15016        }
15017    }
15018
15019    @Override
15020    public int movePackage(final String packageName, final String volumeUuid) {
15021        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15022
15023        final int moveId = mNextMoveId.getAndIncrement();
15024        try {
15025            movePackageInternal(packageName, volumeUuid, moveId);
15026        } catch (PackageManagerException e) {
15027            Slog.w(TAG, "Failed to move " + packageName, e);
15028            mMoveCallbacks.notifyStatusChanged(moveId,
15029                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15030        }
15031        return moveId;
15032    }
15033
15034    private void movePackageInternal(final String packageName, final String volumeUuid,
15035            final int moveId) throws PackageManagerException {
15036        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15037        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15038        final PackageManager pm = mContext.getPackageManager();
15039
15040        final boolean currentAsec;
15041        final String currentVolumeUuid;
15042        final File codeFile;
15043        final String installerPackageName;
15044        final String packageAbiOverride;
15045        final int appId;
15046        final String seinfo;
15047        final String label;
15048
15049        // reader
15050        synchronized (mPackages) {
15051            final PackageParser.Package pkg = mPackages.get(packageName);
15052            final PackageSetting ps = mSettings.mPackages.get(packageName);
15053            if (pkg == null || ps == null) {
15054                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15055            }
15056
15057            if (pkg.applicationInfo.isSystemApp()) {
15058                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15059                        "Cannot move system application");
15060            }
15061
15062            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15063                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15064                        "Package already moved to " + volumeUuid);
15065            }
15066
15067            final File probe = new File(pkg.codePath);
15068            final File probeOat = new File(probe, "oat");
15069            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15070                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15071                        "Move only supported for modern cluster style installs");
15072            }
15073
15074            if (ps.frozen) {
15075                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15076                        "Failed to move already frozen package");
15077            }
15078            ps.frozen = true;
15079
15080            currentAsec = pkg.applicationInfo.isForwardLocked()
15081                    || pkg.applicationInfo.isExternalAsec();
15082            currentVolumeUuid = ps.volumeUuid;
15083            codeFile = new File(pkg.codePath);
15084            installerPackageName = ps.installerPackageName;
15085            packageAbiOverride = ps.cpuAbiOverrideString;
15086            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15087            seinfo = pkg.applicationInfo.seinfo;
15088            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15089        }
15090
15091        // Now that we're guarded by frozen state, kill app during move
15092        killApplication(packageName, appId, "move pkg");
15093
15094        final Bundle extras = new Bundle();
15095        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15096        extras.putString(Intent.EXTRA_TITLE, label);
15097        mMoveCallbacks.notifyCreated(moveId, extras);
15098
15099        int installFlags;
15100        final boolean moveCompleteApp;
15101        final File measurePath;
15102
15103        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15104            installFlags = INSTALL_INTERNAL;
15105            moveCompleteApp = !currentAsec;
15106            measurePath = Environment.getDataAppDirectory(volumeUuid);
15107        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15108            installFlags = INSTALL_EXTERNAL;
15109            moveCompleteApp = false;
15110            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15111        } else {
15112            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15113            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15114                    || !volume.isMountedWritable()) {
15115                unfreezePackage(packageName);
15116                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15117                        "Move location not mounted private volume");
15118            }
15119
15120            Preconditions.checkState(!currentAsec);
15121
15122            installFlags = INSTALL_INTERNAL;
15123            moveCompleteApp = true;
15124            measurePath = Environment.getDataAppDirectory(volumeUuid);
15125        }
15126
15127        final PackageStats stats = new PackageStats(null, -1);
15128        synchronized (mInstaller) {
15129            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15130                unfreezePackage(packageName);
15131                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15132                        "Failed to measure package size");
15133            }
15134        }
15135
15136        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15137                + stats.dataSize);
15138
15139        final long startFreeBytes = measurePath.getFreeSpace();
15140        final long sizeBytes;
15141        if (moveCompleteApp) {
15142            sizeBytes = stats.codeSize + stats.dataSize;
15143        } else {
15144            sizeBytes = stats.codeSize;
15145        }
15146
15147        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15148            unfreezePackage(packageName);
15149            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15150                    "Not enough free space to move");
15151        }
15152
15153        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15154
15155        final CountDownLatch installedLatch = new CountDownLatch(1);
15156        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15157            @Override
15158            public void onUserActionRequired(Intent intent) throws RemoteException {
15159                throw new IllegalStateException();
15160            }
15161
15162            @Override
15163            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15164                    Bundle extras) throws RemoteException {
15165                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15166                        + PackageManager.installStatusToString(returnCode, msg));
15167
15168                installedLatch.countDown();
15169
15170                // Regardless of success or failure of the move operation,
15171                // always unfreeze the package
15172                unfreezePackage(packageName);
15173
15174                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15175                switch (status) {
15176                    case PackageInstaller.STATUS_SUCCESS:
15177                        mMoveCallbacks.notifyStatusChanged(moveId,
15178                                PackageManager.MOVE_SUCCEEDED);
15179                        break;
15180                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15181                        mMoveCallbacks.notifyStatusChanged(moveId,
15182                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15183                        break;
15184                    default:
15185                        mMoveCallbacks.notifyStatusChanged(moveId,
15186                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15187                        break;
15188                }
15189            }
15190        };
15191
15192        final MoveInfo move;
15193        if (moveCompleteApp) {
15194            // Kick off a thread to report progress estimates
15195            new Thread() {
15196                @Override
15197                public void run() {
15198                    while (true) {
15199                        try {
15200                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15201                                break;
15202                            }
15203                        } catch (InterruptedException ignored) {
15204                        }
15205
15206                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15207                        final int progress = 10 + (int) MathUtils.constrain(
15208                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15209                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15210                    }
15211                }
15212            }.start();
15213
15214            final String dataAppName = codeFile.getName();
15215            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15216                    dataAppName, appId, seinfo);
15217        } else {
15218            move = null;
15219        }
15220
15221        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15222
15223        final Message msg = mHandler.obtainMessage(INIT_COPY);
15224        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15225        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15226                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15227        mHandler.sendMessage(msg);
15228    }
15229
15230    @Override
15231    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15232        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15233
15234        final int realMoveId = mNextMoveId.getAndIncrement();
15235        final Bundle extras = new Bundle();
15236        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15237        mMoveCallbacks.notifyCreated(realMoveId, extras);
15238
15239        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15240            @Override
15241            public void onCreated(int moveId, Bundle extras) {
15242                // Ignored
15243            }
15244
15245            @Override
15246            public void onStatusChanged(int moveId, int status, long estMillis) {
15247                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15248            }
15249        };
15250
15251        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15252        storage.setPrimaryStorageUuid(volumeUuid, callback);
15253        return realMoveId;
15254    }
15255
15256    @Override
15257    public int getMoveStatus(int moveId) {
15258        mContext.enforceCallingOrSelfPermission(
15259                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15260        return mMoveCallbacks.mLastStatus.get(moveId);
15261    }
15262
15263    @Override
15264    public void registerMoveCallback(IPackageMoveObserver callback) {
15265        mContext.enforceCallingOrSelfPermission(
15266                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15267        mMoveCallbacks.register(callback);
15268    }
15269
15270    @Override
15271    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15272        mContext.enforceCallingOrSelfPermission(
15273                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15274        mMoveCallbacks.unregister(callback);
15275    }
15276
15277    @Override
15278    public boolean setInstallLocation(int loc) {
15279        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15280                null);
15281        if (getInstallLocation() == loc) {
15282            return true;
15283        }
15284        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15285                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15286            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15287                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15288            return true;
15289        }
15290        return false;
15291   }
15292
15293    @Override
15294    public int getInstallLocation() {
15295        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15296                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15297                PackageHelper.APP_INSTALL_AUTO);
15298    }
15299
15300    /** Called by UserManagerService */
15301    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15302        mDirtyUsers.remove(userHandle);
15303        mSettings.removeUserLPw(userHandle);
15304        mPendingBroadcasts.remove(userHandle);
15305        if (mInstaller != null) {
15306            // Technically, we shouldn't be doing this with the package lock
15307            // held.  However, this is very rare, and there is already so much
15308            // other disk I/O going on, that we'll let it slide for now.
15309            final StorageManager storage = StorageManager.from(mContext);
15310            final List<VolumeInfo> vols = storage.getVolumes();
15311            for (VolumeInfo vol : vols) {
15312                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15313                    final String volumeUuid = vol.getFsUuid();
15314                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15315                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15316                }
15317            }
15318        }
15319        mUserNeedsBadging.delete(userHandle);
15320        removeUnusedPackagesLILPw(userManager, userHandle);
15321    }
15322
15323    /**
15324     * We're removing userHandle and would like to remove any downloaded packages
15325     * that are no longer in use by any other user.
15326     * @param userHandle the user being removed
15327     */
15328    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15329        final boolean DEBUG_CLEAN_APKS = false;
15330        int [] users = userManager.getUserIdsLPr();
15331        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15332        while (psit.hasNext()) {
15333            PackageSetting ps = psit.next();
15334            if (ps.pkg == null) {
15335                continue;
15336            }
15337            final String packageName = ps.pkg.packageName;
15338            // Skip over if system app
15339            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15340                continue;
15341            }
15342            if (DEBUG_CLEAN_APKS) {
15343                Slog.i(TAG, "Checking package " + packageName);
15344            }
15345            boolean keep = false;
15346            for (int i = 0; i < users.length; i++) {
15347                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15348                    keep = true;
15349                    if (DEBUG_CLEAN_APKS) {
15350                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15351                                + users[i]);
15352                    }
15353                    break;
15354                }
15355            }
15356            if (!keep) {
15357                if (DEBUG_CLEAN_APKS) {
15358                    Slog.i(TAG, "  Removing package " + packageName);
15359                }
15360                mHandler.post(new Runnable() {
15361                    public void run() {
15362                        deletePackageX(packageName, userHandle, 0);
15363                    } //end run
15364                });
15365            }
15366        }
15367    }
15368
15369    /** Called by UserManagerService */
15370    void createNewUserLILPw(int userHandle, File path) {
15371        if (mInstaller != null) {
15372            mInstaller.createUserConfig(userHandle);
15373            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15374        }
15375    }
15376
15377    void newUserCreatedLILPw(final int userHandle) {
15378        // We cannot grant the default permissions with a lock held as
15379        // we query providers from other components for default handlers
15380        // such as enabled IMEs, etc.
15381        mHandler.post(new Runnable() {
15382            @Override
15383            public void run() {
15384                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15385            }
15386        });
15387    }
15388
15389    @Override
15390    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15391        mContext.enforceCallingOrSelfPermission(
15392                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15393                "Only package verification agents can read the verifier device identity");
15394
15395        synchronized (mPackages) {
15396            return mSettings.getVerifierDeviceIdentityLPw();
15397        }
15398    }
15399
15400    @Override
15401    public void setPermissionEnforced(String permission, boolean enforced) {
15402        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15403        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15404            synchronized (mPackages) {
15405                if (mSettings.mReadExternalStorageEnforced == null
15406                        || mSettings.mReadExternalStorageEnforced != enforced) {
15407                    mSettings.mReadExternalStorageEnforced = enforced;
15408                    mSettings.writeLPr();
15409                }
15410            }
15411            // kill any non-foreground processes so we restart them and
15412            // grant/revoke the GID.
15413            final IActivityManager am = ActivityManagerNative.getDefault();
15414            if (am != null) {
15415                final long token = Binder.clearCallingIdentity();
15416                try {
15417                    am.killProcessesBelowForeground("setPermissionEnforcement");
15418                } catch (RemoteException e) {
15419                } finally {
15420                    Binder.restoreCallingIdentity(token);
15421                }
15422            }
15423        } else {
15424            throw new IllegalArgumentException("No selective enforcement for " + permission);
15425        }
15426    }
15427
15428    @Override
15429    @Deprecated
15430    public boolean isPermissionEnforced(String permission) {
15431        return true;
15432    }
15433
15434    @Override
15435    public boolean isStorageLow() {
15436        final long token = Binder.clearCallingIdentity();
15437        try {
15438            final DeviceStorageMonitorInternal
15439                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15440            if (dsm != null) {
15441                return dsm.isMemoryLow();
15442            } else {
15443                return false;
15444            }
15445        } finally {
15446            Binder.restoreCallingIdentity(token);
15447        }
15448    }
15449
15450    @Override
15451    public IPackageInstaller getPackageInstaller() {
15452        return mInstallerService;
15453    }
15454
15455    private boolean userNeedsBadging(int userId) {
15456        int index = mUserNeedsBadging.indexOfKey(userId);
15457        if (index < 0) {
15458            final UserInfo userInfo;
15459            final long token = Binder.clearCallingIdentity();
15460            try {
15461                userInfo = sUserManager.getUserInfo(userId);
15462            } finally {
15463                Binder.restoreCallingIdentity(token);
15464            }
15465            final boolean b;
15466            if (userInfo != null && userInfo.isManagedProfile()) {
15467                b = true;
15468            } else {
15469                b = false;
15470            }
15471            mUserNeedsBadging.put(userId, b);
15472            return b;
15473        }
15474        return mUserNeedsBadging.valueAt(index);
15475    }
15476
15477    @Override
15478    public KeySet getKeySetByAlias(String packageName, String alias) {
15479        if (packageName == null || alias == null) {
15480            return null;
15481        }
15482        synchronized(mPackages) {
15483            final PackageParser.Package pkg = mPackages.get(packageName);
15484            if (pkg == null) {
15485                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15486                throw new IllegalArgumentException("Unknown package: " + packageName);
15487            }
15488            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15489            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15490        }
15491    }
15492
15493    @Override
15494    public KeySet getSigningKeySet(String packageName) {
15495        if (packageName == null) {
15496            return null;
15497        }
15498        synchronized(mPackages) {
15499            final PackageParser.Package pkg = mPackages.get(packageName);
15500            if (pkg == null) {
15501                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15502                throw new IllegalArgumentException("Unknown package: " + packageName);
15503            }
15504            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15505                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15506                throw new SecurityException("May not access signing KeySet of other apps.");
15507            }
15508            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15509            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15510        }
15511    }
15512
15513    @Override
15514    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15515        if (packageName == null || ks == null) {
15516            return false;
15517        }
15518        synchronized(mPackages) {
15519            final PackageParser.Package pkg = mPackages.get(packageName);
15520            if (pkg == null) {
15521                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15522                throw new IllegalArgumentException("Unknown package: " + packageName);
15523            }
15524            IBinder ksh = ks.getToken();
15525            if (ksh instanceof KeySetHandle) {
15526                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15527                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15528            }
15529            return false;
15530        }
15531    }
15532
15533    @Override
15534    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15535        if (packageName == null || ks == null) {
15536            return false;
15537        }
15538        synchronized(mPackages) {
15539            final PackageParser.Package pkg = mPackages.get(packageName);
15540            if (pkg == null) {
15541                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15542                throw new IllegalArgumentException("Unknown package: " + packageName);
15543            }
15544            IBinder ksh = ks.getToken();
15545            if (ksh instanceof KeySetHandle) {
15546                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15547                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15548            }
15549            return false;
15550        }
15551    }
15552
15553    public void getUsageStatsIfNoPackageUsageInfo() {
15554        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15555            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15556            if (usm == null) {
15557                throw new IllegalStateException("UsageStatsManager must be initialized");
15558            }
15559            long now = System.currentTimeMillis();
15560            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15561            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15562                String packageName = entry.getKey();
15563                PackageParser.Package pkg = mPackages.get(packageName);
15564                if (pkg == null) {
15565                    continue;
15566                }
15567                UsageStats usage = entry.getValue();
15568                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15569                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15570            }
15571        }
15572    }
15573
15574    /**
15575     * Check and throw if the given before/after packages would be considered a
15576     * downgrade.
15577     */
15578    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15579            throws PackageManagerException {
15580        if (after.versionCode < before.mVersionCode) {
15581            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15582                    "Update version code " + after.versionCode + " is older than current "
15583                    + before.mVersionCode);
15584        } else if (after.versionCode == before.mVersionCode) {
15585            if (after.baseRevisionCode < before.baseRevisionCode) {
15586                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15587                        "Update base revision code " + after.baseRevisionCode
15588                        + " is older than current " + before.baseRevisionCode);
15589            }
15590
15591            if (!ArrayUtils.isEmpty(after.splitNames)) {
15592                for (int i = 0; i < after.splitNames.length; i++) {
15593                    final String splitName = after.splitNames[i];
15594                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15595                    if (j != -1) {
15596                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15597                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15598                                    "Update split " + splitName + " revision code "
15599                                    + after.splitRevisionCodes[i] + " is older than current "
15600                                    + before.splitRevisionCodes[j]);
15601                        }
15602                    }
15603                }
15604            }
15605        }
15606    }
15607
15608    private static class MoveCallbacks extends Handler {
15609        private static final int MSG_CREATED = 1;
15610        private static final int MSG_STATUS_CHANGED = 2;
15611
15612        private final RemoteCallbackList<IPackageMoveObserver>
15613                mCallbacks = new RemoteCallbackList<>();
15614
15615        private final SparseIntArray mLastStatus = new SparseIntArray();
15616
15617        public MoveCallbacks(Looper looper) {
15618            super(looper);
15619        }
15620
15621        public void register(IPackageMoveObserver callback) {
15622            mCallbacks.register(callback);
15623        }
15624
15625        public void unregister(IPackageMoveObserver callback) {
15626            mCallbacks.unregister(callback);
15627        }
15628
15629        @Override
15630        public void handleMessage(Message msg) {
15631            final SomeArgs args = (SomeArgs) msg.obj;
15632            final int n = mCallbacks.beginBroadcast();
15633            for (int i = 0; i < n; i++) {
15634                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15635                try {
15636                    invokeCallback(callback, msg.what, args);
15637                } catch (RemoteException ignored) {
15638                }
15639            }
15640            mCallbacks.finishBroadcast();
15641            args.recycle();
15642        }
15643
15644        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15645                throws RemoteException {
15646            switch (what) {
15647                case MSG_CREATED: {
15648                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15649                    break;
15650                }
15651                case MSG_STATUS_CHANGED: {
15652                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15653                    break;
15654                }
15655            }
15656        }
15657
15658        private void notifyCreated(int moveId, Bundle extras) {
15659            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15660
15661            final SomeArgs args = SomeArgs.obtain();
15662            args.argi1 = moveId;
15663            args.arg2 = extras;
15664            obtainMessage(MSG_CREATED, args).sendToTarget();
15665        }
15666
15667        private void notifyStatusChanged(int moveId, int status) {
15668            notifyStatusChanged(moveId, status, -1);
15669        }
15670
15671        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15672            Slog.v(TAG, "Move " + moveId + " status " + status);
15673
15674            final SomeArgs args = SomeArgs.obtain();
15675            args.argi1 = moveId;
15676            args.argi2 = status;
15677            args.arg3 = estMillis;
15678            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15679
15680            synchronized (mLastStatus) {
15681                mLastStatus.put(moveId, status);
15682            }
15683        }
15684    }
15685
15686    private final class OnPermissionChangeListeners extends Handler {
15687        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15688
15689        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15690                new RemoteCallbackList<>();
15691
15692        public OnPermissionChangeListeners(Looper looper) {
15693            super(looper);
15694        }
15695
15696        @Override
15697        public void handleMessage(Message msg) {
15698            switch (msg.what) {
15699                case MSG_ON_PERMISSIONS_CHANGED: {
15700                    final int uid = msg.arg1;
15701                    handleOnPermissionsChanged(uid);
15702                } break;
15703            }
15704        }
15705
15706        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15707            mPermissionListeners.register(listener);
15708
15709        }
15710
15711        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15712            mPermissionListeners.unregister(listener);
15713        }
15714
15715        public void onPermissionsChanged(int uid) {
15716            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15717                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15718            }
15719        }
15720
15721        private void handleOnPermissionsChanged(int uid) {
15722            final int count = mPermissionListeners.beginBroadcast();
15723            try {
15724                for (int i = 0; i < count; i++) {
15725                    IOnPermissionsChangeListener callback = mPermissionListeners
15726                            .getBroadcastItem(i);
15727                    try {
15728                        callback.onPermissionsChanged(uid);
15729                    } catch (RemoteException e) {
15730                        Log.e(TAG, "Permission listener is dead", e);
15731                    }
15732                }
15733            } finally {
15734                mPermissionListeners.finishBroadcast();
15735            }
15736        }
15737    }
15738
15739    private class PackageManagerInternalImpl extends PackageManagerInternal {
15740        @Override
15741        public void setLocationPackagesProvider(PackagesProvider provider) {
15742            synchronized (mPackages) {
15743                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15744            }
15745        }
15746
15747        @Override
15748        public void setImePackagesProvider(PackagesProvider provider) {
15749            synchronized (mPackages) {
15750                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15751            }
15752        }
15753
15754        @Override
15755        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15756            synchronized (mPackages) {
15757                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15758            }
15759        }
15760    }
15761}
15762