PackageManagerService.java revision ee4e4e79f59a808c4c13db8281ac895047ea199a
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
47import static android.content.pm.PackageManager.INSTALL_INTERNAL;
48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
53import static android.content.pm.PackageManager.MATCH_ALL;
54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
58import static android.content.pm.PackageManager.PERMISSION_GRANTED;
59import static android.content.pm.PackageParser.isApkFile;
60import static android.os.Process.PACKAGE_INFO_GID;
61import static android.os.Process.SYSTEM_UID;
62import static android.system.OsConstants.O_CREAT;
63import static android.system.OsConstants.O_RDWR;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
68import static com.android.internal.util.ArrayUtils.appendInt;
69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
74
75import android.Manifest;
76import android.app.ActivityManager;
77import android.app.ActivityManagerNative;
78import android.app.AppGlobals;
79import android.app.IActivityManager;
80import android.app.admin.IDevicePolicyManager;
81import android.app.backup.IBackupManager;
82import android.app.usage.UsageStats;
83import android.app.usage.UsageStatsManager;
84import android.content.BroadcastReceiver;
85import android.content.ComponentName;
86import android.content.Context;
87import android.content.IIntentReceiver;
88import android.content.Intent;
89import android.content.IntentFilter;
90import android.content.IntentSender;
91import android.content.IntentSender.SendIntentException;
92import android.content.ServiceConnection;
93import android.content.pm.ActivityInfo;
94import android.content.pm.ApplicationInfo;
95import android.content.pm.FeatureInfo;
96import android.content.pm.IOnPermissionsChangeListener;
97import android.content.pm.IPackageDataObserver;
98import android.content.pm.IPackageDeleteObserver;
99import android.content.pm.IPackageDeleteObserver2;
100import android.content.pm.IPackageInstallObserver2;
101import android.content.pm.IPackageInstaller;
102import android.content.pm.IPackageManager;
103import android.content.pm.IPackageMoveObserver;
104import android.content.pm.IPackageStatsObserver;
105import android.content.pm.InstrumentationInfo;
106import android.content.pm.IntentFilterVerificationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageManagerInternal;
116import android.content.pm.PackageParser;
117import android.content.pm.PackageParser.ActivityIntentInfo;
118import android.content.pm.PackageParser.PackageLite;
119import android.content.pm.PackageParser.PackageParserException;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Debug;
140import android.os.Environment;
141import android.os.Environment.UserEnvironment;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteCallbackList;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.os.storage.IMountService;
159import android.os.storage.StorageEventListener;
160import android.os.storage.StorageManager;
161import android.os.storage.VolumeInfo;
162import android.os.storage.VolumeRecord;
163import android.security.KeyStore;
164import android.security.SystemKeyStore;
165import android.system.ErrnoException;
166import android.system.Os;
167import android.system.StructStat;
168import android.text.TextUtils;
169import android.text.format.DateUtils;
170import android.util.ArrayMap;
171import android.util.ArraySet;
172import android.util.AtomicFile;
173import android.util.DisplayMetrics;
174import android.util.EventLog;
175import android.util.ExceptionUtils;
176import android.util.Log;
177import android.util.LogPrinter;
178import android.util.MathUtils;
179import android.util.PrintStreamPrinter;
180import android.util.Slog;
181import android.util.SparseArray;
182import android.util.SparseBooleanArray;
183import android.util.SparseIntArray;
184import android.util.Xml;
185import android.view.Display;
186
187import dalvik.system.DexFile;
188import dalvik.system.VMRuntime;
189
190import libcore.io.IoUtils;
191import libcore.util.EmptyArray;
192
193import com.android.internal.R;
194import com.android.internal.app.IMediaContainerService;
195import com.android.internal.app.ResolverActivity;
196import com.android.internal.content.NativeLibraryHelper;
197import com.android.internal.content.PackageHelper;
198import com.android.internal.os.IParcelFileDescriptorFactory;
199import com.android.internal.os.SomeArgs;
200import com.android.internal.os.Zygote;
201import com.android.internal.util.ArrayUtils;
202import com.android.internal.util.FastPrintWriter;
203import com.android.internal.util.FastXmlSerializer;
204import com.android.internal.util.IndentingPrintWriter;
205import com.android.internal.util.Preconditions;
206import com.android.server.EventLogTags;
207import com.android.server.FgThread;
208import com.android.server.IntentResolver;
209import com.android.server.LocalServices;
210import com.android.server.ServiceThread;
211import com.android.server.SystemConfig;
212import com.android.server.Watchdog;
213import com.android.server.pm.PermissionsState.PermissionState;
214import com.android.server.pm.Settings.DatabaseVersion;
215import com.android.server.storage.DeviceStorageMonitorInternal;
216
217import org.xmlpull.v1.XmlPullParser;
218import org.xmlpull.v1.XmlPullParserException;
219import org.xmlpull.v1.XmlSerializer;
220
221import java.io.BufferedInputStream;
222import java.io.BufferedOutputStream;
223import java.io.BufferedReader;
224import java.io.ByteArrayInputStream;
225import java.io.ByteArrayOutputStream;
226import java.io.File;
227import java.io.FileDescriptor;
228import java.io.FileNotFoundException;
229import java.io.FileOutputStream;
230import java.io.FileReader;
231import java.io.FilenameFilter;
232import java.io.IOException;
233import java.io.InputStream;
234import java.io.PrintWriter;
235import java.nio.charset.StandardCharsets;
236import java.security.NoSuchAlgorithmException;
237import java.security.PublicKey;
238import java.security.cert.CertificateEncodingException;
239import java.security.cert.CertificateException;
240import java.text.SimpleDateFormat;
241import java.util.ArrayList;
242import java.util.Arrays;
243import java.util.Collection;
244import java.util.Collections;
245import java.util.Comparator;
246import java.util.Date;
247import java.util.Iterator;
248import java.util.List;
249import java.util.Map;
250import java.util.Objects;
251import java.util.Set;
252import java.util.concurrent.CountDownLatch;
253import java.util.concurrent.TimeUnit;
254import java.util.concurrent.atomic.AtomicBoolean;
255import java.util.concurrent.atomic.AtomicInteger;
256import java.util.concurrent.atomic.AtomicLong;
257
258/**
259 * Keep track of all those .apks everywhere.
260 *
261 * This is very central to the platform's security; please run the unit
262 * tests whenever making modifications here:
263 *
264runtest -c android.content.pm.PackageManagerTests frameworks-core
265 *
266 * {@hide}
267 */
268public class PackageManagerService extends IPackageManager.Stub {
269    static final String TAG = "PackageManager";
270    static final boolean DEBUG_SETTINGS = false;
271    static final boolean DEBUG_PREFERRED = false;
272    static final boolean DEBUG_UPGRADE = false;
273    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
274    private static final boolean DEBUG_BACKUP = true;
275    private static final boolean DEBUG_INSTALL = false;
276    private static final boolean DEBUG_REMOVE = false;
277    private static final boolean DEBUG_BROADCASTS = false;
278    private static final boolean DEBUG_SHOW_INFO = false;
279    private static final boolean DEBUG_PACKAGE_INFO = false;
280    private static final boolean DEBUG_INTENT_MATCHING = false;
281    private static final boolean DEBUG_PACKAGE_SCANNING = false;
282    private static final boolean DEBUG_VERIFY = false;
283    private static final boolean DEBUG_DEXOPT = false;
284    private static final boolean DEBUG_ABI_SELECTION = false;
285
286    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
287
288    private static final int RADIO_UID = Process.PHONE_UID;
289    private static final int LOG_UID = Process.LOG_UID;
290    private static final int NFC_UID = Process.NFC_UID;
291    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
292    private static final int SHELL_UID = Process.SHELL_UID;
293
294    // Cap the size of permission trees that 3rd party apps can define
295    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
296
297    // Suffix used during package installation when copying/moving
298    // package apks to install directory.
299    private static final String INSTALL_PACKAGE_SUFFIX = "-";
300
301    static final int SCAN_NO_DEX = 1<<1;
302    static final int SCAN_FORCE_DEX = 1<<2;
303    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
304    static final int SCAN_NEW_INSTALL = 1<<4;
305    static final int SCAN_NO_PATHS = 1<<5;
306    static final int SCAN_UPDATE_TIME = 1<<6;
307    static final int SCAN_DEFER_DEX = 1<<7;
308    static final int SCAN_BOOTING = 1<<8;
309    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
310    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
311    static final int SCAN_REQUIRE_KNOWN = 1<<12;
312    static final int SCAN_MOVE = 1<<13;
313    static final int SCAN_INITIAL = 1<<14;
314
315    static final int REMOVE_CHATTY = 1<<16;
316
317    private static final int[] EMPTY_INT_ARRAY = new int[0];
318
319    /**
320     * Timeout (in milliseconds) after which the watchdog should declare that
321     * our handler thread is wedged.  The usual default for such things is one
322     * minute but we sometimes do very lengthy I/O operations on this thread,
323     * such as installing multi-gigabyte applications, so ours needs to be longer.
324     */
325    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
326
327    /**
328     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
329     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
330     * settings entry if available, otherwise we use the hardcoded default.  If it's been
331     * more than this long since the last fstrim, we force one during the boot sequence.
332     *
333     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
334     * one gets run at the next available charging+idle time.  This final mandatory
335     * no-fstrim check kicks in only of the other scheduling criteria is never met.
336     */
337    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
338
339    /**
340     * Whether verification is enabled by default.
341     */
342    private static final boolean DEFAULT_VERIFY_ENABLE = true;
343
344    /**
345     * The default maximum time to wait for the verification agent to return in
346     * milliseconds.
347     */
348    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
349
350    /**
351     * The default response for package verification timeout.
352     *
353     * This can be either PackageManager.VERIFICATION_ALLOW or
354     * PackageManager.VERIFICATION_REJECT.
355     */
356    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
357
358    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
359
360    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
361            DEFAULT_CONTAINER_PACKAGE,
362            "com.android.defcontainer.DefaultContainerService");
363
364    private static final String KILL_APP_REASON_GIDS_CHANGED =
365            "permission grant or revoke changed gids";
366
367    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
368            "permissions revoked";
369
370    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
371
372    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
373
374    /** Permission grant: not grant the permission. */
375    private static final int GRANT_DENIED = 1;
376
377    /** Permission grant: grant the permission as an install permission. */
378    private static final int GRANT_INSTALL = 2;
379
380    /** Permission grant: grant the permission as an install permission for a legacy app. */
381    private static final int GRANT_INSTALL_LEGACY = 3;
382
383    /** Permission grant: grant the permission as a runtime one. */
384    private static final int GRANT_RUNTIME = 4;
385
386    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
387    private static final int GRANT_UPGRADE = 5;
388
389    final ServiceThread mHandlerThread;
390
391    final PackageHandler mHandler;
392
393    /**
394     * Messages for {@link #mHandler} that need to wait for system ready before
395     * being dispatched.
396     */
397    private ArrayList<Message> mPostSystemReadyMessages;
398
399    final int mSdkVersion = Build.VERSION.SDK_INT;
400
401    final Context mContext;
402    final boolean mFactoryTest;
403    final boolean mOnlyCore;
404    final boolean mLazyDexOpt;
405    final long mDexOptLRUThresholdInMills;
406    final DisplayMetrics mMetrics;
407    final int mDefParseFlags;
408    final String[] mSeparateProcesses;
409    final boolean mIsUpgrade;
410
411    // This is where all application persistent data goes.
412    final File mAppDataDir;
413
414    // This is where all application persistent data goes for secondary users.
415    final File mUserAppDataDir;
416
417    /** The location for ASEC container files on internal storage. */
418    final String mAsecInternalPath;
419
420    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
421    // LOCK HELD.  Can be called with mInstallLock held.
422    final Installer mInstaller;
423
424    /** Directory where installed third-party apps stored */
425    final File mAppInstallDir;
426
427    /**
428     * Directory to which applications installed internally have their
429     * 32 bit native libraries copied.
430     */
431    private File mAppLib32InstallDir;
432
433    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
434    // apps.
435    final File mDrmAppPrivateInstallDir;
436
437    // ----------------------------------------------------------------
438
439    // Lock for state used when installing and doing other long running
440    // operations.  Methods that must be called with this lock held have
441    // the suffix "LI".
442    final Object mInstallLock = new Object();
443
444    // ----------------------------------------------------------------
445
446    // Keys are String (package name), values are Package.  This also serves
447    // as the lock for the global state.  Methods that must be called with
448    // this lock held have the prefix "LP".
449    final ArrayMap<String, PackageParser.Package> mPackages =
450            new ArrayMap<String, PackageParser.Package>();
451
452    // Tracks available target package names -> overlay package paths.
453    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
454        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
455
456    final Settings mSettings;
457    boolean mRestoredSettings;
458
459    // System configuration read by SystemConfig.
460    final int[] mGlobalGids;
461    final SparseArray<ArraySet<String>> mSystemPermissions;
462    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
463
464    // If mac_permissions.xml was found for seinfo labeling.
465    boolean mFoundPolicyFile;
466
467    // If a recursive restorecon of /data/data/<pkg> is needed.
468    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
469
470    public static final class SharedLibraryEntry {
471        public final String path;
472        public final String apk;
473
474        SharedLibraryEntry(String _path, String _apk) {
475            path = _path;
476            apk = _apk;
477        }
478    }
479
480    // Currently known shared libraries.
481    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
482            new ArrayMap<String, SharedLibraryEntry>();
483
484    // All available activities, for your resolving pleasure.
485    final ActivityIntentResolver mActivities =
486            new ActivityIntentResolver();
487
488    // All available receivers, for your resolving pleasure.
489    final ActivityIntentResolver mReceivers =
490            new ActivityIntentResolver();
491
492    // All available services, for your resolving pleasure.
493    final ServiceIntentResolver mServices = new ServiceIntentResolver();
494
495    // All available providers, for your resolving pleasure.
496    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
497
498    // Mapping from provider base names (first directory in content URI codePath)
499    // to the provider information.
500    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
501            new ArrayMap<String, PackageParser.Provider>();
502
503    // Mapping from instrumentation class names to info about them.
504    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
505            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
506
507    // Mapping from permission names to info about them.
508    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
509            new ArrayMap<String, PackageParser.PermissionGroup>();
510
511    // Packages whose data we have transfered into another package, thus
512    // should no longer exist.
513    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
514
515    // Broadcast actions that are only available to the system.
516    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
517
518    /** List of packages waiting for verification. */
519    final SparseArray<PackageVerificationState> mPendingVerification
520            = new SparseArray<PackageVerificationState>();
521
522    /** Set of packages associated with each app op permission. */
523    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
524
525    final PackageInstallerService mInstallerService;
526
527    private final PackageDexOptimizer mPackageDexOptimizer;
528
529    private AtomicInteger mNextMoveId = new AtomicInteger();
530    private final MoveCallbacks mMoveCallbacks;
531
532    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
533
534    // Cache of users who need badging.
535    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
536
537    /** Token for keys in mPendingVerification. */
538    private int mPendingVerificationToken = 0;
539
540    volatile boolean mSystemReady;
541    volatile boolean mSafeMode;
542    volatile boolean mHasSystemUidErrors;
543
544    ApplicationInfo mAndroidApplication;
545    final ActivityInfo mResolveActivity = new ActivityInfo();
546    final ResolveInfo mResolveInfo = new ResolveInfo();
547    ComponentName mResolveComponentName;
548    PackageParser.Package mPlatformPackage;
549    ComponentName mCustomResolverComponentName;
550
551    boolean mResolverReplaced = false;
552
553    private final ComponentName mIntentFilterVerifierComponent;
554    private int mIntentFilterVerificationToken = 0;
555
556    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
557            = new SparseArray<IntentFilterVerificationState>();
558
559    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
560            new DefaultPermissionGrantPolicy(this);
561
562    private static class IFVerificationParams {
563        PackageParser.Package pkg;
564        boolean replacing;
565        int userId;
566        int verifierUid;
567
568        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
569                int _userId, int _verifierUid) {
570            pkg = _pkg;
571            replacing = _replacing;
572            userId = _userId;
573            replacing = _replacing;
574            verifierUid = _verifierUid;
575        }
576    }
577
578    private interface IntentFilterVerifier<T extends IntentFilter> {
579        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
580                                               T filter, String packageName);
581        void startVerifications(int userId);
582        void receiveVerificationResponse(int verificationId);
583    }
584
585    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
586        private Context mContext;
587        private ComponentName mIntentFilterVerifierComponent;
588        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
589
590        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
591            mContext = context;
592            mIntentFilterVerifierComponent = verifierComponent;
593        }
594
595        private String getDefaultScheme() {
596            return IntentFilter.SCHEME_HTTPS;
597        }
598
599        @Override
600        public void startVerifications(int userId) {
601            // Launch verifications requests
602            int count = mCurrentIntentFilterVerifications.size();
603            for (int n=0; n<count; n++) {
604                int verificationId = mCurrentIntentFilterVerifications.get(n);
605                final IntentFilterVerificationState ivs =
606                        mIntentFilterVerificationStates.get(verificationId);
607
608                String packageName = ivs.getPackageName();
609
610                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
611                final int filterCount = filters.size();
612                ArraySet<String> domainsSet = new ArraySet<>();
613                for (int m=0; m<filterCount; m++) {
614                    PackageParser.ActivityIntentInfo filter = filters.get(m);
615                    domainsSet.addAll(filter.getHostsList());
616                }
617                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
618                synchronized (mPackages) {
619                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
620                            packageName, domainsList) != null) {
621                        scheduleWriteSettingsLocked();
622                    }
623                }
624                sendVerificationRequest(userId, verificationId, ivs);
625            }
626            mCurrentIntentFilterVerifications.clear();
627        }
628
629        private void sendVerificationRequest(int userId, int verificationId,
630                IntentFilterVerificationState ivs) {
631
632            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
633            verificationIntent.putExtra(
634                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
635                    verificationId);
636            verificationIntent.putExtra(
637                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
638                    getDefaultScheme());
639            verificationIntent.putExtra(
640                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
641                    ivs.getHostsString());
642            verificationIntent.putExtra(
643                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
644                    ivs.getPackageName());
645            verificationIntent.setComponent(mIntentFilterVerifierComponent);
646            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
647
648            UserHandle user = new UserHandle(userId);
649            mContext.sendBroadcastAsUser(verificationIntent, user);
650            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
651                    "Sending IntentFilter verification broadcast");
652        }
653
654        public void receiveVerificationResponse(int verificationId) {
655            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
656
657            final boolean verified = ivs.isVerified();
658
659            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
660            final int count = filters.size();
661            if (DEBUG_DOMAIN_VERIFICATION) {
662                Slog.i(TAG, "Received verification response " + verificationId
663                        + " for " + count + " filters, verified=" + verified);
664            }
665            for (int n=0; n<count; n++) {
666                PackageParser.ActivityIntentInfo filter = filters.get(n);
667                filter.setVerified(verified);
668
669                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
670                        + " verified with result:" + verified + " and hosts:"
671                        + ivs.getHostsString());
672            }
673
674            mIntentFilterVerificationStates.remove(verificationId);
675
676            final String packageName = ivs.getPackageName();
677            IntentFilterVerificationInfo ivi = null;
678
679            synchronized (mPackages) {
680                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
681            }
682            if (ivi == null) {
683                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
684                        + verificationId + " packageName:" + packageName);
685                return;
686            }
687            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
688                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
689
690            synchronized (mPackages) {
691                if (verified) {
692                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
693                } else {
694                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
695                }
696                scheduleWriteSettingsLocked();
697
698                final int userId = ivs.getUserId();
699                if (userId != UserHandle.USER_ALL) {
700                    final int userStatus =
701                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
702
703                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
704                    boolean needUpdate = false;
705
706                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
707                    // already been set by the User thru the Disambiguation dialog
708                    switch (userStatus) {
709                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
710                            if (verified) {
711                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
712                            } else {
713                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
714                            }
715                            needUpdate = true;
716                            break;
717
718                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
719                            if (verified) {
720                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
721                                needUpdate = true;
722                            }
723                            break;
724
725                        default:
726                            // Nothing to do
727                    }
728
729                    if (needUpdate) {
730                        mSettings.updateIntentFilterVerificationStatusLPw(
731                                packageName, updatedStatus, userId);
732                        scheduleWritePackageRestrictionsLocked(userId);
733                    }
734                }
735            }
736        }
737
738        @Override
739        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
740                    ActivityIntentInfo filter, String packageName) {
741            if (!hasValidDomains(filter)) {
742                return false;
743            }
744            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
745            if (ivs == null) {
746                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
747                        packageName);
748            }
749            if (DEBUG_DOMAIN_VERIFICATION) {
750                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
751            }
752            ivs.addFilter(filter);
753            return true;
754        }
755
756        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
757                int userId, int verificationId, String packageName) {
758            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
759                    verifierUid, userId, packageName);
760            ivs.setPendingState();
761            synchronized (mPackages) {
762                mIntentFilterVerificationStates.append(verificationId, ivs);
763                mCurrentIntentFilterVerifications.add(verificationId);
764            }
765            return ivs;
766        }
767    }
768
769    private static boolean hasValidDomains(ActivityIntentInfo filter) {
770        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
771                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
772        if (!hasHTTPorHTTPS) {
773            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
774                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
775            return false;
776        }
777        return true;
778    }
779
780    private IntentFilterVerifier mIntentFilterVerifier;
781
782    // Set of pending broadcasts for aggregating enable/disable of components.
783    static class PendingPackageBroadcasts {
784        // for each user id, a map of <package name -> components within that package>
785        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
786
787        public PendingPackageBroadcasts() {
788            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
789        }
790
791        public ArrayList<String> get(int userId, String packageName) {
792            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
793            return packages.get(packageName);
794        }
795
796        public void put(int userId, String packageName, ArrayList<String> components) {
797            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
798            packages.put(packageName, components);
799        }
800
801        public void remove(int userId, String packageName) {
802            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
803            if (packages != null) {
804                packages.remove(packageName);
805            }
806        }
807
808        public void remove(int userId) {
809            mUidMap.remove(userId);
810        }
811
812        public int userIdCount() {
813            return mUidMap.size();
814        }
815
816        public int userIdAt(int n) {
817            return mUidMap.keyAt(n);
818        }
819
820        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
821            return mUidMap.get(userId);
822        }
823
824        public int size() {
825            // total number of pending broadcast entries across all userIds
826            int num = 0;
827            for (int i = 0; i< mUidMap.size(); i++) {
828                num += mUidMap.valueAt(i).size();
829            }
830            return num;
831        }
832
833        public void clear() {
834            mUidMap.clear();
835        }
836
837        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
838            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
839            if (map == null) {
840                map = new ArrayMap<String, ArrayList<String>>();
841                mUidMap.put(userId, map);
842            }
843            return map;
844        }
845    }
846    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
847
848    // Service Connection to remote media container service to copy
849    // package uri's from external media onto secure containers
850    // or internal storage.
851    private IMediaContainerService mContainerService = null;
852
853    static final int SEND_PENDING_BROADCAST = 1;
854    static final int MCS_BOUND = 3;
855    static final int END_COPY = 4;
856    static final int INIT_COPY = 5;
857    static final int MCS_UNBIND = 6;
858    static final int START_CLEANING_PACKAGE = 7;
859    static final int FIND_INSTALL_LOC = 8;
860    static final int POST_INSTALL = 9;
861    static final int MCS_RECONNECT = 10;
862    static final int MCS_GIVE_UP = 11;
863    static final int UPDATED_MEDIA_STATUS = 12;
864    static final int WRITE_SETTINGS = 13;
865    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
866    static final int PACKAGE_VERIFIED = 15;
867    static final int CHECK_PENDING_VERIFICATION = 16;
868    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
869    static final int INTENT_FILTER_VERIFIED = 18;
870
871    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
872
873    // Delay time in millisecs
874    static final int BROADCAST_DELAY = 10 * 1000;
875
876    static UserManagerService sUserManager;
877
878    // Stores a list of users whose package restrictions file needs to be updated
879    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
880
881    final private DefaultContainerConnection mDefContainerConn =
882            new DefaultContainerConnection();
883    class DefaultContainerConnection implements ServiceConnection {
884        public void onServiceConnected(ComponentName name, IBinder service) {
885            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
886            IMediaContainerService imcs =
887                IMediaContainerService.Stub.asInterface(service);
888            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
889        }
890
891        public void onServiceDisconnected(ComponentName name) {
892            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
893        }
894    }
895
896    // Recordkeeping of restore-after-install operations that are currently in flight
897    // between the Package Manager and the Backup Manager
898    class PostInstallData {
899        public InstallArgs args;
900        public PackageInstalledInfo res;
901
902        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
903            args = _a;
904            res = _r;
905        }
906    }
907
908    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
909    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
910
911    // XML tags for backup/restore of various bits of state
912    private static final String TAG_PREFERRED_BACKUP = "pa";
913    private static final String TAG_DEFAULT_APPS = "da";
914    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
915
916    private final String mRequiredVerifierPackage;
917
918    private final PackageUsage mPackageUsage = new PackageUsage();
919
920    private class PackageUsage {
921        private static final int WRITE_INTERVAL
922            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
923
924        private final Object mFileLock = new Object();
925        private final AtomicLong mLastWritten = new AtomicLong(0);
926        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
927
928        private boolean mIsHistoricalPackageUsageAvailable = true;
929
930        boolean isHistoricalPackageUsageAvailable() {
931            return mIsHistoricalPackageUsageAvailable;
932        }
933
934        void write(boolean force) {
935            if (force) {
936                writeInternal();
937                return;
938            }
939            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
940                && !DEBUG_DEXOPT) {
941                return;
942            }
943            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
944                new Thread("PackageUsage_DiskWriter") {
945                    @Override
946                    public void run() {
947                        try {
948                            writeInternal();
949                        } finally {
950                            mBackgroundWriteRunning.set(false);
951                        }
952                    }
953                }.start();
954            }
955        }
956
957        private void writeInternal() {
958            synchronized (mPackages) {
959                synchronized (mFileLock) {
960                    AtomicFile file = getFile();
961                    FileOutputStream f = null;
962                    try {
963                        f = file.startWrite();
964                        BufferedOutputStream out = new BufferedOutputStream(f);
965                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
966                        StringBuilder sb = new StringBuilder();
967                        for (PackageParser.Package pkg : mPackages.values()) {
968                            if (pkg.mLastPackageUsageTimeInMills == 0) {
969                                continue;
970                            }
971                            sb.setLength(0);
972                            sb.append(pkg.packageName);
973                            sb.append(' ');
974                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
975                            sb.append('\n');
976                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
977                        }
978                        out.flush();
979                        file.finishWrite(f);
980                    } catch (IOException e) {
981                        if (f != null) {
982                            file.failWrite(f);
983                        }
984                        Log.e(TAG, "Failed to write package usage times", e);
985                    }
986                }
987            }
988            mLastWritten.set(SystemClock.elapsedRealtime());
989        }
990
991        void readLP() {
992            synchronized (mFileLock) {
993                AtomicFile file = getFile();
994                BufferedInputStream in = null;
995                try {
996                    in = new BufferedInputStream(file.openRead());
997                    StringBuffer sb = new StringBuffer();
998                    while (true) {
999                        String packageName = readToken(in, sb, ' ');
1000                        if (packageName == null) {
1001                            break;
1002                        }
1003                        String timeInMillisString = readToken(in, sb, '\n');
1004                        if (timeInMillisString == null) {
1005                            throw new IOException("Failed to find last usage time for package "
1006                                                  + packageName);
1007                        }
1008                        PackageParser.Package pkg = mPackages.get(packageName);
1009                        if (pkg == null) {
1010                            continue;
1011                        }
1012                        long timeInMillis;
1013                        try {
1014                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1015                        } catch (NumberFormatException e) {
1016                            throw new IOException("Failed to parse " + timeInMillisString
1017                                                  + " as a long.", e);
1018                        }
1019                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1020                    }
1021                } catch (FileNotFoundException expected) {
1022                    mIsHistoricalPackageUsageAvailable = false;
1023                } catch (IOException e) {
1024                    Log.w(TAG, "Failed to read package usage times", e);
1025                } finally {
1026                    IoUtils.closeQuietly(in);
1027                }
1028            }
1029            mLastWritten.set(SystemClock.elapsedRealtime());
1030        }
1031
1032        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1033                throws IOException {
1034            sb.setLength(0);
1035            while (true) {
1036                int ch = in.read();
1037                if (ch == -1) {
1038                    if (sb.length() == 0) {
1039                        return null;
1040                    }
1041                    throw new IOException("Unexpected EOF");
1042                }
1043                if (ch == endOfToken) {
1044                    return sb.toString();
1045                }
1046                sb.append((char)ch);
1047            }
1048        }
1049
1050        private AtomicFile getFile() {
1051            File dataDir = Environment.getDataDirectory();
1052            File systemDir = new File(dataDir, "system");
1053            File fname = new File(systemDir, "package-usage.list");
1054            return new AtomicFile(fname);
1055        }
1056    }
1057
1058    class PackageHandler extends Handler {
1059        private boolean mBound = false;
1060        final ArrayList<HandlerParams> mPendingInstalls =
1061            new ArrayList<HandlerParams>();
1062
1063        private boolean connectToService() {
1064            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1065                    " DefaultContainerService");
1066            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1067            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1068            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1069                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1070                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1071                mBound = true;
1072                return true;
1073            }
1074            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1075            return false;
1076        }
1077
1078        private void disconnectService() {
1079            mContainerService = null;
1080            mBound = false;
1081            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1082            mContext.unbindService(mDefContainerConn);
1083            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1084        }
1085
1086        PackageHandler(Looper looper) {
1087            super(looper);
1088        }
1089
1090        public void handleMessage(Message msg) {
1091            try {
1092                doHandleMessage(msg);
1093            } finally {
1094                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1095            }
1096        }
1097
1098        void doHandleMessage(Message msg) {
1099            switch (msg.what) {
1100                case INIT_COPY: {
1101                    HandlerParams params = (HandlerParams) msg.obj;
1102                    int idx = mPendingInstalls.size();
1103                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1104                    // If a bind was already initiated we dont really
1105                    // need to do anything. The pending install
1106                    // will be processed later on.
1107                    if (!mBound) {
1108                        // If this is the only one pending we might
1109                        // have to bind to the service again.
1110                        if (!connectToService()) {
1111                            Slog.e(TAG, "Failed to bind to media container service");
1112                            params.serviceError();
1113                            return;
1114                        } else {
1115                            // Once we bind to the service, the first
1116                            // pending request will be processed.
1117                            mPendingInstalls.add(idx, params);
1118                        }
1119                    } else {
1120                        mPendingInstalls.add(idx, params);
1121                        // Already bound to the service. Just make
1122                        // sure we trigger off processing the first request.
1123                        if (idx == 0) {
1124                            mHandler.sendEmptyMessage(MCS_BOUND);
1125                        }
1126                    }
1127                    break;
1128                }
1129                case MCS_BOUND: {
1130                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1131                    if (msg.obj != null) {
1132                        mContainerService = (IMediaContainerService) msg.obj;
1133                    }
1134                    if (mContainerService == null) {
1135                        if (!mBound) {
1136                            // Something seriously wrong since we are not bound and we are not
1137                            // waiting for connection. Bail out.
1138                            Slog.e(TAG, "Cannot bind to media container service");
1139                            for (HandlerParams params : mPendingInstalls) {
1140                                // Indicate service bind error
1141                                params.serviceError();
1142                            }
1143                            mPendingInstalls.clear();
1144                        } else {
1145                            Slog.w(TAG, "Waiting to connect to media container service");
1146                        }
1147                    } else if (mPendingInstalls.size() > 0) {
1148                        HandlerParams params = mPendingInstalls.get(0);
1149                        if (params != null) {
1150                            if (params.startCopy()) {
1151                                // We are done...  look for more work or to
1152                                // go idle.
1153                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1154                                        "Checking for more work or unbind...");
1155                                // Delete pending install
1156                                if (mPendingInstalls.size() > 0) {
1157                                    mPendingInstalls.remove(0);
1158                                }
1159                                if (mPendingInstalls.size() == 0) {
1160                                    if (mBound) {
1161                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1162                                                "Posting delayed MCS_UNBIND");
1163                                        removeMessages(MCS_UNBIND);
1164                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1165                                        // Unbind after a little delay, to avoid
1166                                        // continual thrashing.
1167                                        sendMessageDelayed(ubmsg, 10000);
1168                                    }
1169                                } else {
1170                                    // There are more pending requests in queue.
1171                                    // Just post MCS_BOUND message to trigger processing
1172                                    // of next pending install.
1173                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1174                                            "Posting MCS_BOUND for next work");
1175                                    mHandler.sendEmptyMessage(MCS_BOUND);
1176                                }
1177                            }
1178                        }
1179                    } else {
1180                        // Should never happen ideally.
1181                        Slog.w(TAG, "Empty queue");
1182                    }
1183                    break;
1184                }
1185                case MCS_RECONNECT: {
1186                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1187                    if (mPendingInstalls.size() > 0) {
1188                        if (mBound) {
1189                            disconnectService();
1190                        }
1191                        if (!connectToService()) {
1192                            Slog.e(TAG, "Failed to bind to media container service");
1193                            for (HandlerParams params : mPendingInstalls) {
1194                                // Indicate service bind error
1195                                params.serviceError();
1196                            }
1197                            mPendingInstalls.clear();
1198                        }
1199                    }
1200                    break;
1201                }
1202                case MCS_UNBIND: {
1203                    // If there is no actual work left, then time to unbind.
1204                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1205
1206                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1207                        if (mBound) {
1208                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1209
1210                            disconnectService();
1211                        }
1212                    } else if (mPendingInstalls.size() > 0) {
1213                        // There are more pending requests in queue.
1214                        // Just post MCS_BOUND message to trigger processing
1215                        // of next pending install.
1216                        mHandler.sendEmptyMessage(MCS_BOUND);
1217                    }
1218
1219                    break;
1220                }
1221                case MCS_GIVE_UP: {
1222                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1223                    mPendingInstalls.remove(0);
1224                    break;
1225                }
1226                case SEND_PENDING_BROADCAST: {
1227                    String packages[];
1228                    ArrayList<String> components[];
1229                    int size = 0;
1230                    int uids[];
1231                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1232                    synchronized (mPackages) {
1233                        if (mPendingBroadcasts == null) {
1234                            return;
1235                        }
1236                        size = mPendingBroadcasts.size();
1237                        if (size <= 0) {
1238                            // Nothing to be done. Just return
1239                            return;
1240                        }
1241                        packages = new String[size];
1242                        components = new ArrayList[size];
1243                        uids = new int[size];
1244                        int i = 0;  // filling out the above arrays
1245
1246                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1247                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1248                            Iterator<Map.Entry<String, ArrayList<String>>> it
1249                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1250                                            .entrySet().iterator();
1251                            while (it.hasNext() && i < size) {
1252                                Map.Entry<String, ArrayList<String>> ent = it.next();
1253                                packages[i] = ent.getKey();
1254                                components[i] = ent.getValue();
1255                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1256                                uids[i] = (ps != null)
1257                                        ? UserHandle.getUid(packageUserId, ps.appId)
1258                                        : -1;
1259                                i++;
1260                            }
1261                        }
1262                        size = i;
1263                        mPendingBroadcasts.clear();
1264                    }
1265                    // Send broadcasts
1266                    for (int i = 0; i < size; i++) {
1267                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1268                    }
1269                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1270                    break;
1271                }
1272                case START_CLEANING_PACKAGE: {
1273                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1274                    final String packageName = (String)msg.obj;
1275                    final int userId = msg.arg1;
1276                    final boolean andCode = msg.arg2 != 0;
1277                    synchronized (mPackages) {
1278                        if (userId == UserHandle.USER_ALL) {
1279                            int[] users = sUserManager.getUserIds();
1280                            for (int user : users) {
1281                                mSettings.addPackageToCleanLPw(
1282                                        new PackageCleanItem(user, packageName, andCode));
1283                            }
1284                        } else {
1285                            mSettings.addPackageToCleanLPw(
1286                                    new PackageCleanItem(userId, packageName, andCode));
1287                        }
1288                    }
1289                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1290                    startCleaningPackages();
1291                } break;
1292                case POST_INSTALL: {
1293                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1294                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1295                    mRunningInstalls.delete(msg.arg1);
1296                    boolean deleteOld = false;
1297
1298                    if (data != null) {
1299                        InstallArgs args = data.args;
1300                        PackageInstalledInfo res = data.res;
1301
1302                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1303                            res.removedInfo.sendBroadcast(false, true, false);
1304                            Bundle extras = new Bundle(1);
1305                            extras.putInt(Intent.EXTRA_UID, res.uid);
1306
1307                            // Now that we successfully installed the package, grant runtime
1308                            // permissions if requested before broadcasting the install.
1309                            if ((args.installFlags
1310                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1311                                grantRequestedRuntimePermissions(res.pkg,
1312                                        args.user.getIdentifier());
1313                            }
1314
1315                            // Determine the set of users who are adding this
1316                            // package for the first time vs. those who are seeing
1317                            // an update.
1318                            int[] firstUsers;
1319                            int[] updateUsers = new int[0];
1320                            if (res.origUsers == null || res.origUsers.length == 0) {
1321                                firstUsers = res.newUsers;
1322                            } else {
1323                                firstUsers = new int[0];
1324                                for (int i=0; i<res.newUsers.length; i++) {
1325                                    int user = res.newUsers[i];
1326                                    boolean isNew = true;
1327                                    for (int j=0; j<res.origUsers.length; j++) {
1328                                        if (res.origUsers[j] == user) {
1329                                            isNew = false;
1330                                            break;
1331                                        }
1332                                    }
1333                                    if (isNew) {
1334                                        int[] newFirst = new int[firstUsers.length+1];
1335                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1336                                                firstUsers.length);
1337                                        newFirst[firstUsers.length] = user;
1338                                        firstUsers = newFirst;
1339                                    } else {
1340                                        int[] newUpdate = new int[updateUsers.length+1];
1341                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1342                                                updateUsers.length);
1343                                        newUpdate[updateUsers.length] = user;
1344                                        updateUsers = newUpdate;
1345                                    }
1346                                }
1347                            }
1348                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1349                                    res.pkg.applicationInfo.packageName,
1350                                    extras, null, null, firstUsers);
1351                            final boolean update = res.removedInfo.removedPackage != null;
1352                            if (update) {
1353                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1354                            }
1355                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1356                                    res.pkg.applicationInfo.packageName,
1357                                    extras, null, null, updateUsers);
1358                            if (update) {
1359                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1360                                        res.pkg.applicationInfo.packageName,
1361                                        extras, null, null, updateUsers);
1362                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1363                                        null, null,
1364                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1365
1366                                // treat asec-hosted packages like removable media on upgrade
1367                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1368                                    if (DEBUG_INSTALL) {
1369                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1370                                                + " is ASEC-hosted -> AVAILABLE");
1371                                    }
1372                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1373                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1374                                    pkgList.add(res.pkg.applicationInfo.packageName);
1375                                    sendResourcesChangedBroadcast(true, true,
1376                                            pkgList,uidArray, null);
1377                                }
1378                            }
1379                            if (res.removedInfo.args != null) {
1380                                // Remove the replaced package's older resources safely now
1381                                deleteOld = true;
1382                            }
1383
1384                            // Log current value of "unknown sources" setting
1385                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1386                                getUnknownSourcesSettings());
1387                        }
1388                        // Force a gc to clear up things
1389                        Runtime.getRuntime().gc();
1390                        // We delete after a gc for applications  on sdcard.
1391                        if (deleteOld) {
1392                            synchronized (mInstallLock) {
1393                                res.removedInfo.args.doPostDeleteLI(true);
1394                            }
1395                        }
1396                        if (args.observer != null) {
1397                            try {
1398                                Bundle extras = extrasForInstallResult(res);
1399                                args.observer.onPackageInstalled(res.name, res.returnCode,
1400                                        res.returnMsg, extras);
1401                            } catch (RemoteException e) {
1402                                Slog.i(TAG, "Observer no longer exists.");
1403                            }
1404                        }
1405                    } else {
1406                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1407                    }
1408                } break;
1409                case UPDATED_MEDIA_STATUS: {
1410                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1411                    boolean reportStatus = msg.arg1 == 1;
1412                    boolean doGc = msg.arg2 == 1;
1413                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1414                    if (doGc) {
1415                        // Force a gc to clear up stale containers.
1416                        Runtime.getRuntime().gc();
1417                    }
1418                    if (msg.obj != null) {
1419                        @SuppressWarnings("unchecked")
1420                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1421                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1422                        // Unload containers
1423                        unloadAllContainers(args);
1424                    }
1425                    if (reportStatus) {
1426                        try {
1427                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1428                            PackageHelper.getMountService().finishMediaUpdate();
1429                        } catch (RemoteException e) {
1430                            Log.e(TAG, "MountService not running?");
1431                        }
1432                    }
1433                } break;
1434                case WRITE_SETTINGS: {
1435                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1436                    synchronized (mPackages) {
1437                        removeMessages(WRITE_SETTINGS);
1438                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1439                        mSettings.writeLPr();
1440                        mDirtyUsers.clear();
1441                    }
1442                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443                } break;
1444                case WRITE_PACKAGE_RESTRICTIONS: {
1445                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1446                    synchronized (mPackages) {
1447                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1448                        for (int userId : mDirtyUsers) {
1449                            mSettings.writePackageRestrictionsLPr(userId);
1450                        }
1451                        mDirtyUsers.clear();
1452                    }
1453                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1454                } break;
1455                case CHECK_PENDING_VERIFICATION: {
1456                    final int verificationId = msg.arg1;
1457                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1458
1459                    if ((state != null) && !state.timeoutExtended()) {
1460                        final InstallArgs args = state.getInstallArgs();
1461                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1462
1463                        Slog.i(TAG, "Verification timed out for " + originUri);
1464                        mPendingVerification.remove(verificationId);
1465
1466                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1467
1468                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1469                            Slog.i(TAG, "Continuing with installation of " + originUri);
1470                            state.setVerifierResponse(Binder.getCallingUid(),
1471                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1472                            broadcastPackageVerified(verificationId, originUri,
1473                                    PackageManager.VERIFICATION_ALLOW,
1474                                    state.getInstallArgs().getUser());
1475                            try {
1476                                ret = args.copyApk(mContainerService, true);
1477                            } catch (RemoteException e) {
1478                                Slog.e(TAG, "Could not contact the ContainerService");
1479                            }
1480                        } else {
1481                            broadcastPackageVerified(verificationId, originUri,
1482                                    PackageManager.VERIFICATION_REJECT,
1483                                    state.getInstallArgs().getUser());
1484                        }
1485
1486                        processPendingInstall(args, ret);
1487                        mHandler.sendEmptyMessage(MCS_UNBIND);
1488                    }
1489                    break;
1490                }
1491                case PACKAGE_VERIFIED: {
1492                    final int verificationId = msg.arg1;
1493
1494                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1495                    if (state == null) {
1496                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1497                        break;
1498                    }
1499
1500                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1501
1502                    state.setVerifierResponse(response.callerUid, response.code);
1503
1504                    if (state.isVerificationComplete()) {
1505                        mPendingVerification.remove(verificationId);
1506
1507                        final InstallArgs args = state.getInstallArgs();
1508                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1509
1510                        int ret;
1511                        if (state.isInstallAllowed()) {
1512                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    response.code, state.getInstallArgs().getUser());
1515                            try {
1516                                ret = args.copyApk(mContainerService, true);
1517                            } catch (RemoteException e) {
1518                                Slog.e(TAG, "Could not contact the ContainerService");
1519                            }
1520                        } else {
1521                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1522                        }
1523
1524                        processPendingInstall(args, ret);
1525
1526                        mHandler.sendEmptyMessage(MCS_UNBIND);
1527                    }
1528
1529                    break;
1530                }
1531                case START_INTENT_FILTER_VERIFICATIONS: {
1532                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1533                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1534                            params.replacing, params.pkg);
1535                    break;
1536                }
1537                case INTENT_FILTER_VERIFIED: {
1538                    final int verificationId = msg.arg1;
1539
1540                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1541                            verificationId);
1542                    if (state == null) {
1543                        Slog.w(TAG, "Invalid IntentFilter verification token "
1544                                + verificationId + " received");
1545                        break;
1546                    }
1547
1548                    final int userId = state.getUserId();
1549
1550                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1551                            "Processing IntentFilter verification with token:"
1552                            + verificationId + " and userId:" + userId);
1553
1554                    final IntentFilterVerificationResponse response =
1555                            (IntentFilterVerificationResponse) msg.obj;
1556
1557                    state.setVerifierResponse(response.callerUid, response.code);
1558
1559                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1560                            "IntentFilter verification with token:" + verificationId
1561                            + " and userId:" + userId
1562                            + " is settings verifier response with response code:"
1563                            + response.code);
1564
1565                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1566                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1567                                + response.getFailedDomainsString());
1568                    }
1569
1570                    if (state.isVerificationComplete()) {
1571                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1572                    } else {
1573                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1574                                "IntentFilter verification with token:" + verificationId
1575                                + " was not said to be complete");
1576                    }
1577
1578                    break;
1579                }
1580            }
1581        }
1582    }
1583
1584    private StorageEventListener mStorageListener = new StorageEventListener() {
1585        @Override
1586        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1587            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1588                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1589                    // TODO: ensure that private directories exist for all active users
1590                    // TODO: remove user data whose serial number doesn't match
1591                    loadPrivatePackages(vol);
1592                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1593                    unloadPrivatePackages(vol);
1594                }
1595            }
1596
1597            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1598                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1599                    updateExternalMediaStatus(true, false);
1600                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1601                    updateExternalMediaStatus(false, false);
1602                }
1603            }
1604        }
1605
1606        @Override
1607        public void onVolumeForgotten(String fsUuid) {
1608            // TODO: remove all packages hosted on this uuid
1609        }
1610    };
1611
1612    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1613        if (userId >= UserHandle.USER_OWNER) {
1614            grantRequestedRuntimePermissionsForUser(pkg, userId);
1615        } else if (userId == UserHandle.USER_ALL) {
1616            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1617                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1618            }
1619        }
1620
1621        // We could have touched GID membership, so flush out packages.list
1622        synchronized (mPackages) {
1623            mSettings.writePackageListLPr();
1624        }
1625    }
1626
1627    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1628        SettingBase sb = (SettingBase) pkg.mExtras;
1629        if (sb == null) {
1630            return;
1631        }
1632
1633        PermissionsState permissionsState = sb.getPermissionsState();
1634
1635        for (String permission : pkg.requestedPermissions) {
1636            BasePermission bp = mSettings.mPermissions.get(permission);
1637            if (bp != null && bp.isRuntime()) {
1638                permissionsState.grantRuntimePermission(bp, userId);
1639            }
1640        }
1641    }
1642
1643    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1644        Bundle extras = null;
1645        switch (res.returnCode) {
1646            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1647                extras = new Bundle();
1648                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1649                        res.origPermission);
1650                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1651                        res.origPackage);
1652                break;
1653            }
1654            case PackageManager.INSTALL_SUCCEEDED: {
1655                extras = new Bundle();
1656                extras.putBoolean(Intent.EXTRA_REPLACING,
1657                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1658                break;
1659            }
1660        }
1661        return extras;
1662    }
1663
1664    void scheduleWriteSettingsLocked() {
1665        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1666            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1667        }
1668    }
1669
1670    void scheduleWritePackageRestrictionsLocked(int userId) {
1671        if (!sUserManager.exists(userId)) return;
1672        mDirtyUsers.add(userId);
1673        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1674            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1675        }
1676    }
1677
1678    public static PackageManagerService main(Context context, Installer installer,
1679            boolean factoryTest, boolean onlyCore) {
1680        PackageManagerService m = new PackageManagerService(context, installer,
1681                factoryTest, onlyCore);
1682        ServiceManager.addService("package", m);
1683        return m;
1684    }
1685
1686    static String[] splitString(String str, char sep) {
1687        int count = 1;
1688        int i = 0;
1689        while ((i=str.indexOf(sep, i)) >= 0) {
1690            count++;
1691            i++;
1692        }
1693
1694        String[] res = new String[count];
1695        i=0;
1696        count = 0;
1697        int lastI=0;
1698        while ((i=str.indexOf(sep, i)) >= 0) {
1699            res[count] = str.substring(lastI, i);
1700            count++;
1701            i++;
1702            lastI = i;
1703        }
1704        res[count] = str.substring(lastI, str.length());
1705        return res;
1706    }
1707
1708    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1709        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1710                Context.DISPLAY_SERVICE);
1711        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1712    }
1713
1714    public PackageManagerService(Context context, Installer installer,
1715            boolean factoryTest, boolean onlyCore) {
1716        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1717                SystemClock.uptimeMillis());
1718
1719        if (mSdkVersion <= 0) {
1720            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1721        }
1722
1723        mContext = context;
1724        mFactoryTest = factoryTest;
1725        mOnlyCore = onlyCore;
1726        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1727        mMetrics = new DisplayMetrics();
1728        mSettings = new Settings(mPackages);
1729        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1730                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1731        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1732                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1733        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1734                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1735        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1736                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1737        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1738                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1739        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1740                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1741
1742        // TODO: add a property to control this?
1743        long dexOptLRUThresholdInMinutes;
1744        if (mLazyDexOpt) {
1745            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1746        } else {
1747            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1748        }
1749        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1750
1751        String separateProcesses = SystemProperties.get("debug.separate_processes");
1752        if (separateProcesses != null && separateProcesses.length() > 0) {
1753            if ("*".equals(separateProcesses)) {
1754                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1755                mSeparateProcesses = null;
1756                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1757            } else {
1758                mDefParseFlags = 0;
1759                mSeparateProcesses = separateProcesses.split(",");
1760                Slog.w(TAG, "Running with debug.separate_processes: "
1761                        + separateProcesses);
1762            }
1763        } else {
1764            mDefParseFlags = 0;
1765            mSeparateProcesses = null;
1766        }
1767
1768        mInstaller = installer;
1769        mPackageDexOptimizer = new PackageDexOptimizer(this);
1770        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1771
1772        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1773                FgThread.get().getLooper());
1774
1775        getDefaultDisplayMetrics(context, mMetrics);
1776
1777        SystemConfig systemConfig = SystemConfig.getInstance();
1778        mGlobalGids = systemConfig.getGlobalGids();
1779        mSystemPermissions = systemConfig.getSystemPermissions();
1780        mAvailableFeatures = systemConfig.getAvailableFeatures();
1781
1782        synchronized (mInstallLock) {
1783        // writer
1784        synchronized (mPackages) {
1785            mHandlerThread = new ServiceThread(TAG,
1786                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1787            mHandlerThread.start();
1788            mHandler = new PackageHandler(mHandlerThread.getLooper());
1789            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1790
1791            File dataDir = Environment.getDataDirectory();
1792            mAppDataDir = new File(dataDir, "data");
1793            mAppInstallDir = new File(dataDir, "app");
1794            mAppLib32InstallDir = new File(dataDir, "app-lib");
1795            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1796            mUserAppDataDir = new File(dataDir, "user");
1797            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1798
1799            sUserManager = new UserManagerService(context, this,
1800                    mInstallLock, mPackages);
1801
1802            // Propagate permission configuration in to package manager.
1803            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1804                    = systemConfig.getPermissions();
1805            for (int i=0; i<permConfig.size(); i++) {
1806                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1807                BasePermission bp = mSettings.mPermissions.get(perm.name);
1808                if (bp == null) {
1809                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1810                    mSettings.mPermissions.put(perm.name, bp);
1811                }
1812                if (perm.gids != null) {
1813                    bp.setGids(perm.gids, perm.perUser);
1814                }
1815            }
1816
1817            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1818            for (int i=0; i<libConfig.size(); i++) {
1819                mSharedLibraries.put(libConfig.keyAt(i),
1820                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1821            }
1822
1823            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1824
1825            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1826                    mSdkVersion, mOnlyCore);
1827
1828            String customResolverActivity = Resources.getSystem().getString(
1829                    R.string.config_customResolverActivity);
1830            if (TextUtils.isEmpty(customResolverActivity)) {
1831                customResolverActivity = null;
1832            } else {
1833                mCustomResolverComponentName = ComponentName.unflattenFromString(
1834                        customResolverActivity);
1835            }
1836
1837            long startTime = SystemClock.uptimeMillis();
1838
1839            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1840                    startTime);
1841
1842            // Set flag to monitor and not change apk file paths when
1843            // scanning install directories.
1844            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1845
1846            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1847
1848            /**
1849             * Add everything in the in the boot class path to the
1850             * list of process files because dexopt will have been run
1851             * if necessary during zygote startup.
1852             */
1853            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1854            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1855
1856            if (bootClassPath != null) {
1857                String[] bootClassPathElements = splitString(bootClassPath, ':');
1858                for (String element : bootClassPathElements) {
1859                    alreadyDexOpted.add(element);
1860                }
1861            } else {
1862                Slog.w(TAG, "No BOOTCLASSPATH found!");
1863            }
1864
1865            if (systemServerClassPath != null) {
1866                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1867                for (String element : systemServerClassPathElements) {
1868                    alreadyDexOpted.add(element);
1869                }
1870            } else {
1871                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1872            }
1873
1874            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1875            final String[] dexCodeInstructionSets =
1876                    getDexCodeInstructionSets(
1877                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1878
1879            /**
1880             * Ensure all external libraries have had dexopt run on them.
1881             */
1882            if (mSharedLibraries.size() > 0) {
1883                // NOTE: For now, we're compiling these system "shared libraries"
1884                // (and framework jars) into all available architectures. It's possible
1885                // to compile them only when we come across an app that uses them (there's
1886                // already logic for that in scanPackageLI) but that adds some complexity.
1887                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1888                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1889                        final String lib = libEntry.path;
1890                        if (lib == null) {
1891                            continue;
1892                        }
1893
1894                        try {
1895                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1896                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1897                                alreadyDexOpted.add(lib);
1898                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1899                            }
1900                        } catch (FileNotFoundException e) {
1901                            Slog.w(TAG, "Library not found: " + lib);
1902                        } catch (IOException e) {
1903                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1904                                    + e.getMessage());
1905                        }
1906                    }
1907                }
1908            }
1909
1910            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1911
1912            // Gross hack for now: we know this file doesn't contain any
1913            // code, so don't dexopt it to avoid the resulting log spew.
1914            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1915
1916            // Gross hack for now: we know this file is only part of
1917            // the boot class path for art, so don't dexopt it to
1918            // avoid the resulting log spew.
1919            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1920
1921            /**
1922             * There are a number of commands implemented in Java, which
1923             * we currently need to do the dexopt on so that they can be
1924             * run from a non-root shell.
1925             */
1926            String[] frameworkFiles = frameworkDir.list();
1927            if (frameworkFiles != null) {
1928                // TODO: We could compile these only for the most preferred ABI. We should
1929                // first double check that the dex files for these commands are not referenced
1930                // by other system apps.
1931                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1932                    for (int i=0; i<frameworkFiles.length; i++) {
1933                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1934                        String path = libPath.getPath();
1935                        // Skip the file if we already did it.
1936                        if (alreadyDexOpted.contains(path)) {
1937                            continue;
1938                        }
1939                        // Skip the file if it is not a type we want to dexopt.
1940                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1941                            continue;
1942                        }
1943                        try {
1944                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1945                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1946                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1947                            }
1948                        } catch (FileNotFoundException e) {
1949                            Slog.w(TAG, "Jar not found: " + path);
1950                        } catch (IOException e) {
1951                            Slog.w(TAG, "Exception reading jar: " + path, e);
1952                        }
1953                    }
1954                }
1955            }
1956
1957            // Collect vendor overlay packages.
1958            // (Do this before scanning any apps.)
1959            // For security and version matching reason, only consider
1960            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1961            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1962            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1963                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1964
1965            // Find base frameworks (resource packages without code).
1966            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1967                    | PackageParser.PARSE_IS_SYSTEM_DIR
1968                    | PackageParser.PARSE_IS_PRIVILEGED,
1969                    scanFlags | SCAN_NO_DEX, 0);
1970
1971            // Collected privileged system packages.
1972            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1973            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1974                    | PackageParser.PARSE_IS_SYSTEM_DIR
1975                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1976
1977            // Collect ordinary system packages.
1978            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1979            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1980                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1981
1982            // Collect all vendor packages.
1983            File vendorAppDir = new File("/vendor/app");
1984            try {
1985                vendorAppDir = vendorAppDir.getCanonicalFile();
1986            } catch (IOException e) {
1987                // failed to look up canonical path, continue with original one
1988            }
1989            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1990                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1991
1992            // Collect all OEM packages.
1993            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1994            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1995                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1996
1997            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1998            mInstaller.moveFiles();
1999
2000            // Prune any system packages that no longer exist.
2001            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2002            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2003            if (!mOnlyCore) {
2004                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2005                while (psit.hasNext()) {
2006                    PackageSetting ps = psit.next();
2007
2008                    /*
2009                     * If this is not a system app, it can't be a
2010                     * disable system app.
2011                     */
2012                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2013                        continue;
2014                    }
2015
2016                    /*
2017                     * If the package is scanned, it's not erased.
2018                     */
2019                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2020                    if (scannedPkg != null) {
2021                        /*
2022                         * If the system app is both scanned and in the
2023                         * disabled packages list, then it must have been
2024                         * added via OTA. Remove it from the currently
2025                         * scanned package so the previously user-installed
2026                         * application can be scanned.
2027                         */
2028                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2029                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2030                                    + ps.name + "; removing system app.  Last known codePath="
2031                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2032                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2033                                    + scannedPkg.mVersionCode);
2034                            removePackageLI(ps, true);
2035                            expectingBetter.put(ps.name, ps.codePath);
2036                        }
2037
2038                        continue;
2039                    }
2040
2041                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2042                        psit.remove();
2043                        logCriticalInfo(Log.WARN, "System package " + ps.name
2044                                + " no longer exists; wiping its data");
2045                        removeDataDirsLI(null, ps.name);
2046                    } else {
2047                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2048                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2049                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2050                        }
2051                    }
2052                }
2053            }
2054
2055            //look for any incomplete package installations
2056            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2057            //clean up list
2058            for(int i = 0; i < deletePkgsList.size(); i++) {
2059                //clean up here
2060                cleanupInstallFailedPackage(deletePkgsList.get(i));
2061            }
2062            //delete tmp files
2063            deleteTempPackageFiles();
2064
2065            // Remove any shared userIDs that have no associated packages
2066            mSettings.pruneSharedUsersLPw();
2067
2068            if (!mOnlyCore) {
2069                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2070                        SystemClock.uptimeMillis());
2071                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2072
2073                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2074                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2075
2076                /**
2077                 * Remove disable package settings for any updated system
2078                 * apps that were removed via an OTA. If they're not a
2079                 * previously-updated app, remove them completely.
2080                 * Otherwise, just revoke their system-level permissions.
2081                 */
2082                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2083                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2084                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2085
2086                    String msg;
2087                    if (deletedPkg == null) {
2088                        msg = "Updated system package " + deletedAppName
2089                                + " no longer exists; wiping its data";
2090                        removeDataDirsLI(null, deletedAppName);
2091                    } else {
2092                        msg = "Updated system app + " + deletedAppName
2093                                + " no longer present; removing system privileges for "
2094                                + deletedAppName;
2095
2096                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2097
2098                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2099                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2100                    }
2101                    logCriticalInfo(Log.WARN, msg);
2102                }
2103
2104                /**
2105                 * Make sure all system apps that we expected to appear on
2106                 * the userdata partition actually showed up. If they never
2107                 * appeared, crawl back and revive the system version.
2108                 */
2109                for (int i = 0; i < expectingBetter.size(); i++) {
2110                    final String packageName = expectingBetter.keyAt(i);
2111                    if (!mPackages.containsKey(packageName)) {
2112                        final File scanFile = expectingBetter.valueAt(i);
2113
2114                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2115                                + " but never showed up; reverting to system");
2116
2117                        final int reparseFlags;
2118                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2119                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2120                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2121                                    | PackageParser.PARSE_IS_PRIVILEGED;
2122                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2123                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2124                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2125                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2126                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2127                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2128                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2129                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2130                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2131                        } else {
2132                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2133                            continue;
2134                        }
2135
2136                        mSettings.enableSystemPackageLPw(packageName);
2137
2138                        try {
2139                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2140                        } catch (PackageManagerException e) {
2141                            Slog.e(TAG, "Failed to parse original system package: "
2142                                    + e.getMessage());
2143                        }
2144                    }
2145                }
2146            }
2147
2148            // Now that we know all of the shared libraries, update all clients to have
2149            // the correct library paths.
2150            updateAllSharedLibrariesLPw();
2151
2152            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2153                // NOTE: We ignore potential failures here during a system scan (like
2154                // the rest of the commands above) because there's precious little we
2155                // can do about it. A settings error is reported, though.
2156                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2157                        false /* force dexopt */, false /* defer dexopt */);
2158            }
2159
2160            // Now that we know all the packages we are keeping,
2161            // read and update their last usage times.
2162            mPackageUsage.readLP();
2163
2164            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2165                    SystemClock.uptimeMillis());
2166            Slog.i(TAG, "Time to scan packages: "
2167                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2168                    + " seconds");
2169
2170            // If the platform SDK has changed since the last time we booted,
2171            // we need to re-grant app permission to catch any new ones that
2172            // appear.  This is really a hack, and means that apps can in some
2173            // cases get permissions that the user didn't initially explicitly
2174            // allow...  it would be nice to have some better way to handle
2175            // this situation.
2176            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2177                    != mSdkVersion;
2178            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2179                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2180                    + "; regranting permissions for internal storage");
2181            mSettings.mInternalSdkPlatform = mSdkVersion;
2182
2183            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2184                    | (regrantPermissions
2185                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2186                            : 0));
2187
2188            // If this is the first boot, and it is a normal boot, then
2189            // we need to initialize the default preferred apps.
2190            if (!mRestoredSettings && !onlyCore) {
2191                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2192                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2193            }
2194
2195            // If this is first boot after an OTA, and a normal boot, then
2196            // we need to clear code cache directories.
2197            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2198            if (mIsUpgrade && !onlyCore) {
2199                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2200                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2201                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2202                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2203                }
2204                mSettings.mFingerprint = Build.FINGERPRINT;
2205            }
2206
2207            primeDomainVerificationsLPw();
2208            checkDefaultBrowser();
2209
2210            // All the changes are done during package scanning.
2211            mSettings.updateInternalDatabaseVersion();
2212
2213            // can downgrade to reader
2214            mSettings.writeLPr();
2215
2216            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2217                    SystemClock.uptimeMillis());
2218
2219            mRequiredVerifierPackage = getRequiredVerifierLPr();
2220
2221            mInstallerService = new PackageInstallerService(context, this);
2222
2223            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2224            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2225                    mIntentFilterVerifierComponent);
2226
2227        } // synchronized (mPackages)
2228        } // synchronized (mInstallLock)
2229
2230        // Now after opening every single application zip, make sure they
2231        // are all flushed.  Not really needed, but keeps things nice and
2232        // tidy.
2233        Runtime.getRuntime().gc();
2234
2235        // Expose private service for system components to use.
2236        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2237    }
2238
2239    @Override
2240    public boolean isFirstBoot() {
2241        return !mRestoredSettings;
2242    }
2243
2244    @Override
2245    public boolean isOnlyCoreApps() {
2246        return mOnlyCore;
2247    }
2248
2249    @Override
2250    public boolean isUpgrade() {
2251        return mIsUpgrade;
2252    }
2253
2254    private String getRequiredVerifierLPr() {
2255        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2256        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2257                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2258
2259        String requiredVerifier = null;
2260
2261        final int N = receivers.size();
2262        for (int i = 0; i < N; i++) {
2263            final ResolveInfo info = receivers.get(i);
2264
2265            if (info.activityInfo == null) {
2266                continue;
2267            }
2268
2269            final String packageName = info.activityInfo.packageName;
2270
2271            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2272                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2273                continue;
2274            }
2275
2276            if (requiredVerifier != null) {
2277                throw new RuntimeException("There can be only one required verifier");
2278            }
2279
2280            requiredVerifier = packageName;
2281        }
2282
2283        return requiredVerifier;
2284    }
2285
2286    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2287        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2288        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2289                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2290
2291        ComponentName verifierComponentName = null;
2292
2293        int priority = -1000;
2294        final int N = receivers.size();
2295        for (int i = 0; i < N; i++) {
2296            final ResolveInfo info = receivers.get(i);
2297
2298            if (info.activityInfo == null) {
2299                continue;
2300            }
2301
2302            final String packageName = info.activityInfo.packageName;
2303
2304            final PackageSetting ps = mSettings.mPackages.get(packageName);
2305            if (ps == null) {
2306                continue;
2307            }
2308
2309            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2310                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2311                continue;
2312            }
2313
2314            // Select the IntentFilterVerifier with the highest priority
2315            if (priority < info.priority) {
2316                priority = info.priority;
2317                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2318                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2319                        + verifierComponentName + " with priority: " + info.priority);
2320            }
2321        }
2322
2323        return verifierComponentName;
2324    }
2325
2326    private void primeDomainVerificationsLPw() {
2327        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2328        boolean updated = false;
2329        ArraySet<String> allHostsSet = new ArraySet<>();
2330        for (PackageParser.Package pkg : mPackages.values()) {
2331            final String packageName = pkg.packageName;
2332            if (!hasDomainURLs(pkg)) {
2333                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2334                            "package with no domain URLs: " + packageName);
2335                continue;
2336            }
2337            if (!pkg.isSystemApp()) {
2338                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2339                        "No priming domain verifications for a non system package : " +
2340                                packageName);
2341                continue;
2342            }
2343            for (PackageParser.Activity a : pkg.activities) {
2344                for (ActivityIntentInfo filter : a.intents) {
2345                    if (hasValidDomains(filter)) {
2346                        allHostsSet.addAll(filter.getHostsList());
2347                    }
2348                }
2349            }
2350            if (allHostsSet.size() == 0) {
2351                allHostsSet.add("*");
2352            }
2353            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2354            IntentFilterVerificationInfo ivi =
2355                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2356            if (ivi != null) {
2357                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2358                        "Priming domain verifications for package: " + packageName +
2359                        " with hosts:" + ivi.getDomainsString());
2360                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2361                updated = true;
2362            }
2363            else {
2364                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2365                        "No priming domain verifications for package: " + packageName);
2366            }
2367            allHostsSet.clear();
2368        }
2369        if (updated) {
2370            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2371                    "Will need to write primed domain verifications");
2372        }
2373        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2374    }
2375
2376    private void applyFactoryDefaultBrowserLPw(int userId) {
2377        // The default browser app's package name is stored in a string resource,
2378        // with a product-specific overlay used for vendor customization.
2379        String browserPkg = mContext.getResources().getString(
2380                com.android.internal.R.string.default_browser);
2381        if (browserPkg != null) {
2382            // non-empty string => required to be a known package
2383            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2384            if (ps == null) {
2385                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2386                browserPkg = null;
2387            } else {
2388                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2389            }
2390        }
2391
2392        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2393        // default.  If there's more than one, just leave everything alone.
2394        if (browserPkg == null) {
2395            calculateDefaultBrowserLPw(userId);
2396        }
2397    }
2398
2399    private void calculateDefaultBrowserLPw(int userId) {
2400        List<String> allBrowsers = resolveAllBrowserApps(userId);
2401        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2402        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2403    }
2404
2405    private List<String> resolveAllBrowserApps(int userId) {
2406        // Match all generic http: browser apps
2407        Intent intent = new Intent();
2408        intent.setAction(Intent.ACTION_VIEW);
2409        intent.addCategory(Intent.CATEGORY_BROWSABLE);
2410        intent.setData(Uri.parse("http:"));
2411
2412        // Resolve that intent and check that the handleAllWebDataURI boolean is set
2413        List<ResolveInfo> list = queryIntentActivities(intent, null, 0, userId);
2414
2415        final int count = list.size();
2416        List<String> result = new ArrayList<String>(count);
2417        for (int i=0; i<count; i++) {
2418            ResolveInfo info = list.get(i);
2419            if (info.activityInfo == null
2420                    || !info.handleAllWebDataURI
2421                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2422                    || result.contains(info.activityInfo.packageName)) {
2423                continue;
2424            }
2425            result.add(info.activityInfo.packageName);
2426        }
2427
2428        return result;
2429    }
2430
2431    private void checkDefaultBrowser() {
2432        final int myUserId = UserHandle.myUserId();
2433        final String packageName = getDefaultBrowserPackageName(myUserId);
2434        if (packageName != null) {
2435            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2436            if (info == null) {
2437                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2438                synchronized (mPackages) {
2439                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2440                }
2441            }
2442        }
2443    }
2444
2445    @Override
2446    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2447            throws RemoteException {
2448        try {
2449            return super.onTransact(code, data, reply, flags);
2450        } catch (RuntimeException e) {
2451            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2452                Slog.wtf(TAG, "Package Manager Crash", e);
2453            }
2454            throw e;
2455        }
2456    }
2457
2458    void cleanupInstallFailedPackage(PackageSetting ps) {
2459        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2460
2461        removeDataDirsLI(ps.volumeUuid, ps.name);
2462        if (ps.codePath != null) {
2463            if (ps.codePath.isDirectory()) {
2464                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2465            } else {
2466                ps.codePath.delete();
2467            }
2468        }
2469        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2470            if (ps.resourcePath.isDirectory()) {
2471                FileUtils.deleteContents(ps.resourcePath);
2472            }
2473            ps.resourcePath.delete();
2474        }
2475        mSettings.removePackageLPw(ps.name);
2476    }
2477
2478    static int[] appendInts(int[] cur, int[] add) {
2479        if (add == null) return cur;
2480        if (cur == null) return add;
2481        final int N = add.length;
2482        for (int i=0; i<N; i++) {
2483            cur = appendInt(cur, add[i]);
2484        }
2485        return cur;
2486    }
2487
2488    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2489        if (!sUserManager.exists(userId)) return null;
2490        final PackageSetting ps = (PackageSetting) p.mExtras;
2491        if (ps == null) {
2492            return null;
2493        }
2494
2495        final PermissionsState permissionsState = ps.getPermissionsState();
2496
2497        final int[] gids = permissionsState.computeGids(userId);
2498        final Set<String> permissions = permissionsState.getPermissions(userId);
2499        final PackageUserState state = ps.readUserState(userId);
2500
2501        return PackageParser.generatePackageInfo(p, gids, flags,
2502                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2503    }
2504
2505    @Override
2506    public boolean isPackageFrozen(String packageName) {
2507        synchronized (mPackages) {
2508            final PackageSetting ps = mSettings.mPackages.get(packageName);
2509            if (ps != null) {
2510                return ps.frozen;
2511            }
2512        }
2513        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2514        return true;
2515    }
2516
2517    @Override
2518    public boolean isPackageAvailable(String packageName, int userId) {
2519        if (!sUserManager.exists(userId)) return false;
2520        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2521        synchronized (mPackages) {
2522            PackageParser.Package p = mPackages.get(packageName);
2523            if (p != null) {
2524                final PackageSetting ps = (PackageSetting) p.mExtras;
2525                if (ps != null) {
2526                    final PackageUserState state = ps.readUserState(userId);
2527                    if (state != null) {
2528                        return PackageParser.isAvailable(state);
2529                    }
2530                }
2531            }
2532        }
2533        return false;
2534    }
2535
2536    @Override
2537    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2538        if (!sUserManager.exists(userId)) return null;
2539        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2540        // reader
2541        synchronized (mPackages) {
2542            PackageParser.Package p = mPackages.get(packageName);
2543            if (DEBUG_PACKAGE_INFO)
2544                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2545            if (p != null) {
2546                return generatePackageInfo(p, flags, userId);
2547            }
2548            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2549                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2550            }
2551        }
2552        return null;
2553    }
2554
2555    @Override
2556    public String[] currentToCanonicalPackageNames(String[] names) {
2557        String[] out = new String[names.length];
2558        // reader
2559        synchronized (mPackages) {
2560            for (int i=names.length-1; i>=0; i--) {
2561                PackageSetting ps = mSettings.mPackages.get(names[i]);
2562                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2563            }
2564        }
2565        return out;
2566    }
2567
2568    @Override
2569    public String[] canonicalToCurrentPackageNames(String[] names) {
2570        String[] out = new String[names.length];
2571        // reader
2572        synchronized (mPackages) {
2573            for (int i=names.length-1; i>=0; i--) {
2574                String cur = mSettings.mRenamedPackages.get(names[i]);
2575                out[i] = cur != null ? cur : names[i];
2576            }
2577        }
2578        return out;
2579    }
2580
2581    @Override
2582    public int getPackageUid(String packageName, int userId) {
2583        if (!sUserManager.exists(userId)) return -1;
2584        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2585
2586        // reader
2587        synchronized (mPackages) {
2588            PackageParser.Package p = mPackages.get(packageName);
2589            if(p != null) {
2590                return UserHandle.getUid(userId, p.applicationInfo.uid);
2591            }
2592            PackageSetting ps = mSettings.mPackages.get(packageName);
2593            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2594                return -1;
2595            }
2596            p = ps.pkg;
2597            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2598        }
2599    }
2600
2601    @Override
2602    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2603        if (!sUserManager.exists(userId)) {
2604            return null;
2605        }
2606
2607        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2608                "getPackageGids");
2609
2610        // reader
2611        synchronized (mPackages) {
2612            PackageParser.Package p = mPackages.get(packageName);
2613            if (DEBUG_PACKAGE_INFO) {
2614                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2615            }
2616            if (p != null) {
2617                PackageSetting ps = (PackageSetting) p.mExtras;
2618                return ps.getPermissionsState().computeGids(userId);
2619            }
2620        }
2621
2622        return null;
2623    }
2624
2625    @Override
2626    public int getMountExternalMode(int uid) {
2627        if (Process.isIsolated(uid)) {
2628            return Zygote.MOUNT_EXTERNAL_NONE;
2629        } else {
2630            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2631                return Zygote.MOUNT_EXTERNAL_WRITE;
2632            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2633                return Zygote.MOUNT_EXTERNAL_READ;
2634            } else {
2635                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2636            }
2637        }
2638    }
2639
2640    static PermissionInfo generatePermissionInfo(
2641            BasePermission bp, int flags) {
2642        if (bp.perm != null) {
2643            return PackageParser.generatePermissionInfo(bp.perm, flags);
2644        }
2645        PermissionInfo pi = new PermissionInfo();
2646        pi.name = bp.name;
2647        pi.packageName = bp.sourcePackage;
2648        pi.nonLocalizedLabel = bp.name;
2649        pi.protectionLevel = bp.protectionLevel;
2650        return pi;
2651    }
2652
2653    @Override
2654    public PermissionInfo getPermissionInfo(String name, int flags) {
2655        // reader
2656        synchronized (mPackages) {
2657            final BasePermission p = mSettings.mPermissions.get(name);
2658            if (p != null) {
2659                return generatePermissionInfo(p, flags);
2660            }
2661            return null;
2662        }
2663    }
2664
2665    @Override
2666    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2667        // reader
2668        synchronized (mPackages) {
2669            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2670            for (BasePermission p : mSettings.mPermissions.values()) {
2671                if (group == null) {
2672                    if (p.perm == null || p.perm.info.group == null) {
2673                        out.add(generatePermissionInfo(p, flags));
2674                    }
2675                } else {
2676                    if (p.perm != null && group.equals(p.perm.info.group)) {
2677                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2678                    }
2679                }
2680            }
2681
2682            if (out.size() > 0) {
2683                return out;
2684            }
2685            return mPermissionGroups.containsKey(group) ? out : null;
2686        }
2687    }
2688
2689    @Override
2690    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2691        // reader
2692        synchronized (mPackages) {
2693            return PackageParser.generatePermissionGroupInfo(
2694                    mPermissionGroups.get(name), flags);
2695        }
2696    }
2697
2698    @Override
2699    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2700        // reader
2701        synchronized (mPackages) {
2702            final int N = mPermissionGroups.size();
2703            ArrayList<PermissionGroupInfo> out
2704                    = new ArrayList<PermissionGroupInfo>(N);
2705            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2706                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2707            }
2708            return out;
2709        }
2710    }
2711
2712    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2713            int userId) {
2714        if (!sUserManager.exists(userId)) return null;
2715        PackageSetting ps = mSettings.mPackages.get(packageName);
2716        if (ps != null) {
2717            if (ps.pkg == null) {
2718                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2719                        flags, userId);
2720                if (pInfo != null) {
2721                    return pInfo.applicationInfo;
2722                }
2723                return null;
2724            }
2725            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2726                    ps.readUserState(userId), userId);
2727        }
2728        return null;
2729    }
2730
2731    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2732            int userId) {
2733        if (!sUserManager.exists(userId)) return null;
2734        PackageSetting ps = mSettings.mPackages.get(packageName);
2735        if (ps != null) {
2736            PackageParser.Package pkg = ps.pkg;
2737            if (pkg == null) {
2738                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2739                    return null;
2740                }
2741                // Only data remains, so we aren't worried about code paths
2742                pkg = new PackageParser.Package(packageName);
2743                pkg.applicationInfo.packageName = packageName;
2744                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2745                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2746                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2747                        packageName, userId).getAbsolutePath();
2748                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2749                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2750            }
2751            return generatePackageInfo(pkg, flags, userId);
2752        }
2753        return null;
2754    }
2755
2756    @Override
2757    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2758        if (!sUserManager.exists(userId)) return null;
2759        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2760        // writer
2761        synchronized (mPackages) {
2762            PackageParser.Package p = mPackages.get(packageName);
2763            if (DEBUG_PACKAGE_INFO) Log.v(
2764                    TAG, "getApplicationInfo " + packageName
2765                    + ": " + p);
2766            if (p != null) {
2767                PackageSetting ps = mSettings.mPackages.get(packageName);
2768                if (ps == null) return null;
2769                // Note: isEnabledLP() does not apply here - always return info
2770                return PackageParser.generateApplicationInfo(
2771                        p, flags, ps.readUserState(userId), userId);
2772            }
2773            if ("android".equals(packageName)||"system".equals(packageName)) {
2774                return mAndroidApplication;
2775            }
2776            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2777                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2778            }
2779        }
2780        return null;
2781    }
2782
2783    @Override
2784    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2785            final IPackageDataObserver observer) {
2786        mContext.enforceCallingOrSelfPermission(
2787                android.Manifest.permission.CLEAR_APP_CACHE, null);
2788        // Queue up an async operation since clearing cache may take a little while.
2789        mHandler.post(new Runnable() {
2790            public void run() {
2791                mHandler.removeCallbacks(this);
2792                int retCode = -1;
2793                synchronized (mInstallLock) {
2794                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2795                    if (retCode < 0) {
2796                        Slog.w(TAG, "Couldn't clear application caches");
2797                    }
2798                }
2799                if (observer != null) {
2800                    try {
2801                        observer.onRemoveCompleted(null, (retCode >= 0));
2802                    } catch (RemoteException e) {
2803                        Slog.w(TAG, "RemoveException when invoking call back");
2804                    }
2805                }
2806            }
2807        });
2808    }
2809
2810    @Override
2811    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2812            final IntentSender pi) {
2813        mContext.enforceCallingOrSelfPermission(
2814                android.Manifest.permission.CLEAR_APP_CACHE, null);
2815        // Queue up an async operation since clearing cache may take a little while.
2816        mHandler.post(new Runnable() {
2817            public void run() {
2818                mHandler.removeCallbacks(this);
2819                int retCode = -1;
2820                synchronized (mInstallLock) {
2821                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2822                    if (retCode < 0) {
2823                        Slog.w(TAG, "Couldn't clear application caches");
2824                    }
2825                }
2826                if(pi != null) {
2827                    try {
2828                        // Callback via pending intent
2829                        int code = (retCode >= 0) ? 1 : 0;
2830                        pi.sendIntent(null, code, null,
2831                                null, null);
2832                    } catch (SendIntentException e1) {
2833                        Slog.i(TAG, "Failed to send pending intent");
2834                    }
2835                }
2836            }
2837        });
2838    }
2839
2840    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2841        synchronized (mInstallLock) {
2842            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2843                throw new IOException("Failed to free enough space");
2844            }
2845        }
2846    }
2847
2848    @Override
2849    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2850        if (!sUserManager.exists(userId)) return null;
2851        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2852        synchronized (mPackages) {
2853            PackageParser.Activity a = mActivities.mActivities.get(component);
2854
2855            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2856            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2857                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2858                if (ps == null) return null;
2859                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2860                        userId);
2861            }
2862            if (mResolveComponentName.equals(component)) {
2863                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2864                        new PackageUserState(), userId);
2865            }
2866        }
2867        return null;
2868    }
2869
2870    @Override
2871    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2872            String resolvedType) {
2873        synchronized (mPackages) {
2874            PackageParser.Activity a = mActivities.mActivities.get(component);
2875            if (a == null) {
2876                return false;
2877            }
2878            for (int i=0; i<a.intents.size(); i++) {
2879                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2880                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2881                    return true;
2882                }
2883            }
2884            return false;
2885        }
2886    }
2887
2888    @Override
2889    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2890        if (!sUserManager.exists(userId)) return null;
2891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2892        synchronized (mPackages) {
2893            PackageParser.Activity a = mReceivers.mActivities.get(component);
2894            if (DEBUG_PACKAGE_INFO) Log.v(
2895                TAG, "getReceiverInfo " + component + ": " + a);
2896            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2897                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2898                if (ps == null) return null;
2899                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2900                        userId);
2901            }
2902        }
2903        return null;
2904    }
2905
2906    @Override
2907    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2908        if (!sUserManager.exists(userId)) return null;
2909        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2910        synchronized (mPackages) {
2911            PackageParser.Service s = mServices.mServices.get(component);
2912            if (DEBUG_PACKAGE_INFO) Log.v(
2913                TAG, "getServiceInfo " + component + ": " + s);
2914            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2915                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2916                if (ps == null) return null;
2917                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2918                        userId);
2919            }
2920        }
2921        return null;
2922    }
2923
2924    @Override
2925    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2926        if (!sUserManager.exists(userId)) return null;
2927        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2928        synchronized (mPackages) {
2929            PackageParser.Provider p = mProviders.mProviders.get(component);
2930            if (DEBUG_PACKAGE_INFO) Log.v(
2931                TAG, "getProviderInfo " + component + ": " + p);
2932            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2933                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2934                if (ps == null) return null;
2935                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2936                        userId);
2937            }
2938        }
2939        return null;
2940    }
2941
2942    @Override
2943    public String[] getSystemSharedLibraryNames() {
2944        Set<String> libSet;
2945        synchronized (mPackages) {
2946            libSet = mSharedLibraries.keySet();
2947            int size = libSet.size();
2948            if (size > 0) {
2949                String[] libs = new String[size];
2950                libSet.toArray(libs);
2951                return libs;
2952            }
2953        }
2954        return null;
2955    }
2956
2957    /**
2958     * @hide
2959     */
2960    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2961        synchronized (mPackages) {
2962            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2963            if (lib != null && lib.apk != null) {
2964                return mPackages.get(lib.apk);
2965            }
2966        }
2967        return null;
2968    }
2969
2970    @Override
2971    public FeatureInfo[] getSystemAvailableFeatures() {
2972        Collection<FeatureInfo> featSet;
2973        synchronized (mPackages) {
2974            featSet = mAvailableFeatures.values();
2975            int size = featSet.size();
2976            if (size > 0) {
2977                FeatureInfo[] features = new FeatureInfo[size+1];
2978                featSet.toArray(features);
2979                FeatureInfo fi = new FeatureInfo();
2980                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2981                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2982                features[size] = fi;
2983                return features;
2984            }
2985        }
2986        return null;
2987    }
2988
2989    @Override
2990    public boolean hasSystemFeature(String name) {
2991        synchronized (mPackages) {
2992            return mAvailableFeatures.containsKey(name);
2993        }
2994    }
2995
2996    private void checkValidCaller(int uid, int userId) {
2997        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2998            return;
2999
3000        throw new SecurityException("Caller uid=" + uid
3001                + " is not privileged to communicate with user=" + userId);
3002    }
3003
3004    @Override
3005    public int checkPermission(String permName, String pkgName, int userId) {
3006        if (!sUserManager.exists(userId)) {
3007            return PackageManager.PERMISSION_DENIED;
3008        }
3009
3010        synchronized (mPackages) {
3011            final PackageParser.Package p = mPackages.get(pkgName);
3012            if (p != null && p.mExtras != null) {
3013                final PackageSetting ps = (PackageSetting) p.mExtras;
3014                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3015                    return PackageManager.PERMISSION_GRANTED;
3016                }
3017            }
3018        }
3019
3020        return PackageManager.PERMISSION_DENIED;
3021    }
3022
3023    @Override
3024    public int checkUidPermission(String permName, int uid) {
3025        final int userId = UserHandle.getUserId(uid);
3026
3027        if (!sUserManager.exists(userId)) {
3028            return PackageManager.PERMISSION_DENIED;
3029        }
3030
3031        synchronized (mPackages) {
3032            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3033            if (obj != null) {
3034                final SettingBase ps = (SettingBase) obj;
3035                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3036                    return PackageManager.PERMISSION_GRANTED;
3037                }
3038            } else {
3039                ArraySet<String> perms = mSystemPermissions.get(uid);
3040                if (perms != null && perms.contains(permName)) {
3041                    return PackageManager.PERMISSION_GRANTED;
3042                }
3043            }
3044        }
3045
3046        return PackageManager.PERMISSION_DENIED;
3047    }
3048
3049    /**
3050     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3051     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3052     * @param checkShell TODO(yamasani):
3053     * @param message the message to log on security exception
3054     */
3055    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3056            boolean checkShell, String message) {
3057        if (userId < 0) {
3058            throw new IllegalArgumentException("Invalid userId " + userId);
3059        }
3060        if (checkShell) {
3061            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3062        }
3063        if (userId == UserHandle.getUserId(callingUid)) return;
3064        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3065            if (requireFullPermission) {
3066                mContext.enforceCallingOrSelfPermission(
3067                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3068            } else {
3069                try {
3070                    mContext.enforceCallingOrSelfPermission(
3071                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3072                } catch (SecurityException se) {
3073                    mContext.enforceCallingOrSelfPermission(
3074                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3075                }
3076            }
3077        }
3078    }
3079
3080    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3081        if (callingUid == Process.SHELL_UID) {
3082            if (userHandle >= 0
3083                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3084                throw new SecurityException("Shell does not have permission to access user "
3085                        + userHandle);
3086            } else if (userHandle < 0) {
3087                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3088                        + Debug.getCallers(3));
3089            }
3090        }
3091    }
3092
3093    private BasePermission findPermissionTreeLP(String permName) {
3094        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3095            if (permName.startsWith(bp.name) &&
3096                    permName.length() > bp.name.length() &&
3097                    permName.charAt(bp.name.length()) == '.') {
3098                return bp;
3099            }
3100        }
3101        return null;
3102    }
3103
3104    private BasePermission checkPermissionTreeLP(String permName) {
3105        if (permName != null) {
3106            BasePermission bp = findPermissionTreeLP(permName);
3107            if (bp != null) {
3108                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3109                    return bp;
3110                }
3111                throw new SecurityException("Calling uid "
3112                        + Binder.getCallingUid()
3113                        + " is not allowed to add to permission tree "
3114                        + bp.name + " owned by uid " + bp.uid);
3115            }
3116        }
3117        throw new SecurityException("No permission tree found for " + permName);
3118    }
3119
3120    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3121        if (s1 == null) {
3122            return s2 == null;
3123        }
3124        if (s2 == null) {
3125            return false;
3126        }
3127        if (s1.getClass() != s2.getClass()) {
3128            return false;
3129        }
3130        return s1.equals(s2);
3131    }
3132
3133    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3134        if (pi1.icon != pi2.icon) return false;
3135        if (pi1.logo != pi2.logo) return false;
3136        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3137        if (!compareStrings(pi1.name, pi2.name)) return false;
3138        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3139        // We'll take care of setting this one.
3140        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3141        // These are not currently stored in settings.
3142        //if (!compareStrings(pi1.group, pi2.group)) return false;
3143        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3144        //if (pi1.labelRes != pi2.labelRes) return false;
3145        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3146        return true;
3147    }
3148
3149    int permissionInfoFootprint(PermissionInfo info) {
3150        int size = info.name.length();
3151        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3152        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3153        return size;
3154    }
3155
3156    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3157        int size = 0;
3158        for (BasePermission perm : mSettings.mPermissions.values()) {
3159            if (perm.uid == tree.uid) {
3160                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3161            }
3162        }
3163        return size;
3164    }
3165
3166    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3167        // We calculate the max size of permissions defined by this uid and throw
3168        // if that plus the size of 'info' would exceed our stated maximum.
3169        if (tree.uid != Process.SYSTEM_UID) {
3170            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3171            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3172                throw new SecurityException("Permission tree size cap exceeded");
3173            }
3174        }
3175    }
3176
3177    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3178        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3179            throw new SecurityException("Label must be specified in permission");
3180        }
3181        BasePermission tree = checkPermissionTreeLP(info.name);
3182        BasePermission bp = mSettings.mPermissions.get(info.name);
3183        boolean added = bp == null;
3184        boolean changed = true;
3185        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3186        if (added) {
3187            enforcePermissionCapLocked(info, tree);
3188            bp = new BasePermission(info.name, tree.sourcePackage,
3189                    BasePermission.TYPE_DYNAMIC);
3190        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3191            throw new SecurityException(
3192                    "Not allowed to modify non-dynamic permission "
3193                    + info.name);
3194        } else {
3195            if (bp.protectionLevel == fixedLevel
3196                    && bp.perm.owner.equals(tree.perm.owner)
3197                    && bp.uid == tree.uid
3198                    && comparePermissionInfos(bp.perm.info, info)) {
3199                changed = false;
3200            }
3201        }
3202        bp.protectionLevel = fixedLevel;
3203        info = new PermissionInfo(info);
3204        info.protectionLevel = fixedLevel;
3205        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3206        bp.perm.info.packageName = tree.perm.info.packageName;
3207        bp.uid = tree.uid;
3208        if (added) {
3209            mSettings.mPermissions.put(info.name, bp);
3210        }
3211        if (changed) {
3212            if (!async) {
3213                mSettings.writeLPr();
3214            } else {
3215                scheduleWriteSettingsLocked();
3216            }
3217        }
3218        return added;
3219    }
3220
3221    @Override
3222    public boolean addPermission(PermissionInfo info) {
3223        synchronized (mPackages) {
3224            return addPermissionLocked(info, false);
3225        }
3226    }
3227
3228    @Override
3229    public boolean addPermissionAsync(PermissionInfo info) {
3230        synchronized (mPackages) {
3231            return addPermissionLocked(info, true);
3232        }
3233    }
3234
3235    @Override
3236    public void removePermission(String name) {
3237        synchronized (mPackages) {
3238            checkPermissionTreeLP(name);
3239            BasePermission bp = mSettings.mPermissions.get(name);
3240            if (bp != null) {
3241                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3242                    throw new SecurityException(
3243                            "Not allowed to modify non-dynamic permission "
3244                            + name);
3245                }
3246                mSettings.mPermissions.remove(name);
3247                mSettings.writeLPr();
3248            }
3249        }
3250    }
3251
3252    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3253            BasePermission bp) {
3254        int index = pkg.requestedPermissions.indexOf(bp.name);
3255        if (index == -1) {
3256            throw new SecurityException("Package " + pkg.packageName
3257                    + " has not requested permission " + bp.name);
3258        }
3259        if (!bp.isRuntime()) {
3260            throw new SecurityException("Permission " + bp.name
3261                    + " is not a changeable permission type");
3262        }
3263    }
3264
3265    @Override
3266    public void grantRuntimePermission(String packageName, String name, final int userId) {
3267        if (!sUserManager.exists(userId)) {
3268            Log.e(TAG, "No such user:" + userId);
3269            return;
3270        }
3271
3272        mContext.enforceCallingOrSelfPermission(
3273                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3274                "grantRuntimePermission");
3275
3276        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3277                "grantRuntimePermission");
3278
3279        final int uid;
3280        final SettingBase sb;
3281
3282        synchronized (mPackages) {
3283            final PackageParser.Package pkg = mPackages.get(packageName);
3284            if (pkg == null) {
3285                throw new IllegalArgumentException("Unknown package: " + packageName);
3286            }
3287
3288            final BasePermission bp = mSettings.mPermissions.get(name);
3289            if (bp == null) {
3290                throw new IllegalArgumentException("Unknown permission: " + name);
3291            }
3292
3293            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3294
3295            uid = pkg.applicationInfo.uid;
3296            sb = (SettingBase) pkg.mExtras;
3297            if (sb == null) {
3298                throw new IllegalArgumentException("Unknown package: " + packageName);
3299            }
3300
3301            final PermissionsState permissionsState = sb.getPermissionsState();
3302
3303            final int flags = permissionsState.getPermissionFlags(name, userId);
3304            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3305                throw new SecurityException("Cannot grant system fixed permission: "
3306                        + name + " for package: " + packageName);
3307            }
3308
3309            final int result = permissionsState.grantRuntimePermission(bp, userId);
3310            switch (result) {
3311                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3312                    return;
3313                }
3314
3315                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3316                    mHandler.post(new Runnable() {
3317                        @Override
3318                        public void run() {
3319                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3320                        }
3321                    });
3322                } break;
3323            }
3324
3325            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3326
3327            // Not critical if that is lost - app has to request again.
3328            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3329        }
3330
3331        if (READ_EXTERNAL_STORAGE.equals(name)
3332                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3333            final long token = Binder.clearCallingIdentity();
3334            try {
3335                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3336                storage.remountUid(uid);
3337            } finally {
3338                Binder.restoreCallingIdentity(token);
3339            }
3340        }
3341    }
3342
3343    @Override
3344    public void revokeRuntimePermission(String packageName, String name, int userId) {
3345        if (!sUserManager.exists(userId)) {
3346            Log.e(TAG, "No such user:" + userId);
3347            return;
3348        }
3349
3350        mContext.enforceCallingOrSelfPermission(
3351                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3352                "revokeRuntimePermission");
3353
3354        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3355                "revokeRuntimePermission");
3356
3357        final SettingBase sb;
3358
3359        synchronized (mPackages) {
3360            final PackageParser.Package pkg = mPackages.get(packageName);
3361            if (pkg == null) {
3362                throw new IllegalArgumentException("Unknown package: " + packageName);
3363            }
3364
3365            final BasePermission bp = mSettings.mPermissions.get(name);
3366            if (bp == null) {
3367                throw new IllegalArgumentException("Unknown permission: " + name);
3368            }
3369
3370            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3371
3372            sb = (SettingBase) pkg.mExtras;
3373            if (sb == null) {
3374                throw new IllegalArgumentException("Unknown package: " + packageName);
3375            }
3376
3377            final PermissionsState permissionsState = sb.getPermissionsState();
3378
3379            final int flags = permissionsState.getPermissionFlags(name, userId);
3380            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3381                throw new SecurityException("Cannot revoke system fixed permission: "
3382                        + name + " for package: " + packageName);
3383            }
3384
3385            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3386                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3387                return;
3388            }
3389
3390            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3391
3392            // Critical, after this call app should never have the permission.
3393            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3394        }
3395
3396        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3397    }
3398
3399    @Override
3400    public void resetRuntimePermissions() {
3401        mContext.enforceCallingOrSelfPermission(
3402                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3403                "revokeRuntimePermission");
3404
3405        int callingUid = Binder.getCallingUid();
3406        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3407            mContext.enforceCallingOrSelfPermission(
3408                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3409                    "resetRuntimePermissions");
3410        }
3411
3412        synchronized (mPackages) {
3413            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3414            for (int userId : UserManagerService.getInstance().getUserIds()) {
3415                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3416            }
3417        }
3418    }
3419
3420    @Override
3421    public int getPermissionFlags(String name, String packageName, int userId) {
3422        if (!sUserManager.exists(userId)) {
3423            return 0;
3424        }
3425
3426        mContext.enforceCallingOrSelfPermission(
3427                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3428                "getPermissionFlags");
3429
3430        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3431                "getPermissionFlags");
3432
3433        synchronized (mPackages) {
3434            final PackageParser.Package pkg = mPackages.get(packageName);
3435            if (pkg == null) {
3436                throw new IllegalArgumentException("Unknown package: " + packageName);
3437            }
3438
3439            final BasePermission bp = mSettings.mPermissions.get(name);
3440            if (bp == null) {
3441                throw new IllegalArgumentException("Unknown permission: " + name);
3442            }
3443
3444            SettingBase sb = (SettingBase) pkg.mExtras;
3445            if (sb == null) {
3446                throw new IllegalArgumentException("Unknown package: " + packageName);
3447            }
3448
3449            PermissionsState permissionsState = sb.getPermissionsState();
3450            return permissionsState.getPermissionFlags(name, userId);
3451        }
3452    }
3453
3454    @Override
3455    public void updatePermissionFlags(String name, String packageName, int flagMask,
3456            int flagValues, int userId) {
3457        if (!sUserManager.exists(userId)) {
3458            return;
3459        }
3460
3461        mContext.enforceCallingOrSelfPermission(
3462                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3463                "updatePermissionFlags");
3464
3465        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3466                "updatePermissionFlags");
3467
3468        // Only the system can change system fixed flags.
3469        if (getCallingUid() != Process.SYSTEM_UID) {
3470            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3471            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3472        }
3473
3474        synchronized (mPackages) {
3475            final PackageParser.Package pkg = mPackages.get(packageName);
3476            if (pkg == null) {
3477                throw new IllegalArgumentException("Unknown package: " + packageName);
3478            }
3479
3480            final BasePermission bp = mSettings.mPermissions.get(name);
3481            if (bp == null) {
3482                throw new IllegalArgumentException("Unknown permission: " + name);
3483            }
3484
3485            SettingBase sb = (SettingBase) pkg.mExtras;
3486            if (sb == null) {
3487                throw new IllegalArgumentException("Unknown package: " + packageName);
3488            }
3489
3490            PermissionsState permissionsState = sb.getPermissionsState();
3491
3492            // Only the package manager can change flags for system component permissions.
3493            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3494            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3495                return;
3496            }
3497
3498            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3499
3500            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3501                // Install and runtime permissions are stored in different places,
3502                // so figure out what permission changed and persist the change.
3503                if (permissionsState.getInstallPermissionState(name) != null) {
3504                    scheduleWriteSettingsLocked();
3505                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3506                        || hadState) {
3507                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3508                }
3509            }
3510        }
3511    }
3512
3513    /**
3514     * Update the permission flags for all packages and runtime permissions of a user in order
3515     * to allow device or profile owner to remove POLICY_FIXED.
3516     */
3517    @Override
3518    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3519        if (!sUserManager.exists(userId)) {
3520            return;
3521        }
3522
3523        mContext.enforceCallingOrSelfPermission(
3524                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3525                "updatePermissionFlagsForAllApps");
3526
3527        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3528                "updatePermissionFlagsForAllApps");
3529
3530        // Only the system can change system fixed flags.
3531        if (getCallingUid() != Process.SYSTEM_UID) {
3532            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3533            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3534        }
3535
3536        synchronized (mPackages) {
3537            boolean changed = false;
3538            final int packageCount = mPackages.size();
3539            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3540                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3541                SettingBase sb = (SettingBase) pkg.mExtras;
3542                if (sb == null) {
3543                    continue;
3544                }
3545                PermissionsState permissionsState = sb.getPermissionsState();
3546                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3547                        userId, flagMask, flagValues);
3548            }
3549            if (changed) {
3550                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3551            }
3552        }
3553    }
3554
3555    @Override
3556    public boolean shouldShowRequestPermissionRationale(String permissionName,
3557            String packageName, int userId) {
3558        if (UserHandle.getCallingUserId() != userId) {
3559            mContext.enforceCallingPermission(
3560                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3561                    "canShowRequestPermissionRationale for user " + userId);
3562        }
3563
3564        final int uid = getPackageUid(packageName, userId);
3565        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3566            return false;
3567        }
3568
3569        if (checkPermission(permissionName, packageName, userId)
3570                == PackageManager.PERMISSION_GRANTED) {
3571            return false;
3572        }
3573
3574        final int flags;
3575
3576        final long identity = Binder.clearCallingIdentity();
3577        try {
3578            flags = getPermissionFlags(permissionName,
3579                    packageName, userId);
3580        } finally {
3581            Binder.restoreCallingIdentity(identity);
3582        }
3583
3584        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3585                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3586                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3587
3588        if ((flags & fixedFlags) != 0) {
3589            return false;
3590        }
3591
3592        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3593    }
3594
3595    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3596        BasePermission bp = mSettings.mPermissions.get(permission);
3597        if (bp == null) {
3598            throw new SecurityException("Missing " + permission + " permission");
3599        }
3600
3601        SettingBase sb = (SettingBase) pkg.mExtras;
3602        PermissionsState permissionsState = sb.getPermissionsState();
3603
3604        if (permissionsState.grantInstallPermission(bp) !=
3605                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3606            scheduleWriteSettingsLocked();
3607        }
3608    }
3609
3610    @Override
3611    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3612        mContext.enforceCallingOrSelfPermission(
3613                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3614                "addOnPermissionsChangeListener");
3615
3616        synchronized (mPackages) {
3617            mOnPermissionChangeListeners.addListenerLocked(listener);
3618        }
3619    }
3620
3621    @Override
3622    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3623        synchronized (mPackages) {
3624            mOnPermissionChangeListeners.removeListenerLocked(listener);
3625        }
3626    }
3627
3628    @Override
3629    public boolean isProtectedBroadcast(String actionName) {
3630        synchronized (mPackages) {
3631            return mProtectedBroadcasts.contains(actionName);
3632        }
3633    }
3634
3635    @Override
3636    public int checkSignatures(String pkg1, String pkg2) {
3637        synchronized (mPackages) {
3638            final PackageParser.Package p1 = mPackages.get(pkg1);
3639            final PackageParser.Package p2 = mPackages.get(pkg2);
3640            if (p1 == null || p1.mExtras == null
3641                    || p2 == null || p2.mExtras == null) {
3642                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3643            }
3644            return compareSignatures(p1.mSignatures, p2.mSignatures);
3645        }
3646    }
3647
3648    @Override
3649    public int checkUidSignatures(int uid1, int uid2) {
3650        // Map to base uids.
3651        uid1 = UserHandle.getAppId(uid1);
3652        uid2 = UserHandle.getAppId(uid2);
3653        // reader
3654        synchronized (mPackages) {
3655            Signature[] s1;
3656            Signature[] s2;
3657            Object obj = mSettings.getUserIdLPr(uid1);
3658            if (obj != null) {
3659                if (obj instanceof SharedUserSetting) {
3660                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3661                } else if (obj instanceof PackageSetting) {
3662                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3663                } else {
3664                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3665                }
3666            } else {
3667                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3668            }
3669            obj = mSettings.getUserIdLPr(uid2);
3670            if (obj != null) {
3671                if (obj instanceof SharedUserSetting) {
3672                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3673                } else if (obj instanceof PackageSetting) {
3674                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3675                } else {
3676                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3677                }
3678            } else {
3679                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3680            }
3681            return compareSignatures(s1, s2);
3682        }
3683    }
3684
3685    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3686        final long identity = Binder.clearCallingIdentity();
3687        try {
3688            if (sb instanceof SharedUserSetting) {
3689                SharedUserSetting sus = (SharedUserSetting) sb;
3690                final int packageCount = sus.packages.size();
3691                for (int i = 0; i < packageCount; i++) {
3692                    PackageSetting susPs = sus.packages.valueAt(i);
3693                    if (userId == UserHandle.USER_ALL) {
3694                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3695                    } else {
3696                        final int uid = UserHandle.getUid(userId, susPs.appId);
3697                        killUid(uid, reason);
3698                    }
3699                }
3700            } else if (sb instanceof PackageSetting) {
3701                PackageSetting ps = (PackageSetting) sb;
3702                if (userId == UserHandle.USER_ALL) {
3703                    killApplication(ps.pkg.packageName, ps.appId, reason);
3704                } else {
3705                    final int uid = UserHandle.getUid(userId, ps.appId);
3706                    killUid(uid, reason);
3707                }
3708            }
3709        } finally {
3710            Binder.restoreCallingIdentity(identity);
3711        }
3712    }
3713
3714    private static void killUid(int uid, String reason) {
3715        IActivityManager am = ActivityManagerNative.getDefault();
3716        if (am != null) {
3717            try {
3718                am.killUid(uid, reason);
3719            } catch (RemoteException e) {
3720                /* ignore - same process */
3721            }
3722        }
3723    }
3724
3725    /**
3726     * Compares two sets of signatures. Returns:
3727     * <br />
3728     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3729     * <br />
3730     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3731     * <br />
3732     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3733     * <br />
3734     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3735     * <br />
3736     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3737     */
3738    static int compareSignatures(Signature[] s1, Signature[] s2) {
3739        if (s1 == null) {
3740            return s2 == null
3741                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3742                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3743        }
3744
3745        if (s2 == null) {
3746            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3747        }
3748
3749        if (s1.length != s2.length) {
3750            return PackageManager.SIGNATURE_NO_MATCH;
3751        }
3752
3753        // Since both signature sets are of size 1, we can compare without HashSets.
3754        if (s1.length == 1) {
3755            return s1[0].equals(s2[0]) ?
3756                    PackageManager.SIGNATURE_MATCH :
3757                    PackageManager.SIGNATURE_NO_MATCH;
3758        }
3759
3760        ArraySet<Signature> set1 = new ArraySet<Signature>();
3761        for (Signature sig : s1) {
3762            set1.add(sig);
3763        }
3764        ArraySet<Signature> set2 = new ArraySet<Signature>();
3765        for (Signature sig : s2) {
3766            set2.add(sig);
3767        }
3768        // Make sure s2 contains all signatures in s1.
3769        if (set1.equals(set2)) {
3770            return PackageManager.SIGNATURE_MATCH;
3771        }
3772        return PackageManager.SIGNATURE_NO_MATCH;
3773    }
3774
3775    /**
3776     * If the database version for this type of package (internal storage or
3777     * external storage) is less than the version where package signatures
3778     * were updated, return true.
3779     */
3780    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3781        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3782                DatabaseVersion.SIGNATURE_END_ENTITY))
3783                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3784                        DatabaseVersion.SIGNATURE_END_ENTITY));
3785    }
3786
3787    /**
3788     * Used for backward compatibility to make sure any packages with
3789     * certificate chains get upgraded to the new style. {@code existingSigs}
3790     * will be in the old format (since they were stored on disk from before the
3791     * system upgrade) and {@code scannedSigs} will be in the newer format.
3792     */
3793    private int compareSignaturesCompat(PackageSignatures existingSigs,
3794            PackageParser.Package scannedPkg) {
3795        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3796            return PackageManager.SIGNATURE_NO_MATCH;
3797        }
3798
3799        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3800        for (Signature sig : existingSigs.mSignatures) {
3801            existingSet.add(sig);
3802        }
3803        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3804        for (Signature sig : scannedPkg.mSignatures) {
3805            try {
3806                Signature[] chainSignatures = sig.getChainSignatures();
3807                for (Signature chainSig : chainSignatures) {
3808                    scannedCompatSet.add(chainSig);
3809                }
3810            } catch (CertificateEncodingException e) {
3811                scannedCompatSet.add(sig);
3812            }
3813        }
3814        /*
3815         * Make sure the expanded scanned set contains all signatures in the
3816         * existing one.
3817         */
3818        if (scannedCompatSet.equals(existingSet)) {
3819            // Migrate the old signatures to the new scheme.
3820            existingSigs.assignSignatures(scannedPkg.mSignatures);
3821            // The new KeySets will be re-added later in the scanning process.
3822            synchronized (mPackages) {
3823                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3824            }
3825            return PackageManager.SIGNATURE_MATCH;
3826        }
3827        return PackageManager.SIGNATURE_NO_MATCH;
3828    }
3829
3830    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3831        if (isExternal(scannedPkg)) {
3832            return mSettings.isExternalDatabaseVersionOlderThan(
3833                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3834        } else {
3835            return mSettings.isInternalDatabaseVersionOlderThan(
3836                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3837        }
3838    }
3839
3840    private int compareSignaturesRecover(PackageSignatures existingSigs,
3841            PackageParser.Package scannedPkg) {
3842        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3843            return PackageManager.SIGNATURE_NO_MATCH;
3844        }
3845
3846        String msg = null;
3847        try {
3848            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3849                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3850                        + scannedPkg.packageName);
3851                return PackageManager.SIGNATURE_MATCH;
3852            }
3853        } catch (CertificateException e) {
3854            msg = e.getMessage();
3855        }
3856
3857        logCriticalInfo(Log.INFO,
3858                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3859        return PackageManager.SIGNATURE_NO_MATCH;
3860    }
3861
3862    @Override
3863    public String[] getPackagesForUid(int uid) {
3864        uid = UserHandle.getAppId(uid);
3865        // reader
3866        synchronized (mPackages) {
3867            Object obj = mSettings.getUserIdLPr(uid);
3868            if (obj instanceof SharedUserSetting) {
3869                final SharedUserSetting sus = (SharedUserSetting) obj;
3870                final int N = sus.packages.size();
3871                final String[] res = new String[N];
3872                final Iterator<PackageSetting> it = sus.packages.iterator();
3873                int i = 0;
3874                while (it.hasNext()) {
3875                    res[i++] = it.next().name;
3876                }
3877                return res;
3878            } else if (obj instanceof PackageSetting) {
3879                final PackageSetting ps = (PackageSetting) obj;
3880                return new String[] { ps.name };
3881            }
3882        }
3883        return null;
3884    }
3885
3886    @Override
3887    public String getNameForUid(int uid) {
3888        // reader
3889        synchronized (mPackages) {
3890            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3891            if (obj instanceof SharedUserSetting) {
3892                final SharedUserSetting sus = (SharedUserSetting) obj;
3893                return sus.name + ":" + sus.userId;
3894            } else if (obj instanceof PackageSetting) {
3895                final PackageSetting ps = (PackageSetting) obj;
3896                return ps.name;
3897            }
3898        }
3899        return null;
3900    }
3901
3902    @Override
3903    public int getUidForSharedUser(String sharedUserName) {
3904        if(sharedUserName == null) {
3905            return -1;
3906        }
3907        // reader
3908        synchronized (mPackages) {
3909            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3910            if (suid == null) {
3911                return -1;
3912            }
3913            return suid.userId;
3914        }
3915    }
3916
3917    @Override
3918    public int getFlagsForUid(int uid) {
3919        synchronized (mPackages) {
3920            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3921            if (obj instanceof SharedUserSetting) {
3922                final SharedUserSetting sus = (SharedUserSetting) obj;
3923                return sus.pkgFlags;
3924            } else if (obj instanceof PackageSetting) {
3925                final PackageSetting ps = (PackageSetting) obj;
3926                return ps.pkgFlags;
3927            }
3928        }
3929        return 0;
3930    }
3931
3932    @Override
3933    public int getPrivateFlagsForUid(int uid) {
3934        synchronized (mPackages) {
3935            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3936            if (obj instanceof SharedUserSetting) {
3937                final SharedUserSetting sus = (SharedUserSetting) obj;
3938                return sus.pkgPrivateFlags;
3939            } else if (obj instanceof PackageSetting) {
3940                final PackageSetting ps = (PackageSetting) obj;
3941                return ps.pkgPrivateFlags;
3942            }
3943        }
3944        return 0;
3945    }
3946
3947    @Override
3948    public boolean isUidPrivileged(int uid) {
3949        uid = UserHandle.getAppId(uid);
3950        // reader
3951        synchronized (mPackages) {
3952            Object obj = mSettings.getUserIdLPr(uid);
3953            if (obj instanceof SharedUserSetting) {
3954                final SharedUserSetting sus = (SharedUserSetting) obj;
3955                final Iterator<PackageSetting> it = sus.packages.iterator();
3956                while (it.hasNext()) {
3957                    if (it.next().isPrivileged()) {
3958                        return true;
3959                    }
3960                }
3961            } else if (obj instanceof PackageSetting) {
3962                final PackageSetting ps = (PackageSetting) obj;
3963                return ps.isPrivileged();
3964            }
3965        }
3966        return false;
3967    }
3968
3969    @Override
3970    public String[] getAppOpPermissionPackages(String permissionName) {
3971        synchronized (mPackages) {
3972            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3973            if (pkgs == null) {
3974                return null;
3975            }
3976            return pkgs.toArray(new String[pkgs.size()]);
3977        }
3978    }
3979
3980    @Override
3981    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3982            int flags, int userId) {
3983        if (!sUserManager.exists(userId)) return null;
3984        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3985        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3986        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3987    }
3988
3989    @Override
3990    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3991            IntentFilter filter, int match, ComponentName activity) {
3992        final int userId = UserHandle.getCallingUserId();
3993        if (DEBUG_PREFERRED) {
3994            Log.v(TAG, "setLastChosenActivity intent=" + intent
3995                + " resolvedType=" + resolvedType
3996                + " flags=" + flags
3997                + " filter=" + filter
3998                + " match=" + match
3999                + " activity=" + activity);
4000            filter.dump(new PrintStreamPrinter(System.out), "    ");
4001        }
4002        intent.setComponent(null);
4003        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4004        // Find any earlier preferred or last chosen entries and nuke them
4005        findPreferredActivity(intent, resolvedType,
4006                flags, query, 0, false, true, false, userId);
4007        // Add the new activity as the last chosen for this filter
4008        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4009                "Setting last chosen");
4010    }
4011
4012    @Override
4013    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4014        final int userId = UserHandle.getCallingUserId();
4015        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4016        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4017        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4018                false, false, false, userId);
4019    }
4020
4021    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4022            int flags, List<ResolveInfo> query, int userId) {
4023        if (query != null) {
4024            final int N = query.size();
4025            if (N == 1) {
4026                return query.get(0);
4027            } else if (N > 1) {
4028                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4029                // If there is more than one activity with the same priority,
4030                // then let the user decide between them.
4031                ResolveInfo r0 = query.get(0);
4032                ResolveInfo r1 = query.get(1);
4033                if (DEBUG_INTENT_MATCHING || debug) {
4034                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4035                            + r1.activityInfo.name + "=" + r1.priority);
4036                }
4037                // If the first activity has a higher priority, or a different
4038                // default, then it is always desireable to pick it.
4039                if (r0.priority != r1.priority
4040                        || r0.preferredOrder != r1.preferredOrder
4041                        || r0.isDefault != r1.isDefault) {
4042                    return query.get(0);
4043                }
4044                // If we have saved a preference for a preferred activity for
4045                // this Intent, use that.
4046                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4047                        flags, query, r0.priority, true, false, debug, userId);
4048                if (ri != null) {
4049                    return ri;
4050                }
4051                if (userId != 0) {
4052                    ri = new ResolveInfo(mResolveInfo);
4053                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4054                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4055                            ri.activityInfo.applicationInfo);
4056                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4057                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4058                    return ri;
4059                }
4060                return mResolveInfo;
4061            }
4062        }
4063        return null;
4064    }
4065
4066    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4067            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4068        final int N = query.size();
4069        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4070                .get(userId);
4071        // Get the list of persistent preferred activities that handle the intent
4072        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4073        List<PersistentPreferredActivity> pprefs = ppir != null
4074                ? ppir.queryIntent(intent, resolvedType,
4075                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4076                : null;
4077        if (pprefs != null && pprefs.size() > 0) {
4078            final int M = pprefs.size();
4079            for (int i=0; i<M; i++) {
4080                final PersistentPreferredActivity ppa = pprefs.get(i);
4081                if (DEBUG_PREFERRED || debug) {
4082                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4083                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4084                            + "\n  component=" + ppa.mComponent);
4085                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4086                }
4087                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4088                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4089                if (DEBUG_PREFERRED || debug) {
4090                    Slog.v(TAG, "Found persistent preferred activity:");
4091                    if (ai != null) {
4092                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4093                    } else {
4094                        Slog.v(TAG, "  null");
4095                    }
4096                }
4097                if (ai == null) {
4098                    // This previously registered persistent preferred activity
4099                    // component is no longer known. Ignore it and do NOT remove it.
4100                    continue;
4101                }
4102                for (int j=0; j<N; j++) {
4103                    final ResolveInfo ri = query.get(j);
4104                    if (!ri.activityInfo.applicationInfo.packageName
4105                            .equals(ai.applicationInfo.packageName)) {
4106                        continue;
4107                    }
4108                    if (!ri.activityInfo.name.equals(ai.name)) {
4109                        continue;
4110                    }
4111                    //  Found a persistent preference that can handle the intent.
4112                    if (DEBUG_PREFERRED || debug) {
4113                        Slog.v(TAG, "Returning persistent preferred activity: " +
4114                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4115                    }
4116                    return ri;
4117                }
4118            }
4119        }
4120        return null;
4121    }
4122
4123    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4124            List<ResolveInfo> query, int priority, boolean always,
4125            boolean removeMatches, boolean debug, int userId) {
4126        if (!sUserManager.exists(userId)) return null;
4127        // writer
4128        synchronized (mPackages) {
4129            if (intent.getSelector() != null) {
4130                intent = intent.getSelector();
4131            }
4132            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4133
4134            // Try to find a matching persistent preferred activity.
4135            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4136                    debug, userId);
4137
4138            // If a persistent preferred activity matched, use it.
4139            if (pri != null) {
4140                return pri;
4141            }
4142
4143            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4144            // Get the list of preferred activities that handle the intent
4145            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4146            List<PreferredActivity> prefs = pir != null
4147                    ? pir.queryIntent(intent, resolvedType,
4148                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4149                    : null;
4150            if (prefs != null && prefs.size() > 0) {
4151                boolean changed = false;
4152                try {
4153                    // First figure out how good the original match set is.
4154                    // We will only allow preferred activities that came
4155                    // from the same match quality.
4156                    int match = 0;
4157
4158                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4159
4160                    final int N = query.size();
4161                    for (int j=0; j<N; j++) {
4162                        final ResolveInfo ri = query.get(j);
4163                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4164                                + ": 0x" + Integer.toHexString(match));
4165                        if (ri.match > match) {
4166                            match = ri.match;
4167                        }
4168                    }
4169
4170                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4171                            + Integer.toHexString(match));
4172
4173                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4174                    final int M = prefs.size();
4175                    for (int i=0; i<M; i++) {
4176                        final PreferredActivity pa = prefs.get(i);
4177                        if (DEBUG_PREFERRED || debug) {
4178                            Slog.v(TAG, "Checking PreferredActivity ds="
4179                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4180                                    + "\n  component=" + pa.mPref.mComponent);
4181                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4182                        }
4183                        if (pa.mPref.mMatch != match) {
4184                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4185                                    + Integer.toHexString(pa.mPref.mMatch));
4186                            continue;
4187                        }
4188                        // If it's not an "always" type preferred activity and that's what we're
4189                        // looking for, skip it.
4190                        if (always && !pa.mPref.mAlways) {
4191                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4192                            continue;
4193                        }
4194                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4195                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4196                        if (DEBUG_PREFERRED || debug) {
4197                            Slog.v(TAG, "Found preferred activity:");
4198                            if (ai != null) {
4199                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4200                            } else {
4201                                Slog.v(TAG, "  null");
4202                            }
4203                        }
4204                        if (ai == null) {
4205                            // This previously registered preferred activity
4206                            // component is no longer known.  Most likely an update
4207                            // to the app was installed and in the new version this
4208                            // component no longer exists.  Clean it up by removing
4209                            // it from the preferred activities list, and skip it.
4210                            Slog.w(TAG, "Removing dangling preferred activity: "
4211                                    + pa.mPref.mComponent);
4212                            pir.removeFilter(pa);
4213                            changed = true;
4214                            continue;
4215                        }
4216                        for (int j=0; j<N; j++) {
4217                            final ResolveInfo ri = query.get(j);
4218                            if (!ri.activityInfo.applicationInfo.packageName
4219                                    .equals(ai.applicationInfo.packageName)) {
4220                                continue;
4221                            }
4222                            if (!ri.activityInfo.name.equals(ai.name)) {
4223                                continue;
4224                            }
4225
4226                            if (removeMatches) {
4227                                pir.removeFilter(pa);
4228                                changed = true;
4229                                if (DEBUG_PREFERRED) {
4230                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4231                                }
4232                                break;
4233                            }
4234
4235                            // Okay we found a previously set preferred or last chosen app.
4236                            // If the result set is different from when this
4237                            // was created, we need to clear it and re-ask the
4238                            // user their preference, if we're looking for an "always" type entry.
4239                            if (always && !pa.mPref.sameSet(query)) {
4240                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4241                                        + intent + " type " + resolvedType);
4242                                if (DEBUG_PREFERRED) {
4243                                    Slog.v(TAG, "Removing preferred activity since set changed "
4244                                            + pa.mPref.mComponent);
4245                                }
4246                                pir.removeFilter(pa);
4247                                // Re-add the filter as a "last chosen" entry (!always)
4248                                PreferredActivity lastChosen = new PreferredActivity(
4249                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4250                                pir.addFilter(lastChosen);
4251                                changed = true;
4252                                return null;
4253                            }
4254
4255                            // Yay! Either the set matched or we're looking for the last chosen
4256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4257                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4258                            return ri;
4259                        }
4260                    }
4261                } finally {
4262                    if (changed) {
4263                        if (DEBUG_PREFERRED) {
4264                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4265                        }
4266                        scheduleWritePackageRestrictionsLocked(userId);
4267                    }
4268                }
4269            }
4270        }
4271        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4272        return null;
4273    }
4274
4275    /*
4276     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4277     */
4278    @Override
4279    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4280            int targetUserId) {
4281        mContext.enforceCallingOrSelfPermission(
4282                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4283        List<CrossProfileIntentFilter> matches =
4284                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4285        if (matches != null) {
4286            int size = matches.size();
4287            for (int i = 0; i < size; i++) {
4288                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4289            }
4290        }
4291        if (hasWebURI(intent)) {
4292            // cross-profile app linking works only towards the parent.
4293            final UserInfo parent = getProfileParent(sourceUserId);
4294            synchronized(mPackages) {
4295                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4296                        parent.id) != null;
4297            }
4298        }
4299        return false;
4300    }
4301
4302    private UserInfo getProfileParent(int userId) {
4303        final long identity = Binder.clearCallingIdentity();
4304        try {
4305            return sUserManager.getProfileParent(userId);
4306        } finally {
4307            Binder.restoreCallingIdentity(identity);
4308        }
4309    }
4310
4311    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4312            String resolvedType, int userId) {
4313        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4314        if (resolver != null) {
4315            return resolver.queryIntent(intent, resolvedType, false, userId);
4316        }
4317        return null;
4318    }
4319
4320    @Override
4321    public List<ResolveInfo> queryIntentActivities(Intent intent,
4322            String resolvedType, int flags, int userId) {
4323        if (!sUserManager.exists(userId)) return Collections.emptyList();
4324        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4325        ComponentName comp = intent.getComponent();
4326        if (comp == null) {
4327            if (intent.getSelector() != null) {
4328                intent = intent.getSelector();
4329                comp = intent.getComponent();
4330            }
4331        }
4332
4333        if (comp != null) {
4334            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4335            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4336            if (ai != null) {
4337                final ResolveInfo ri = new ResolveInfo();
4338                ri.activityInfo = ai;
4339                list.add(ri);
4340            }
4341            return list;
4342        }
4343
4344        // reader
4345        synchronized (mPackages) {
4346            final String pkgName = intent.getPackage();
4347            if (pkgName == null) {
4348                List<CrossProfileIntentFilter> matchingFilters =
4349                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4350                // Check for results that need to skip the current profile.
4351                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4352                        resolvedType, flags, userId);
4353                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4354                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4355                    result.add(xpResolveInfo);
4356                    return filterIfNotPrimaryUser(result, userId);
4357                }
4358
4359                // Check for results in the current profile.
4360                List<ResolveInfo> result = mActivities.queryIntent(
4361                        intent, resolvedType, flags, userId);
4362
4363                // Check for cross profile results.
4364                xpResolveInfo = queryCrossProfileIntents(
4365                        matchingFilters, intent, resolvedType, flags, userId);
4366                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4367                    result.add(xpResolveInfo);
4368                    Collections.sort(result, mResolvePrioritySorter);
4369                }
4370                result = filterIfNotPrimaryUser(result, userId);
4371                if (hasWebURI(intent)) {
4372                    CrossProfileDomainInfo xpDomainInfo = null;
4373                    final UserInfo parent = getProfileParent(userId);
4374                    if (parent != null) {
4375                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4376                                flags, userId, parent.id);
4377                    }
4378                    if (xpDomainInfo != null) {
4379                        if (xpResolveInfo != null) {
4380                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4381                            // in the result.
4382                            result.remove(xpResolveInfo);
4383                        }
4384                        if (result.size() == 0) {
4385                            result.add(xpDomainInfo.resolveInfo);
4386                            return result;
4387                        }
4388                    } else if (result.size() <= 1) {
4389                        return result;
4390                    }
4391                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4392                            xpDomainInfo);
4393                    Collections.sort(result, mResolvePrioritySorter);
4394                }
4395                return result;
4396            }
4397            final PackageParser.Package pkg = mPackages.get(pkgName);
4398            if (pkg != null) {
4399                return filterIfNotPrimaryUser(
4400                        mActivities.queryIntentForPackage(
4401                                intent, resolvedType, flags, pkg.activities, userId),
4402                        userId);
4403            }
4404            return new ArrayList<ResolveInfo>();
4405        }
4406    }
4407
4408    private static class CrossProfileDomainInfo {
4409        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4410        ResolveInfo resolveInfo;
4411        /* Best domain verification status of the activities found in the other profile */
4412        int bestDomainVerificationStatus;
4413    }
4414
4415    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4416            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4417        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4418                sourceUserId)) {
4419            return null;
4420        }
4421        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4422                resolvedType, flags, parentUserId);
4423
4424        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4425            return null;
4426        }
4427        CrossProfileDomainInfo result = null;
4428        int size = resultTargetUser.size();
4429        for (int i = 0; i < size; i++) {
4430            ResolveInfo riTargetUser = resultTargetUser.get(i);
4431            // Intent filter verification is only for filters that specify a host. So don't return
4432            // those that handle all web uris.
4433            if (riTargetUser.handleAllWebDataURI) {
4434                continue;
4435            }
4436            String packageName = riTargetUser.activityInfo.packageName;
4437            PackageSetting ps = mSettings.mPackages.get(packageName);
4438            if (ps == null) {
4439                continue;
4440            }
4441            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4442            if (result == null) {
4443                result = new CrossProfileDomainInfo();
4444                result.resolveInfo =
4445                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4446                result.bestDomainVerificationStatus = status;
4447            } else {
4448                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4449                        result.bestDomainVerificationStatus);
4450            }
4451        }
4452        return result;
4453    }
4454
4455    /**
4456     * Verification statuses are ordered from the worse to the best, except for
4457     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4458     */
4459    private int bestDomainVerificationStatus(int status1, int status2) {
4460        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4461            return status2;
4462        }
4463        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4464            return status1;
4465        }
4466        return (int) MathUtils.max(status1, status2);
4467    }
4468
4469    private boolean isUserEnabled(int userId) {
4470        long callingId = Binder.clearCallingIdentity();
4471        try {
4472            UserInfo userInfo = sUserManager.getUserInfo(userId);
4473            return userInfo != null && userInfo.isEnabled();
4474        } finally {
4475            Binder.restoreCallingIdentity(callingId);
4476        }
4477    }
4478
4479    /**
4480     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4481     *
4482     * @return filtered list
4483     */
4484    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4485        if (userId == UserHandle.USER_OWNER) {
4486            return resolveInfos;
4487        }
4488        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4489            ResolveInfo info = resolveInfos.get(i);
4490            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4491                resolveInfos.remove(i);
4492            }
4493        }
4494        return resolveInfos;
4495    }
4496
4497    private static boolean hasWebURI(Intent intent) {
4498        if (intent.getData() == null) {
4499            return false;
4500        }
4501        final String scheme = intent.getScheme();
4502        if (TextUtils.isEmpty(scheme)) {
4503            return false;
4504        }
4505        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4506    }
4507
4508    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4509            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4510        if (DEBUG_PREFERRED) {
4511            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4512                    candidates.size());
4513        }
4514
4515        final int userId = UserHandle.getCallingUserId();
4516        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4517        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4518        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4519        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4520        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4521
4522        synchronized (mPackages) {
4523            final int count = candidates.size();
4524            // First, try to use the domain preferred app. Partition the candidates into four lists:
4525            // one for the final results, one for the "do not use ever", one for "undefined status"
4526            // and finally one for "Browser App type".
4527            for (int n=0; n<count; n++) {
4528                ResolveInfo info = candidates.get(n);
4529                String packageName = info.activityInfo.packageName;
4530                PackageSetting ps = mSettings.mPackages.get(packageName);
4531                if (ps != null) {
4532                    // Add to the special match all list (Browser use case)
4533                    if (info.handleAllWebDataURI) {
4534                        matchAllList.add(info);
4535                        continue;
4536                    }
4537                    // Try to get the status from User settings first
4538                    int status = getDomainVerificationStatusLPr(ps, userId);
4539                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4540                        alwaysList.add(info);
4541                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4542                        neverList.add(info);
4543                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4544                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4545                        undefinedList.add(info);
4546                    }
4547                }
4548            }
4549            // First try to add the "always" resolution for the current user if there is any
4550            if (alwaysList.size() > 0) {
4551                result.addAll(alwaysList);
4552            // if there is an "always" for the parent user, add it.
4553            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4554                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4555                result.add(xpDomainInfo.resolveInfo);
4556            } else {
4557                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4558                result.addAll(undefinedList);
4559                if (xpDomainInfo != null && (
4560                        xpDomainInfo.bestDomainVerificationStatus
4561                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4562                        || xpDomainInfo.bestDomainVerificationStatus
4563                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4564                    result.add(xpDomainInfo.resolveInfo);
4565                }
4566                // Also add Browsers (all of them or only the default one)
4567                if ((flags & MATCH_ALL) != 0) {
4568                    result.addAll(matchAllList);
4569                } else {
4570                    // Try to add the Default Browser if we can
4571                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4572                            UserHandle.myUserId());
4573                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4574                        boolean defaultBrowserFound = false;
4575                        final int browserCount = matchAllList.size();
4576                        for (int n=0; n<browserCount; n++) {
4577                            ResolveInfo browser = matchAllList.get(n);
4578                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4579                                result.add(browser);
4580                                defaultBrowserFound = true;
4581                                break;
4582                            }
4583                        }
4584                        if (!defaultBrowserFound) {
4585                            result.addAll(matchAllList);
4586                        }
4587                    } else {
4588                        result.addAll(matchAllList);
4589                    }
4590                }
4591
4592                // If there is nothing selected, add all candidates and remove the ones that the User
4593                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4594                if (result.size() == 0) {
4595                    result.addAll(candidates);
4596                    result.removeAll(neverList);
4597                }
4598            }
4599        }
4600        if (DEBUG_PREFERRED) {
4601            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4602                    result.size());
4603        }
4604        return result;
4605    }
4606
4607    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4608        int status = ps.getDomainVerificationStatusForUser(userId);
4609        // if none available, get the master status
4610        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4611            if (ps.getIntentFilterVerificationInfo() != null) {
4612                status = ps.getIntentFilterVerificationInfo().getStatus();
4613            }
4614        }
4615        return status;
4616    }
4617
4618    private ResolveInfo querySkipCurrentProfileIntents(
4619            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4620            int flags, int sourceUserId) {
4621        if (matchingFilters != null) {
4622            int size = matchingFilters.size();
4623            for (int i = 0; i < size; i ++) {
4624                CrossProfileIntentFilter filter = matchingFilters.get(i);
4625                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4626                    // Checking if there are activities in the target user that can handle the
4627                    // intent.
4628                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4629                            flags, sourceUserId);
4630                    if (resolveInfo != null) {
4631                        return resolveInfo;
4632                    }
4633                }
4634            }
4635        }
4636        return null;
4637    }
4638
4639    // Return matching ResolveInfo if any for skip current profile intent filters.
4640    private ResolveInfo queryCrossProfileIntents(
4641            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4642            int flags, int sourceUserId) {
4643        if (matchingFilters != null) {
4644            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4645            // match the same intent. For performance reasons, it is better not to
4646            // run queryIntent twice for the same userId
4647            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4648            int size = matchingFilters.size();
4649            for (int i = 0; i < size; i++) {
4650                CrossProfileIntentFilter filter = matchingFilters.get(i);
4651                int targetUserId = filter.getTargetUserId();
4652                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4653                        && !alreadyTriedUserIds.get(targetUserId)) {
4654                    // Checking if there are activities in the target user that can handle the
4655                    // intent.
4656                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4657                            flags, sourceUserId);
4658                    if (resolveInfo != null) return resolveInfo;
4659                    alreadyTriedUserIds.put(targetUserId, true);
4660                }
4661            }
4662        }
4663        return null;
4664    }
4665
4666    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4667            String resolvedType, int flags, int sourceUserId) {
4668        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4669                resolvedType, flags, filter.getTargetUserId());
4670        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4671            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4672        }
4673        return null;
4674    }
4675
4676    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4677            int sourceUserId, int targetUserId) {
4678        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4679        String className;
4680        if (targetUserId == UserHandle.USER_OWNER) {
4681            className = FORWARD_INTENT_TO_USER_OWNER;
4682        } else {
4683            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4684        }
4685        ComponentName forwardingActivityComponentName = new ComponentName(
4686                mAndroidApplication.packageName, className);
4687        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4688                sourceUserId);
4689        if (targetUserId == UserHandle.USER_OWNER) {
4690            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4691            forwardingResolveInfo.noResourceId = true;
4692        }
4693        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4694        forwardingResolveInfo.priority = 0;
4695        forwardingResolveInfo.preferredOrder = 0;
4696        forwardingResolveInfo.match = 0;
4697        forwardingResolveInfo.isDefault = true;
4698        forwardingResolveInfo.filter = filter;
4699        forwardingResolveInfo.targetUserId = targetUserId;
4700        return forwardingResolveInfo;
4701    }
4702
4703    @Override
4704    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4705            Intent[] specifics, String[] specificTypes, Intent intent,
4706            String resolvedType, int flags, int userId) {
4707        if (!sUserManager.exists(userId)) return Collections.emptyList();
4708        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4709                false, "query intent activity options");
4710        final String resultsAction = intent.getAction();
4711
4712        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4713                | PackageManager.GET_RESOLVED_FILTER, userId);
4714
4715        if (DEBUG_INTENT_MATCHING) {
4716            Log.v(TAG, "Query " + intent + ": " + results);
4717        }
4718
4719        int specificsPos = 0;
4720        int N;
4721
4722        // todo: note that the algorithm used here is O(N^2).  This
4723        // isn't a problem in our current environment, but if we start running
4724        // into situations where we have more than 5 or 10 matches then this
4725        // should probably be changed to something smarter...
4726
4727        // First we go through and resolve each of the specific items
4728        // that were supplied, taking care of removing any corresponding
4729        // duplicate items in the generic resolve list.
4730        if (specifics != null) {
4731            for (int i=0; i<specifics.length; i++) {
4732                final Intent sintent = specifics[i];
4733                if (sintent == null) {
4734                    continue;
4735                }
4736
4737                if (DEBUG_INTENT_MATCHING) {
4738                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4739                }
4740
4741                String action = sintent.getAction();
4742                if (resultsAction != null && resultsAction.equals(action)) {
4743                    // If this action was explicitly requested, then don't
4744                    // remove things that have it.
4745                    action = null;
4746                }
4747
4748                ResolveInfo ri = null;
4749                ActivityInfo ai = null;
4750
4751                ComponentName comp = sintent.getComponent();
4752                if (comp == null) {
4753                    ri = resolveIntent(
4754                        sintent,
4755                        specificTypes != null ? specificTypes[i] : null,
4756                            flags, userId);
4757                    if (ri == null) {
4758                        continue;
4759                    }
4760                    if (ri == mResolveInfo) {
4761                        // ACK!  Must do something better with this.
4762                    }
4763                    ai = ri.activityInfo;
4764                    comp = new ComponentName(ai.applicationInfo.packageName,
4765                            ai.name);
4766                } else {
4767                    ai = getActivityInfo(comp, flags, userId);
4768                    if (ai == null) {
4769                        continue;
4770                    }
4771                }
4772
4773                // Look for any generic query activities that are duplicates
4774                // of this specific one, and remove them from the results.
4775                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4776                N = results.size();
4777                int j;
4778                for (j=specificsPos; j<N; j++) {
4779                    ResolveInfo sri = results.get(j);
4780                    if ((sri.activityInfo.name.equals(comp.getClassName())
4781                            && sri.activityInfo.applicationInfo.packageName.equals(
4782                                    comp.getPackageName()))
4783                        || (action != null && sri.filter.matchAction(action))) {
4784                        results.remove(j);
4785                        if (DEBUG_INTENT_MATCHING) Log.v(
4786                            TAG, "Removing duplicate item from " + j
4787                            + " due to specific " + specificsPos);
4788                        if (ri == null) {
4789                            ri = sri;
4790                        }
4791                        j--;
4792                        N--;
4793                    }
4794                }
4795
4796                // Add this specific item to its proper place.
4797                if (ri == null) {
4798                    ri = new ResolveInfo();
4799                    ri.activityInfo = ai;
4800                }
4801                results.add(specificsPos, ri);
4802                ri.specificIndex = i;
4803                specificsPos++;
4804            }
4805        }
4806
4807        // Now we go through the remaining generic results and remove any
4808        // duplicate actions that are found here.
4809        N = results.size();
4810        for (int i=specificsPos; i<N-1; i++) {
4811            final ResolveInfo rii = results.get(i);
4812            if (rii.filter == null) {
4813                continue;
4814            }
4815
4816            // Iterate over all of the actions of this result's intent
4817            // filter...  typically this should be just one.
4818            final Iterator<String> it = rii.filter.actionsIterator();
4819            if (it == null) {
4820                continue;
4821            }
4822            while (it.hasNext()) {
4823                final String action = it.next();
4824                if (resultsAction != null && resultsAction.equals(action)) {
4825                    // If this action was explicitly requested, then don't
4826                    // remove things that have it.
4827                    continue;
4828                }
4829                for (int j=i+1; j<N; j++) {
4830                    final ResolveInfo rij = results.get(j);
4831                    if (rij.filter != null && rij.filter.hasAction(action)) {
4832                        results.remove(j);
4833                        if (DEBUG_INTENT_MATCHING) Log.v(
4834                            TAG, "Removing duplicate item from " + j
4835                            + " due to action " + action + " at " + i);
4836                        j--;
4837                        N--;
4838                    }
4839                }
4840            }
4841
4842            // If the caller didn't request filter information, drop it now
4843            // so we don't have to marshall/unmarshall it.
4844            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4845                rii.filter = null;
4846            }
4847        }
4848
4849        // Filter out the caller activity if so requested.
4850        if (caller != null) {
4851            N = results.size();
4852            for (int i=0; i<N; i++) {
4853                ActivityInfo ainfo = results.get(i).activityInfo;
4854                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4855                        && caller.getClassName().equals(ainfo.name)) {
4856                    results.remove(i);
4857                    break;
4858                }
4859            }
4860        }
4861
4862        // If the caller didn't request filter information,
4863        // drop them now so we don't have to
4864        // marshall/unmarshall it.
4865        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4866            N = results.size();
4867            for (int i=0; i<N; i++) {
4868                results.get(i).filter = null;
4869            }
4870        }
4871
4872        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4873        return results;
4874    }
4875
4876    @Override
4877    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4878            int userId) {
4879        if (!sUserManager.exists(userId)) return Collections.emptyList();
4880        ComponentName comp = intent.getComponent();
4881        if (comp == null) {
4882            if (intent.getSelector() != null) {
4883                intent = intent.getSelector();
4884                comp = intent.getComponent();
4885            }
4886        }
4887        if (comp != null) {
4888            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4889            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4890            if (ai != null) {
4891                ResolveInfo ri = new ResolveInfo();
4892                ri.activityInfo = ai;
4893                list.add(ri);
4894            }
4895            return list;
4896        }
4897
4898        // reader
4899        synchronized (mPackages) {
4900            String pkgName = intent.getPackage();
4901            if (pkgName == null) {
4902                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4903            }
4904            final PackageParser.Package pkg = mPackages.get(pkgName);
4905            if (pkg != null) {
4906                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4907                        userId);
4908            }
4909            return null;
4910        }
4911    }
4912
4913    @Override
4914    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4915        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4916        if (!sUserManager.exists(userId)) return null;
4917        if (query != null) {
4918            if (query.size() >= 1) {
4919                // If there is more than one service with the same priority,
4920                // just arbitrarily pick the first one.
4921                return query.get(0);
4922            }
4923        }
4924        return null;
4925    }
4926
4927    @Override
4928    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4929            int userId) {
4930        if (!sUserManager.exists(userId)) return Collections.emptyList();
4931        ComponentName comp = intent.getComponent();
4932        if (comp == null) {
4933            if (intent.getSelector() != null) {
4934                intent = intent.getSelector();
4935                comp = intent.getComponent();
4936            }
4937        }
4938        if (comp != null) {
4939            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4940            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4941            if (si != null) {
4942                final ResolveInfo ri = new ResolveInfo();
4943                ri.serviceInfo = si;
4944                list.add(ri);
4945            }
4946            return list;
4947        }
4948
4949        // reader
4950        synchronized (mPackages) {
4951            String pkgName = intent.getPackage();
4952            if (pkgName == null) {
4953                return mServices.queryIntent(intent, resolvedType, flags, userId);
4954            }
4955            final PackageParser.Package pkg = mPackages.get(pkgName);
4956            if (pkg != null) {
4957                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4958                        userId);
4959            }
4960            return null;
4961        }
4962    }
4963
4964    @Override
4965    public List<ResolveInfo> queryIntentContentProviders(
4966            Intent intent, String resolvedType, int flags, int userId) {
4967        if (!sUserManager.exists(userId)) return Collections.emptyList();
4968        ComponentName comp = intent.getComponent();
4969        if (comp == null) {
4970            if (intent.getSelector() != null) {
4971                intent = intent.getSelector();
4972                comp = intent.getComponent();
4973            }
4974        }
4975        if (comp != null) {
4976            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4977            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4978            if (pi != null) {
4979                final ResolveInfo ri = new ResolveInfo();
4980                ri.providerInfo = pi;
4981                list.add(ri);
4982            }
4983            return list;
4984        }
4985
4986        // reader
4987        synchronized (mPackages) {
4988            String pkgName = intent.getPackage();
4989            if (pkgName == null) {
4990                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4991            }
4992            final PackageParser.Package pkg = mPackages.get(pkgName);
4993            if (pkg != null) {
4994                return mProviders.queryIntentForPackage(
4995                        intent, resolvedType, flags, pkg.providers, userId);
4996            }
4997            return null;
4998        }
4999    }
5000
5001    @Override
5002    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5003        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5004
5005        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5006
5007        // writer
5008        synchronized (mPackages) {
5009            ArrayList<PackageInfo> list;
5010            if (listUninstalled) {
5011                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5012                for (PackageSetting ps : mSettings.mPackages.values()) {
5013                    PackageInfo pi;
5014                    if (ps.pkg != null) {
5015                        pi = generatePackageInfo(ps.pkg, flags, userId);
5016                    } else {
5017                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5018                    }
5019                    if (pi != null) {
5020                        list.add(pi);
5021                    }
5022                }
5023            } else {
5024                list = new ArrayList<PackageInfo>(mPackages.size());
5025                for (PackageParser.Package p : mPackages.values()) {
5026                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5027                    if (pi != null) {
5028                        list.add(pi);
5029                    }
5030                }
5031            }
5032
5033            return new ParceledListSlice<PackageInfo>(list);
5034        }
5035    }
5036
5037    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5038            String[] permissions, boolean[] tmp, int flags, int userId) {
5039        int numMatch = 0;
5040        final PermissionsState permissionsState = ps.getPermissionsState();
5041        for (int i=0; i<permissions.length; i++) {
5042            final String permission = permissions[i];
5043            if (permissionsState.hasPermission(permission, userId)) {
5044                tmp[i] = true;
5045                numMatch++;
5046            } else {
5047                tmp[i] = false;
5048            }
5049        }
5050        if (numMatch == 0) {
5051            return;
5052        }
5053        PackageInfo pi;
5054        if (ps.pkg != null) {
5055            pi = generatePackageInfo(ps.pkg, flags, userId);
5056        } else {
5057            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5058        }
5059        // The above might return null in cases of uninstalled apps or install-state
5060        // skew across users/profiles.
5061        if (pi != null) {
5062            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5063                if (numMatch == permissions.length) {
5064                    pi.requestedPermissions = permissions;
5065                } else {
5066                    pi.requestedPermissions = new String[numMatch];
5067                    numMatch = 0;
5068                    for (int i=0; i<permissions.length; i++) {
5069                        if (tmp[i]) {
5070                            pi.requestedPermissions[numMatch] = permissions[i];
5071                            numMatch++;
5072                        }
5073                    }
5074                }
5075            }
5076            list.add(pi);
5077        }
5078    }
5079
5080    @Override
5081    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5082            String[] permissions, int flags, int userId) {
5083        if (!sUserManager.exists(userId)) return null;
5084        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5085
5086        // writer
5087        synchronized (mPackages) {
5088            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5089            boolean[] tmpBools = new boolean[permissions.length];
5090            if (listUninstalled) {
5091                for (PackageSetting ps : mSettings.mPackages.values()) {
5092                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5093                }
5094            } else {
5095                for (PackageParser.Package pkg : mPackages.values()) {
5096                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5097                    if (ps != null) {
5098                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5099                                userId);
5100                    }
5101                }
5102            }
5103
5104            return new ParceledListSlice<PackageInfo>(list);
5105        }
5106    }
5107
5108    @Override
5109    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5110        if (!sUserManager.exists(userId)) return null;
5111        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5112
5113        // writer
5114        synchronized (mPackages) {
5115            ArrayList<ApplicationInfo> list;
5116            if (listUninstalled) {
5117                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5118                for (PackageSetting ps : mSettings.mPackages.values()) {
5119                    ApplicationInfo ai;
5120                    if (ps.pkg != null) {
5121                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5122                                ps.readUserState(userId), userId);
5123                    } else {
5124                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5125                    }
5126                    if (ai != null) {
5127                        list.add(ai);
5128                    }
5129                }
5130            } else {
5131                list = new ArrayList<ApplicationInfo>(mPackages.size());
5132                for (PackageParser.Package p : mPackages.values()) {
5133                    if (p.mExtras != null) {
5134                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5135                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5136                        if (ai != null) {
5137                            list.add(ai);
5138                        }
5139                    }
5140                }
5141            }
5142
5143            return new ParceledListSlice<ApplicationInfo>(list);
5144        }
5145    }
5146
5147    public List<ApplicationInfo> getPersistentApplications(int flags) {
5148        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5149
5150        // reader
5151        synchronized (mPackages) {
5152            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5153            final int userId = UserHandle.getCallingUserId();
5154            while (i.hasNext()) {
5155                final PackageParser.Package p = i.next();
5156                if (p.applicationInfo != null
5157                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5158                        && (!mSafeMode || isSystemApp(p))) {
5159                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5160                    if (ps != null) {
5161                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5162                                ps.readUserState(userId), userId);
5163                        if (ai != null) {
5164                            finalList.add(ai);
5165                        }
5166                    }
5167                }
5168            }
5169        }
5170
5171        return finalList;
5172    }
5173
5174    @Override
5175    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5176        if (!sUserManager.exists(userId)) return null;
5177        // reader
5178        synchronized (mPackages) {
5179            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5180            PackageSetting ps = provider != null
5181                    ? mSettings.mPackages.get(provider.owner.packageName)
5182                    : null;
5183            return ps != null
5184                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5185                    && (!mSafeMode || (provider.info.applicationInfo.flags
5186                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5187                    ? PackageParser.generateProviderInfo(provider, flags,
5188                            ps.readUserState(userId), userId)
5189                    : null;
5190        }
5191    }
5192
5193    /**
5194     * @deprecated
5195     */
5196    @Deprecated
5197    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5198        // reader
5199        synchronized (mPackages) {
5200            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5201                    .entrySet().iterator();
5202            final int userId = UserHandle.getCallingUserId();
5203            while (i.hasNext()) {
5204                Map.Entry<String, PackageParser.Provider> entry = i.next();
5205                PackageParser.Provider p = entry.getValue();
5206                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5207
5208                if (ps != null && p.syncable
5209                        && (!mSafeMode || (p.info.applicationInfo.flags
5210                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5211                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5212                            ps.readUserState(userId), userId);
5213                    if (info != null) {
5214                        outNames.add(entry.getKey());
5215                        outInfo.add(info);
5216                    }
5217                }
5218            }
5219        }
5220    }
5221
5222    @Override
5223    public List<ProviderInfo> queryContentProviders(String processName,
5224            int uid, int flags) {
5225        ArrayList<ProviderInfo> finalList = null;
5226        // reader
5227        synchronized (mPackages) {
5228            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5229            final int userId = processName != null ?
5230                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5231            while (i.hasNext()) {
5232                final PackageParser.Provider p = i.next();
5233                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5234                if (ps != null && p.info.authority != null
5235                        && (processName == null
5236                                || (p.info.processName.equals(processName)
5237                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5238                        && mSettings.isEnabledLPr(p.info, flags, userId)
5239                        && (!mSafeMode
5240                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5241                    if (finalList == null) {
5242                        finalList = new ArrayList<ProviderInfo>(3);
5243                    }
5244                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5245                            ps.readUserState(userId), userId);
5246                    if (info != null) {
5247                        finalList.add(info);
5248                    }
5249                }
5250            }
5251        }
5252
5253        if (finalList != null) {
5254            Collections.sort(finalList, mProviderInitOrderSorter);
5255        }
5256
5257        return finalList;
5258    }
5259
5260    @Override
5261    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5262            int flags) {
5263        // reader
5264        synchronized (mPackages) {
5265            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5266            return PackageParser.generateInstrumentationInfo(i, flags);
5267        }
5268    }
5269
5270    @Override
5271    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5272            int flags) {
5273        ArrayList<InstrumentationInfo> finalList =
5274            new ArrayList<InstrumentationInfo>();
5275
5276        // reader
5277        synchronized (mPackages) {
5278            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5279            while (i.hasNext()) {
5280                final PackageParser.Instrumentation p = i.next();
5281                if (targetPackage == null
5282                        || targetPackage.equals(p.info.targetPackage)) {
5283                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5284                            flags);
5285                    if (ii != null) {
5286                        finalList.add(ii);
5287                    }
5288                }
5289            }
5290        }
5291
5292        return finalList;
5293    }
5294
5295    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5296        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5297        if (overlays == null) {
5298            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5299            return;
5300        }
5301        for (PackageParser.Package opkg : overlays.values()) {
5302            // Not much to do if idmap fails: we already logged the error
5303            // and we certainly don't want to abort installation of pkg simply
5304            // because an overlay didn't fit properly. For these reasons,
5305            // ignore the return value of createIdmapForPackagePairLI.
5306            createIdmapForPackagePairLI(pkg, opkg);
5307        }
5308    }
5309
5310    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5311            PackageParser.Package opkg) {
5312        if (!opkg.mTrustedOverlay) {
5313            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5314                    opkg.baseCodePath + ": overlay not trusted");
5315            return false;
5316        }
5317        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5318        if (overlaySet == null) {
5319            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5320                    opkg.baseCodePath + " but target package has no known overlays");
5321            return false;
5322        }
5323        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5324        // TODO: generate idmap for split APKs
5325        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5326            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5327                    + opkg.baseCodePath);
5328            return false;
5329        }
5330        PackageParser.Package[] overlayArray =
5331            overlaySet.values().toArray(new PackageParser.Package[0]);
5332        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5333            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5334                return p1.mOverlayPriority - p2.mOverlayPriority;
5335            }
5336        };
5337        Arrays.sort(overlayArray, cmp);
5338
5339        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5340        int i = 0;
5341        for (PackageParser.Package p : overlayArray) {
5342            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5343        }
5344        return true;
5345    }
5346
5347    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5348        final File[] files = dir.listFiles();
5349        if (ArrayUtils.isEmpty(files)) {
5350            Log.d(TAG, "No files in app dir " + dir);
5351            return;
5352        }
5353
5354        if (DEBUG_PACKAGE_SCANNING) {
5355            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5356                    + " flags=0x" + Integer.toHexString(parseFlags));
5357        }
5358
5359        for (File file : files) {
5360            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5361                    && !PackageInstallerService.isStageName(file.getName());
5362            if (!isPackage) {
5363                // Ignore entries which are not packages
5364                continue;
5365            }
5366            try {
5367                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5368                        scanFlags, currentTime, null);
5369            } catch (PackageManagerException e) {
5370                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5371
5372                // Delete invalid userdata apps
5373                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5374                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5375                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5376                    if (file.isDirectory()) {
5377                        mInstaller.rmPackageDir(file.getAbsolutePath());
5378                    } else {
5379                        file.delete();
5380                    }
5381                }
5382            }
5383        }
5384    }
5385
5386    private static File getSettingsProblemFile() {
5387        File dataDir = Environment.getDataDirectory();
5388        File systemDir = new File(dataDir, "system");
5389        File fname = new File(systemDir, "uiderrors.txt");
5390        return fname;
5391    }
5392
5393    static void reportSettingsProblem(int priority, String msg) {
5394        logCriticalInfo(priority, msg);
5395    }
5396
5397    static void logCriticalInfo(int priority, String msg) {
5398        Slog.println(priority, TAG, msg);
5399        EventLogTags.writePmCriticalInfo(msg);
5400        try {
5401            File fname = getSettingsProblemFile();
5402            FileOutputStream out = new FileOutputStream(fname, true);
5403            PrintWriter pw = new FastPrintWriter(out);
5404            SimpleDateFormat formatter = new SimpleDateFormat();
5405            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5406            pw.println(dateString + ": " + msg);
5407            pw.close();
5408            FileUtils.setPermissions(
5409                    fname.toString(),
5410                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5411                    -1, -1);
5412        } catch (java.io.IOException e) {
5413        }
5414    }
5415
5416    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5417            PackageParser.Package pkg, File srcFile, int parseFlags)
5418            throws PackageManagerException {
5419        if (ps != null
5420                && ps.codePath.equals(srcFile)
5421                && ps.timeStamp == srcFile.lastModified()
5422                && !isCompatSignatureUpdateNeeded(pkg)
5423                && !isRecoverSignatureUpdateNeeded(pkg)) {
5424            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5425            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5426            ArraySet<PublicKey> signingKs;
5427            synchronized (mPackages) {
5428                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5429            }
5430            if (ps.signatures.mSignatures != null
5431                    && ps.signatures.mSignatures.length != 0
5432                    && signingKs != null) {
5433                // Optimization: reuse the existing cached certificates
5434                // if the package appears to be unchanged.
5435                pkg.mSignatures = ps.signatures.mSignatures;
5436                pkg.mSigningKeys = signingKs;
5437                return;
5438            }
5439
5440            Slog.w(TAG, "PackageSetting for " + ps.name
5441                    + " is missing signatures.  Collecting certs again to recover them.");
5442        } else {
5443            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5444        }
5445
5446        try {
5447            pp.collectCertificates(pkg, parseFlags);
5448            pp.collectManifestDigest(pkg);
5449        } catch (PackageParserException e) {
5450            throw PackageManagerException.from(e);
5451        }
5452    }
5453
5454    /*
5455     *  Scan a package and return the newly parsed package.
5456     *  Returns null in case of errors and the error code is stored in mLastScanError
5457     */
5458    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5459            long currentTime, UserHandle user) throws PackageManagerException {
5460        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5461        parseFlags |= mDefParseFlags;
5462        PackageParser pp = new PackageParser();
5463        pp.setSeparateProcesses(mSeparateProcesses);
5464        pp.setOnlyCoreApps(mOnlyCore);
5465        pp.setDisplayMetrics(mMetrics);
5466
5467        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5468            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5469        }
5470
5471        final PackageParser.Package pkg;
5472        try {
5473            pkg = pp.parsePackage(scanFile, parseFlags);
5474        } catch (PackageParserException e) {
5475            throw PackageManagerException.from(e);
5476        }
5477
5478        PackageSetting ps = null;
5479        PackageSetting updatedPkg;
5480        // reader
5481        synchronized (mPackages) {
5482            // Look to see if we already know about this package.
5483            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5484            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5485                // This package has been renamed to its original name.  Let's
5486                // use that.
5487                ps = mSettings.peekPackageLPr(oldName);
5488            }
5489            // If there was no original package, see one for the real package name.
5490            if (ps == null) {
5491                ps = mSettings.peekPackageLPr(pkg.packageName);
5492            }
5493            // Check to see if this package could be hiding/updating a system
5494            // package.  Must look for it either under the original or real
5495            // package name depending on our state.
5496            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5497            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5498        }
5499        boolean updatedPkgBetter = false;
5500        // First check if this is a system package that may involve an update
5501        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5502            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5503            // it needs to drop FLAG_PRIVILEGED.
5504            if (locationIsPrivileged(scanFile)) {
5505                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5506            } else {
5507                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5508            }
5509
5510            if (ps != null && !ps.codePath.equals(scanFile)) {
5511                // The path has changed from what was last scanned...  check the
5512                // version of the new path against what we have stored to determine
5513                // what to do.
5514                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5515                if (pkg.mVersionCode <= ps.versionCode) {
5516                    // The system package has been updated and the code path does not match
5517                    // Ignore entry. Skip it.
5518                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5519                            + " ignored: updated version " + ps.versionCode
5520                            + " better than this " + pkg.mVersionCode);
5521                    if (!updatedPkg.codePath.equals(scanFile)) {
5522                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5523                                + ps.name + " changing from " + updatedPkg.codePathString
5524                                + " to " + scanFile);
5525                        updatedPkg.codePath = scanFile;
5526                        updatedPkg.codePathString = scanFile.toString();
5527                        updatedPkg.resourcePath = scanFile;
5528                        updatedPkg.resourcePathString = scanFile.toString();
5529                    }
5530                    updatedPkg.pkg = pkg;
5531                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5532                } else {
5533                    // The current app on the system partition is better than
5534                    // what we have updated to on the data partition; switch
5535                    // back to the system partition version.
5536                    // At this point, its safely assumed that package installation for
5537                    // apps in system partition will go through. If not there won't be a working
5538                    // version of the app
5539                    // writer
5540                    synchronized (mPackages) {
5541                        // Just remove the loaded entries from package lists.
5542                        mPackages.remove(ps.name);
5543                    }
5544
5545                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5546                            + " reverting from " + ps.codePathString
5547                            + ": new version " + pkg.mVersionCode
5548                            + " better than installed " + ps.versionCode);
5549
5550                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5551                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5552                    synchronized (mInstallLock) {
5553                        args.cleanUpResourcesLI();
5554                    }
5555                    synchronized (mPackages) {
5556                        mSettings.enableSystemPackageLPw(ps.name);
5557                    }
5558                    updatedPkgBetter = true;
5559                }
5560            }
5561        }
5562
5563        if (updatedPkg != null) {
5564            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5565            // initially
5566            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5567
5568            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5569            // flag set initially
5570            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5571                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5572            }
5573        }
5574
5575        // Verify certificates against what was last scanned
5576        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5577
5578        /*
5579         * A new system app appeared, but we already had a non-system one of the
5580         * same name installed earlier.
5581         */
5582        boolean shouldHideSystemApp = false;
5583        if (updatedPkg == null && ps != null
5584                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5585            /*
5586             * Check to make sure the signatures match first. If they don't,
5587             * wipe the installed application and its data.
5588             */
5589            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5590                    != PackageManager.SIGNATURE_MATCH) {
5591                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5592                        + " signatures don't match existing userdata copy; removing");
5593                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5594                ps = null;
5595            } else {
5596                /*
5597                 * If the newly-added system app is an older version than the
5598                 * already installed version, hide it. It will be scanned later
5599                 * and re-added like an update.
5600                 */
5601                if (pkg.mVersionCode <= ps.versionCode) {
5602                    shouldHideSystemApp = true;
5603                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5604                            + " but new version " + pkg.mVersionCode + " better than installed "
5605                            + ps.versionCode + "; hiding system");
5606                } else {
5607                    /*
5608                     * The newly found system app is a newer version that the
5609                     * one previously installed. Simply remove the
5610                     * already-installed application and replace it with our own
5611                     * while keeping the application data.
5612                     */
5613                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5614                            + " reverting from " + ps.codePathString + ": new version "
5615                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5616                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5617                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5618                    synchronized (mInstallLock) {
5619                        args.cleanUpResourcesLI();
5620                    }
5621                }
5622            }
5623        }
5624
5625        // The apk is forward locked (not public) if its code and resources
5626        // are kept in different files. (except for app in either system or
5627        // vendor path).
5628        // TODO grab this value from PackageSettings
5629        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5630            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5631                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5632            }
5633        }
5634
5635        // TODO: extend to support forward-locked splits
5636        String resourcePath = null;
5637        String baseResourcePath = null;
5638        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5639            if (ps != null && ps.resourcePathString != null) {
5640                resourcePath = ps.resourcePathString;
5641                baseResourcePath = ps.resourcePathString;
5642            } else {
5643                // Should not happen at all. Just log an error.
5644                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5645            }
5646        } else {
5647            resourcePath = pkg.codePath;
5648            baseResourcePath = pkg.baseCodePath;
5649        }
5650
5651        // Set application objects path explicitly.
5652        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5653        pkg.applicationInfo.setCodePath(pkg.codePath);
5654        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5655        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5656        pkg.applicationInfo.setResourcePath(resourcePath);
5657        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5658        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5659
5660        // Note that we invoke the following method only if we are about to unpack an application
5661        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5662                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5663
5664        /*
5665         * If the system app should be overridden by a previously installed
5666         * data, hide the system app now and let the /data/app scan pick it up
5667         * again.
5668         */
5669        if (shouldHideSystemApp) {
5670            synchronized (mPackages) {
5671                /*
5672                 * We have to grant systems permissions before we hide, because
5673                 * grantPermissions will assume the package update is trying to
5674                 * expand its permissions.
5675                 */
5676                grantPermissionsLPw(pkg, true, pkg.packageName);
5677                mSettings.disableSystemPackageLPw(pkg.packageName);
5678            }
5679        }
5680
5681        return scannedPkg;
5682    }
5683
5684    private static String fixProcessName(String defProcessName,
5685            String processName, int uid) {
5686        if (processName == null) {
5687            return defProcessName;
5688        }
5689        return processName;
5690    }
5691
5692    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5693            throws PackageManagerException {
5694        if (pkgSetting.signatures.mSignatures != null) {
5695            // Already existing package. Make sure signatures match
5696            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5697                    == PackageManager.SIGNATURE_MATCH;
5698            if (!match) {
5699                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5700                        == PackageManager.SIGNATURE_MATCH;
5701            }
5702            if (!match) {
5703                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5704                        == PackageManager.SIGNATURE_MATCH;
5705            }
5706            if (!match) {
5707                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5708                        + pkg.packageName + " signatures do not match the "
5709                        + "previously installed version; ignoring!");
5710            }
5711        }
5712
5713        // Check for shared user signatures
5714        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5715            // Already existing package. Make sure signatures match
5716            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5717                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5718            if (!match) {
5719                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5720                        == PackageManager.SIGNATURE_MATCH;
5721            }
5722            if (!match) {
5723                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5724                        == PackageManager.SIGNATURE_MATCH;
5725            }
5726            if (!match) {
5727                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5728                        "Package " + pkg.packageName
5729                        + " has no signatures that match those in shared user "
5730                        + pkgSetting.sharedUser.name + "; ignoring!");
5731            }
5732        }
5733    }
5734
5735    /**
5736     * Enforces that only the system UID or root's UID can call a method exposed
5737     * via Binder.
5738     *
5739     * @param message used as message if SecurityException is thrown
5740     * @throws SecurityException if the caller is not system or root
5741     */
5742    private static final void enforceSystemOrRoot(String message) {
5743        final int uid = Binder.getCallingUid();
5744        if (uid != Process.SYSTEM_UID && uid != 0) {
5745            throw new SecurityException(message);
5746        }
5747    }
5748
5749    @Override
5750    public void performBootDexOpt() {
5751        enforceSystemOrRoot("Only the system can request dexopt be performed");
5752
5753        // Before everything else, see whether we need to fstrim.
5754        try {
5755            IMountService ms = PackageHelper.getMountService();
5756            if (ms != null) {
5757                final boolean isUpgrade = isUpgrade();
5758                boolean doTrim = isUpgrade;
5759                if (doTrim) {
5760                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5761                } else {
5762                    final long interval = android.provider.Settings.Global.getLong(
5763                            mContext.getContentResolver(),
5764                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5765                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5766                    if (interval > 0) {
5767                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5768                        if (timeSinceLast > interval) {
5769                            doTrim = true;
5770                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5771                                    + "; running immediately");
5772                        }
5773                    }
5774                }
5775                if (doTrim) {
5776                    if (!isFirstBoot()) {
5777                        try {
5778                            ActivityManagerNative.getDefault().showBootMessage(
5779                                    mContext.getResources().getString(
5780                                            R.string.android_upgrading_fstrim), true);
5781                        } catch (RemoteException e) {
5782                        }
5783                    }
5784                    ms.runMaintenance();
5785                }
5786            } else {
5787                Slog.e(TAG, "Mount service unavailable!");
5788            }
5789        } catch (RemoteException e) {
5790            // Can't happen; MountService is local
5791        }
5792
5793        final ArraySet<PackageParser.Package> pkgs;
5794        synchronized (mPackages) {
5795            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5796        }
5797
5798        if (pkgs != null) {
5799            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5800            // in case the device runs out of space.
5801            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5802            // Give priority to core apps.
5803            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5804                PackageParser.Package pkg = it.next();
5805                if (pkg.coreApp) {
5806                    if (DEBUG_DEXOPT) {
5807                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5808                    }
5809                    sortedPkgs.add(pkg);
5810                    it.remove();
5811                }
5812            }
5813            // Give priority to system apps that listen for pre boot complete.
5814            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5815            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5816            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5817                PackageParser.Package pkg = it.next();
5818                if (pkgNames.contains(pkg.packageName)) {
5819                    if (DEBUG_DEXOPT) {
5820                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5821                    }
5822                    sortedPkgs.add(pkg);
5823                    it.remove();
5824                }
5825            }
5826            // Give priority to system apps.
5827            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5828                PackageParser.Package pkg = it.next();
5829                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5830                    if (DEBUG_DEXOPT) {
5831                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5832                    }
5833                    sortedPkgs.add(pkg);
5834                    it.remove();
5835                }
5836            }
5837            // Give priority to updated system apps.
5838            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5839                PackageParser.Package pkg = it.next();
5840                if (pkg.isUpdatedSystemApp()) {
5841                    if (DEBUG_DEXOPT) {
5842                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5843                    }
5844                    sortedPkgs.add(pkg);
5845                    it.remove();
5846                }
5847            }
5848            // Give priority to apps that listen for boot complete.
5849            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5850            pkgNames = getPackageNamesForIntent(intent);
5851            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5852                PackageParser.Package pkg = it.next();
5853                if (pkgNames.contains(pkg.packageName)) {
5854                    if (DEBUG_DEXOPT) {
5855                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5856                    }
5857                    sortedPkgs.add(pkg);
5858                    it.remove();
5859                }
5860            }
5861            // Filter out packages that aren't recently used.
5862            filterRecentlyUsedApps(pkgs);
5863            // Add all remaining apps.
5864            for (PackageParser.Package pkg : pkgs) {
5865                if (DEBUG_DEXOPT) {
5866                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5867                }
5868                sortedPkgs.add(pkg);
5869            }
5870
5871            // If we want to be lazy, filter everything that wasn't recently used.
5872            if (mLazyDexOpt) {
5873                filterRecentlyUsedApps(sortedPkgs);
5874            }
5875
5876            int i = 0;
5877            int total = sortedPkgs.size();
5878            File dataDir = Environment.getDataDirectory();
5879            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5880            if (lowThreshold == 0) {
5881                throw new IllegalStateException("Invalid low memory threshold");
5882            }
5883            for (PackageParser.Package pkg : sortedPkgs) {
5884                long usableSpace = dataDir.getUsableSpace();
5885                if (usableSpace < lowThreshold) {
5886                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5887                    break;
5888                }
5889                performBootDexOpt(pkg, ++i, total);
5890            }
5891        }
5892    }
5893
5894    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5895        // Filter out packages that aren't recently used.
5896        //
5897        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5898        // should do a full dexopt.
5899        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5900            int total = pkgs.size();
5901            int skipped = 0;
5902            long now = System.currentTimeMillis();
5903            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5904                PackageParser.Package pkg = i.next();
5905                long then = pkg.mLastPackageUsageTimeInMills;
5906                if (then + mDexOptLRUThresholdInMills < now) {
5907                    if (DEBUG_DEXOPT) {
5908                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5909                              ((then == 0) ? "never" : new Date(then)));
5910                    }
5911                    i.remove();
5912                    skipped++;
5913                }
5914            }
5915            if (DEBUG_DEXOPT) {
5916                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5917            }
5918        }
5919    }
5920
5921    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5922        List<ResolveInfo> ris = null;
5923        try {
5924            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5925                    intent, null, 0, UserHandle.USER_OWNER);
5926        } catch (RemoteException e) {
5927        }
5928        ArraySet<String> pkgNames = new ArraySet<String>();
5929        if (ris != null) {
5930            for (ResolveInfo ri : ris) {
5931                pkgNames.add(ri.activityInfo.packageName);
5932            }
5933        }
5934        return pkgNames;
5935    }
5936
5937    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5938        if (DEBUG_DEXOPT) {
5939            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5940        }
5941        if (!isFirstBoot()) {
5942            try {
5943                ActivityManagerNative.getDefault().showBootMessage(
5944                        mContext.getResources().getString(R.string.android_upgrading_apk,
5945                                curr, total), true);
5946            } catch (RemoteException e) {
5947            }
5948        }
5949        PackageParser.Package p = pkg;
5950        synchronized (mInstallLock) {
5951            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5952                    false /* force dex */, false /* defer */, true /* include dependencies */);
5953        }
5954    }
5955
5956    @Override
5957    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5958        return performDexOpt(packageName, instructionSet, false);
5959    }
5960
5961    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5962        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5963        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5964        if (!dexopt && !updateUsage) {
5965            // We aren't going to dexopt or update usage, so bail early.
5966            return false;
5967        }
5968        PackageParser.Package p;
5969        final String targetInstructionSet;
5970        synchronized (mPackages) {
5971            p = mPackages.get(packageName);
5972            if (p == null) {
5973                return false;
5974            }
5975            if (updateUsage) {
5976                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5977            }
5978            mPackageUsage.write(false);
5979            if (!dexopt) {
5980                // We aren't going to dexopt, so bail early.
5981                return false;
5982            }
5983
5984            targetInstructionSet = instructionSet != null ? instructionSet :
5985                    getPrimaryInstructionSet(p.applicationInfo);
5986            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5987                return false;
5988            }
5989        }
5990
5991        synchronized (mInstallLock) {
5992            final String[] instructionSets = new String[] { targetInstructionSet };
5993            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5994                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5995            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5996        }
5997    }
5998
5999    public ArraySet<String> getPackagesThatNeedDexOpt() {
6000        ArraySet<String> pkgs = null;
6001        synchronized (mPackages) {
6002            for (PackageParser.Package p : mPackages.values()) {
6003                if (DEBUG_DEXOPT) {
6004                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6005                }
6006                if (!p.mDexOptPerformed.isEmpty()) {
6007                    continue;
6008                }
6009                if (pkgs == null) {
6010                    pkgs = new ArraySet<String>();
6011                }
6012                pkgs.add(p.packageName);
6013            }
6014        }
6015        return pkgs;
6016    }
6017
6018    public void shutdown() {
6019        mPackageUsage.write(true);
6020    }
6021
6022    @Override
6023    public void forceDexOpt(String packageName) {
6024        enforceSystemOrRoot("forceDexOpt");
6025
6026        PackageParser.Package pkg;
6027        synchronized (mPackages) {
6028            pkg = mPackages.get(packageName);
6029            if (pkg == null) {
6030                throw new IllegalArgumentException("Missing package: " + packageName);
6031            }
6032        }
6033
6034        synchronized (mInstallLock) {
6035            final String[] instructionSets = new String[] {
6036                    getPrimaryInstructionSet(pkg.applicationInfo) };
6037            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6038                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6039            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6040                throw new IllegalStateException("Failed to dexopt: " + res);
6041            }
6042        }
6043    }
6044
6045    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6046        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6047            Slog.w(TAG, "Unable to update from " + oldPkg.name
6048                    + " to " + newPkg.packageName
6049                    + ": old package not in system partition");
6050            return false;
6051        } else if (mPackages.get(oldPkg.name) != null) {
6052            Slog.w(TAG, "Unable to update from " + oldPkg.name
6053                    + " to " + newPkg.packageName
6054                    + ": old package still exists");
6055            return false;
6056        }
6057        return true;
6058    }
6059
6060    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6061        int[] users = sUserManager.getUserIds();
6062        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6063        if (res < 0) {
6064            return res;
6065        }
6066        for (int user : users) {
6067            if (user != 0) {
6068                res = mInstaller.createUserData(volumeUuid, packageName,
6069                        UserHandle.getUid(user, uid), user, seinfo);
6070                if (res < 0) {
6071                    return res;
6072                }
6073            }
6074        }
6075        return res;
6076    }
6077
6078    private int removeDataDirsLI(String volumeUuid, String packageName) {
6079        int[] users = sUserManager.getUserIds();
6080        int res = 0;
6081        for (int user : users) {
6082            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6083            if (resInner < 0) {
6084                res = resInner;
6085            }
6086        }
6087
6088        return res;
6089    }
6090
6091    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6092        int[] users = sUserManager.getUserIds();
6093        int res = 0;
6094        for (int user : users) {
6095            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6096            if (resInner < 0) {
6097                res = resInner;
6098            }
6099        }
6100        return res;
6101    }
6102
6103    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6104            PackageParser.Package changingLib) {
6105        if (file.path != null) {
6106            usesLibraryFiles.add(file.path);
6107            return;
6108        }
6109        PackageParser.Package p = mPackages.get(file.apk);
6110        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6111            // If we are doing this while in the middle of updating a library apk,
6112            // then we need to make sure to use that new apk for determining the
6113            // dependencies here.  (We haven't yet finished committing the new apk
6114            // to the package manager state.)
6115            if (p == null || p.packageName.equals(changingLib.packageName)) {
6116                p = changingLib;
6117            }
6118        }
6119        if (p != null) {
6120            usesLibraryFiles.addAll(p.getAllCodePaths());
6121        }
6122    }
6123
6124    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6125            PackageParser.Package changingLib) throws PackageManagerException {
6126        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6127            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6128            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6129            for (int i=0; i<N; i++) {
6130                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6131                if (file == null) {
6132                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6133                            "Package " + pkg.packageName + " requires unavailable shared library "
6134                            + pkg.usesLibraries.get(i) + "; failing!");
6135                }
6136                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6137            }
6138            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6139            for (int i=0; i<N; i++) {
6140                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6141                if (file == null) {
6142                    Slog.w(TAG, "Package " + pkg.packageName
6143                            + " desires unavailable shared library "
6144                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6145                } else {
6146                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6147                }
6148            }
6149            N = usesLibraryFiles.size();
6150            if (N > 0) {
6151                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6152            } else {
6153                pkg.usesLibraryFiles = null;
6154            }
6155        }
6156    }
6157
6158    private static boolean hasString(List<String> list, List<String> which) {
6159        if (list == null) {
6160            return false;
6161        }
6162        for (int i=list.size()-1; i>=0; i--) {
6163            for (int j=which.size()-1; j>=0; j--) {
6164                if (which.get(j).equals(list.get(i))) {
6165                    return true;
6166                }
6167            }
6168        }
6169        return false;
6170    }
6171
6172    private void updateAllSharedLibrariesLPw() {
6173        for (PackageParser.Package pkg : mPackages.values()) {
6174            try {
6175                updateSharedLibrariesLPw(pkg, null);
6176            } catch (PackageManagerException e) {
6177                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6178            }
6179        }
6180    }
6181
6182    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6183            PackageParser.Package changingPkg) {
6184        ArrayList<PackageParser.Package> res = null;
6185        for (PackageParser.Package pkg : mPackages.values()) {
6186            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6187                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6188                if (res == null) {
6189                    res = new ArrayList<PackageParser.Package>();
6190                }
6191                res.add(pkg);
6192                try {
6193                    updateSharedLibrariesLPw(pkg, changingPkg);
6194                } catch (PackageManagerException e) {
6195                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6196                }
6197            }
6198        }
6199        return res;
6200    }
6201
6202    /**
6203     * Derive the value of the {@code cpuAbiOverride} based on the provided
6204     * value and an optional stored value from the package settings.
6205     */
6206    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6207        String cpuAbiOverride = null;
6208
6209        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6210            cpuAbiOverride = null;
6211        } else if (abiOverride != null) {
6212            cpuAbiOverride = abiOverride;
6213        } else if (settings != null) {
6214            cpuAbiOverride = settings.cpuAbiOverrideString;
6215        }
6216
6217        return cpuAbiOverride;
6218    }
6219
6220    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6221            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6222        boolean success = false;
6223        try {
6224            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6225                    currentTime, user);
6226            success = true;
6227            return res;
6228        } finally {
6229            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6230                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6231            }
6232        }
6233    }
6234
6235    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6236            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6237        final File scanFile = new File(pkg.codePath);
6238        if (pkg.applicationInfo.getCodePath() == null ||
6239                pkg.applicationInfo.getResourcePath() == null) {
6240            // Bail out. The resource and code paths haven't been set.
6241            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6242                    "Code and resource paths haven't been set correctly");
6243        }
6244
6245        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6246            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6247        } else {
6248            // Only allow system apps to be flagged as core apps.
6249            pkg.coreApp = false;
6250        }
6251
6252        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6253            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6254        }
6255
6256        if (mCustomResolverComponentName != null &&
6257                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6258            setUpCustomResolverActivity(pkg);
6259        }
6260
6261        if (pkg.packageName.equals("android")) {
6262            synchronized (mPackages) {
6263                if (mAndroidApplication != null) {
6264                    Slog.w(TAG, "*************************************************");
6265                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6266                    Slog.w(TAG, " file=" + scanFile);
6267                    Slog.w(TAG, "*************************************************");
6268                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6269                            "Core android package being redefined.  Skipping.");
6270                }
6271
6272                // Set up information for our fall-back user intent resolution activity.
6273                mPlatformPackage = pkg;
6274                pkg.mVersionCode = mSdkVersion;
6275                mAndroidApplication = pkg.applicationInfo;
6276
6277                if (!mResolverReplaced) {
6278                    mResolveActivity.applicationInfo = mAndroidApplication;
6279                    mResolveActivity.name = ResolverActivity.class.getName();
6280                    mResolveActivity.packageName = mAndroidApplication.packageName;
6281                    mResolveActivity.processName = "system:ui";
6282                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6283                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6284                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6285                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6286                    mResolveActivity.exported = true;
6287                    mResolveActivity.enabled = true;
6288                    mResolveInfo.activityInfo = mResolveActivity;
6289                    mResolveInfo.priority = 0;
6290                    mResolveInfo.preferredOrder = 0;
6291                    mResolveInfo.match = 0;
6292                    mResolveComponentName = new ComponentName(
6293                            mAndroidApplication.packageName, mResolveActivity.name);
6294                }
6295            }
6296        }
6297
6298        if (DEBUG_PACKAGE_SCANNING) {
6299            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6300                Log.d(TAG, "Scanning package " + pkg.packageName);
6301        }
6302
6303        if (mPackages.containsKey(pkg.packageName)
6304                || mSharedLibraries.containsKey(pkg.packageName)) {
6305            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6306                    "Application package " + pkg.packageName
6307                    + " already installed.  Skipping duplicate.");
6308        }
6309
6310        // If we're only installing presumed-existing packages, require that the
6311        // scanned APK is both already known and at the path previously established
6312        // for it.  Previously unknown packages we pick up normally, but if we have an
6313        // a priori expectation about this package's install presence, enforce it.
6314        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6315            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6316            if (known != null) {
6317                if (DEBUG_PACKAGE_SCANNING) {
6318                    Log.d(TAG, "Examining " + pkg.codePath
6319                            + " and requiring known paths " + known.codePathString
6320                            + " & " + known.resourcePathString);
6321                }
6322                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6323                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6324                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6325                            "Application package " + pkg.packageName
6326                            + " found at " + pkg.applicationInfo.getCodePath()
6327                            + " but expected at " + known.codePathString + "; ignoring.");
6328                }
6329            }
6330        }
6331
6332        // Initialize package source and resource directories
6333        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6334        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6335
6336        SharedUserSetting suid = null;
6337        PackageSetting pkgSetting = null;
6338
6339        if (!isSystemApp(pkg)) {
6340            // Only system apps can use these features.
6341            pkg.mOriginalPackages = null;
6342            pkg.mRealPackage = null;
6343            pkg.mAdoptPermissions = null;
6344        }
6345
6346        // writer
6347        synchronized (mPackages) {
6348            if (pkg.mSharedUserId != null) {
6349                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6350                if (suid == null) {
6351                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6352                            "Creating application package " + pkg.packageName
6353                            + " for shared user failed");
6354                }
6355                if (DEBUG_PACKAGE_SCANNING) {
6356                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6357                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6358                                + "): packages=" + suid.packages);
6359                }
6360            }
6361
6362            // Check if we are renaming from an original package name.
6363            PackageSetting origPackage = null;
6364            String realName = null;
6365            if (pkg.mOriginalPackages != null) {
6366                // This package may need to be renamed to a previously
6367                // installed name.  Let's check on that...
6368                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6369                if (pkg.mOriginalPackages.contains(renamed)) {
6370                    // This package had originally been installed as the
6371                    // original name, and we have already taken care of
6372                    // transitioning to the new one.  Just update the new
6373                    // one to continue using the old name.
6374                    realName = pkg.mRealPackage;
6375                    if (!pkg.packageName.equals(renamed)) {
6376                        // Callers into this function may have already taken
6377                        // care of renaming the package; only do it here if
6378                        // it is not already done.
6379                        pkg.setPackageName(renamed);
6380                    }
6381
6382                } else {
6383                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6384                        if ((origPackage = mSettings.peekPackageLPr(
6385                                pkg.mOriginalPackages.get(i))) != null) {
6386                            // We do have the package already installed under its
6387                            // original name...  should we use it?
6388                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6389                                // New package is not compatible with original.
6390                                origPackage = null;
6391                                continue;
6392                            } else if (origPackage.sharedUser != null) {
6393                                // Make sure uid is compatible between packages.
6394                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6395                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6396                                            + " to " + pkg.packageName + ": old uid "
6397                                            + origPackage.sharedUser.name
6398                                            + " differs from " + pkg.mSharedUserId);
6399                                    origPackage = null;
6400                                    continue;
6401                                }
6402                            } else {
6403                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6404                                        + pkg.packageName + " to old name " + origPackage.name);
6405                            }
6406                            break;
6407                        }
6408                    }
6409                }
6410            }
6411
6412            if (mTransferedPackages.contains(pkg.packageName)) {
6413                Slog.w(TAG, "Package " + pkg.packageName
6414                        + " was transferred to another, but its .apk remains");
6415            }
6416
6417            // Just create the setting, don't add it yet. For already existing packages
6418            // the PkgSetting exists already and doesn't have to be created.
6419            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6420                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6421                    pkg.applicationInfo.primaryCpuAbi,
6422                    pkg.applicationInfo.secondaryCpuAbi,
6423                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6424                    user, false);
6425            if (pkgSetting == null) {
6426                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6427                        "Creating application package " + pkg.packageName + " failed");
6428            }
6429
6430            if (pkgSetting.origPackage != null) {
6431                // If we are first transitioning from an original package,
6432                // fix up the new package's name now.  We need to do this after
6433                // looking up the package under its new name, so getPackageLP
6434                // can take care of fiddling things correctly.
6435                pkg.setPackageName(origPackage.name);
6436
6437                // File a report about this.
6438                String msg = "New package " + pkgSetting.realName
6439                        + " renamed to replace old package " + pkgSetting.name;
6440                reportSettingsProblem(Log.WARN, msg);
6441
6442                // Make a note of it.
6443                mTransferedPackages.add(origPackage.name);
6444
6445                // No longer need to retain this.
6446                pkgSetting.origPackage = null;
6447            }
6448
6449            if (realName != null) {
6450                // Make a note of it.
6451                mTransferedPackages.add(pkg.packageName);
6452            }
6453
6454            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6455                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6456            }
6457
6458            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6459                // Check all shared libraries and map to their actual file path.
6460                // We only do this here for apps not on a system dir, because those
6461                // are the only ones that can fail an install due to this.  We
6462                // will take care of the system apps by updating all of their
6463                // library paths after the scan is done.
6464                updateSharedLibrariesLPw(pkg, null);
6465            }
6466
6467            if (mFoundPolicyFile) {
6468                SELinuxMMAC.assignSeinfoValue(pkg);
6469            }
6470
6471            pkg.applicationInfo.uid = pkgSetting.appId;
6472            pkg.mExtras = pkgSetting;
6473            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6474                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6475                    // We just determined the app is signed correctly, so bring
6476                    // over the latest parsed certs.
6477                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6478                } else {
6479                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6480                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6481                                "Package " + pkg.packageName + " upgrade keys do not match the "
6482                                + "previously installed version");
6483                    } else {
6484                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6485                        String msg = "System package " + pkg.packageName
6486                            + " signature changed; retaining data.";
6487                        reportSettingsProblem(Log.WARN, msg);
6488                    }
6489                }
6490            } else {
6491                try {
6492                    verifySignaturesLP(pkgSetting, pkg);
6493                    // We just determined the app is signed correctly, so bring
6494                    // over the latest parsed certs.
6495                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6496                } catch (PackageManagerException e) {
6497                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6498                        throw e;
6499                    }
6500                    // The signature has changed, but this package is in the system
6501                    // image...  let's recover!
6502                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6503                    // However...  if this package is part of a shared user, but it
6504                    // doesn't match the signature of the shared user, let's fail.
6505                    // What this means is that you can't change the signatures
6506                    // associated with an overall shared user, which doesn't seem all
6507                    // that unreasonable.
6508                    if (pkgSetting.sharedUser != null) {
6509                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6510                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6511                            throw new PackageManagerException(
6512                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6513                                            "Signature mismatch for shared user : "
6514                                            + pkgSetting.sharedUser);
6515                        }
6516                    }
6517                    // File a report about this.
6518                    String msg = "System package " + pkg.packageName
6519                        + " signature changed; retaining data.";
6520                    reportSettingsProblem(Log.WARN, msg);
6521                }
6522            }
6523            // Verify that this new package doesn't have any content providers
6524            // that conflict with existing packages.  Only do this if the
6525            // package isn't already installed, since we don't want to break
6526            // things that are installed.
6527            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6528                final int N = pkg.providers.size();
6529                int i;
6530                for (i=0; i<N; i++) {
6531                    PackageParser.Provider p = pkg.providers.get(i);
6532                    if (p.info.authority != null) {
6533                        String names[] = p.info.authority.split(";");
6534                        for (int j = 0; j < names.length; j++) {
6535                            if (mProvidersByAuthority.containsKey(names[j])) {
6536                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6537                                final String otherPackageName =
6538                                        ((other != null && other.getComponentName() != null) ?
6539                                                other.getComponentName().getPackageName() : "?");
6540                                throw new PackageManagerException(
6541                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6542                                                "Can't install because provider name " + names[j]
6543                                                + " (in package " + pkg.applicationInfo.packageName
6544                                                + ") is already used by " + otherPackageName);
6545                            }
6546                        }
6547                    }
6548                }
6549            }
6550
6551            if (pkg.mAdoptPermissions != null) {
6552                // This package wants to adopt ownership of permissions from
6553                // another package.
6554                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6555                    final String origName = pkg.mAdoptPermissions.get(i);
6556                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6557                    if (orig != null) {
6558                        if (verifyPackageUpdateLPr(orig, pkg)) {
6559                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6560                                    + pkg.packageName);
6561                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6562                        }
6563                    }
6564                }
6565            }
6566        }
6567
6568        final String pkgName = pkg.packageName;
6569
6570        final long scanFileTime = scanFile.lastModified();
6571        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6572        pkg.applicationInfo.processName = fixProcessName(
6573                pkg.applicationInfo.packageName,
6574                pkg.applicationInfo.processName,
6575                pkg.applicationInfo.uid);
6576
6577        File dataPath;
6578        if (mPlatformPackage == pkg) {
6579            // The system package is special.
6580            dataPath = new File(Environment.getDataDirectory(), "system");
6581
6582            pkg.applicationInfo.dataDir = dataPath.getPath();
6583
6584        } else {
6585            // This is a normal package, need to make its data directory.
6586            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6587                    UserHandle.USER_OWNER);
6588
6589            boolean uidError = false;
6590            if (dataPath.exists()) {
6591                int currentUid = 0;
6592                try {
6593                    StructStat stat = Os.stat(dataPath.getPath());
6594                    currentUid = stat.st_uid;
6595                } catch (ErrnoException e) {
6596                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6597                }
6598
6599                // If we have mismatched owners for the data path, we have a problem.
6600                if (currentUid != pkg.applicationInfo.uid) {
6601                    boolean recovered = false;
6602                    if (currentUid == 0) {
6603                        // The directory somehow became owned by root.  Wow.
6604                        // This is probably because the system was stopped while
6605                        // installd was in the middle of messing with its libs
6606                        // directory.  Ask installd to fix that.
6607                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6608                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6609                        if (ret >= 0) {
6610                            recovered = true;
6611                            String msg = "Package " + pkg.packageName
6612                                    + " unexpectedly changed to uid 0; recovered to " +
6613                                    + pkg.applicationInfo.uid;
6614                            reportSettingsProblem(Log.WARN, msg);
6615                        }
6616                    }
6617                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6618                            || (scanFlags&SCAN_BOOTING) != 0)) {
6619                        // If this is a system app, we can at least delete its
6620                        // current data so the application will still work.
6621                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6622                        if (ret >= 0) {
6623                            // TODO: Kill the processes first
6624                            // Old data gone!
6625                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6626                                    ? "System package " : "Third party package ";
6627                            String msg = prefix + pkg.packageName
6628                                    + " has changed from uid: "
6629                                    + currentUid + " to "
6630                                    + pkg.applicationInfo.uid + "; old data erased";
6631                            reportSettingsProblem(Log.WARN, msg);
6632                            recovered = true;
6633
6634                            // And now re-install the app.
6635                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6636                                    pkg.applicationInfo.seinfo);
6637                            if (ret == -1) {
6638                                // Ack should not happen!
6639                                msg = prefix + pkg.packageName
6640                                        + " could not have data directory re-created after delete.";
6641                                reportSettingsProblem(Log.WARN, msg);
6642                                throw new PackageManagerException(
6643                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6644                            }
6645                        }
6646                        if (!recovered) {
6647                            mHasSystemUidErrors = true;
6648                        }
6649                    } else if (!recovered) {
6650                        // If we allow this install to proceed, we will be broken.
6651                        // Abort, abort!
6652                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6653                                "scanPackageLI");
6654                    }
6655                    if (!recovered) {
6656                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6657                            + pkg.applicationInfo.uid + "/fs_"
6658                            + currentUid;
6659                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6660                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6661                        String msg = "Package " + pkg.packageName
6662                                + " has mismatched uid: "
6663                                + currentUid + " on disk, "
6664                                + pkg.applicationInfo.uid + " in settings";
6665                        // writer
6666                        synchronized (mPackages) {
6667                            mSettings.mReadMessages.append(msg);
6668                            mSettings.mReadMessages.append('\n');
6669                            uidError = true;
6670                            if (!pkgSetting.uidError) {
6671                                reportSettingsProblem(Log.ERROR, msg);
6672                            }
6673                        }
6674                    }
6675                }
6676                pkg.applicationInfo.dataDir = dataPath.getPath();
6677                if (mShouldRestoreconData) {
6678                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6679                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6680                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6681                }
6682            } else {
6683                if (DEBUG_PACKAGE_SCANNING) {
6684                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6685                        Log.v(TAG, "Want this data dir: " + dataPath);
6686                }
6687                //invoke installer to do the actual installation
6688                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6689                        pkg.applicationInfo.seinfo);
6690                if (ret < 0) {
6691                    // Error from installer
6692                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6693                            "Unable to create data dirs [errorCode=" + ret + "]");
6694                }
6695
6696                if (dataPath.exists()) {
6697                    pkg.applicationInfo.dataDir = dataPath.getPath();
6698                } else {
6699                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6700                    pkg.applicationInfo.dataDir = null;
6701                }
6702            }
6703
6704            pkgSetting.uidError = uidError;
6705        }
6706
6707        final String path = scanFile.getPath();
6708        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6709
6710        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6711            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6712
6713            // Some system apps still use directory structure for native libraries
6714            // in which case we might end up not detecting abi solely based on apk
6715            // structure. Try to detect abi based on directory structure.
6716            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6717                    pkg.applicationInfo.primaryCpuAbi == null) {
6718                setBundledAppAbisAndRoots(pkg, pkgSetting);
6719                setNativeLibraryPaths(pkg);
6720            }
6721
6722        } else {
6723            if ((scanFlags & SCAN_MOVE) != 0) {
6724                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6725                // but we already have this packages package info in the PackageSetting. We just
6726                // use that and derive the native library path based on the new codepath.
6727                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6728                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6729            }
6730
6731            // Set native library paths again. For moves, the path will be updated based on the
6732            // ABIs we've determined above. For non-moves, the path will be updated based on the
6733            // ABIs we determined during compilation, but the path will depend on the final
6734            // package path (after the rename away from the stage path).
6735            setNativeLibraryPaths(pkg);
6736        }
6737
6738        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6739        final int[] userIds = sUserManager.getUserIds();
6740        synchronized (mInstallLock) {
6741            // Create a native library symlink only if we have native libraries
6742            // and if the native libraries are 32 bit libraries. We do not provide
6743            // this symlink for 64 bit libraries.
6744            if (pkg.applicationInfo.primaryCpuAbi != null &&
6745                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6746                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6747                for (int userId : userIds) {
6748                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6749                            nativeLibPath, userId) < 0) {
6750                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6751                                "Failed linking native library dir (user=" + userId + ")");
6752                    }
6753                }
6754            }
6755        }
6756
6757        // This is a special case for the "system" package, where the ABI is
6758        // dictated by the zygote configuration (and init.rc). We should keep track
6759        // of this ABI so that we can deal with "normal" applications that run under
6760        // the same UID correctly.
6761        if (mPlatformPackage == pkg) {
6762            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6763                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6764        }
6765
6766        // If there's a mismatch between the abi-override in the package setting
6767        // and the abiOverride specified for the install. Warn about this because we
6768        // would've already compiled the app without taking the package setting into
6769        // account.
6770        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6771            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6772                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6773                        " for package: " + pkg.packageName);
6774            }
6775        }
6776
6777        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6778        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6779        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6780
6781        // Copy the derived override back to the parsed package, so that we can
6782        // update the package settings accordingly.
6783        pkg.cpuAbiOverride = cpuAbiOverride;
6784
6785        if (DEBUG_ABI_SELECTION) {
6786            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6787                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6788                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6789        }
6790
6791        // Push the derived path down into PackageSettings so we know what to
6792        // clean up at uninstall time.
6793        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6794
6795        if (DEBUG_ABI_SELECTION) {
6796            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6797                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6798                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6799        }
6800
6801        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6802            // We don't do this here during boot because we can do it all
6803            // at once after scanning all existing packages.
6804            //
6805            // We also do this *before* we perform dexopt on this package, so that
6806            // we can avoid redundant dexopts, and also to make sure we've got the
6807            // code and package path correct.
6808            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6809                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6810        }
6811
6812        if ((scanFlags & SCAN_NO_DEX) == 0) {
6813            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6814                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6815            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6816                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6817            }
6818        }
6819        if (mFactoryTest && pkg.requestedPermissions.contains(
6820                android.Manifest.permission.FACTORY_TEST)) {
6821            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6822        }
6823
6824        ArrayList<PackageParser.Package> clientLibPkgs = null;
6825
6826        // writer
6827        synchronized (mPackages) {
6828            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6829                // Only system apps can add new shared libraries.
6830                if (pkg.libraryNames != null) {
6831                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6832                        String name = pkg.libraryNames.get(i);
6833                        boolean allowed = false;
6834                        if (pkg.isUpdatedSystemApp()) {
6835                            // New library entries can only be added through the
6836                            // system image.  This is important to get rid of a lot
6837                            // of nasty edge cases: for example if we allowed a non-
6838                            // system update of the app to add a library, then uninstalling
6839                            // the update would make the library go away, and assumptions
6840                            // we made such as through app install filtering would now
6841                            // have allowed apps on the device which aren't compatible
6842                            // with it.  Better to just have the restriction here, be
6843                            // conservative, and create many fewer cases that can negatively
6844                            // impact the user experience.
6845                            final PackageSetting sysPs = mSettings
6846                                    .getDisabledSystemPkgLPr(pkg.packageName);
6847                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6848                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6849                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6850                                        allowed = true;
6851                                        allowed = true;
6852                                        break;
6853                                    }
6854                                }
6855                            }
6856                        } else {
6857                            allowed = true;
6858                        }
6859                        if (allowed) {
6860                            if (!mSharedLibraries.containsKey(name)) {
6861                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6862                            } else if (!name.equals(pkg.packageName)) {
6863                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6864                                        + name + " already exists; skipping");
6865                            }
6866                        } else {
6867                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6868                                    + name + " that is not declared on system image; skipping");
6869                        }
6870                    }
6871                    if ((scanFlags&SCAN_BOOTING) == 0) {
6872                        // If we are not booting, we need to update any applications
6873                        // that are clients of our shared library.  If we are booting,
6874                        // this will all be done once the scan is complete.
6875                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6876                    }
6877                }
6878            }
6879        }
6880
6881        // We also need to dexopt any apps that are dependent on this library.  Note that
6882        // if these fail, we should abort the install since installing the library will
6883        // result in some apps being broken.
6884        if (clientLibPkgs != null) {
6885            if ((scanFlags & SCAN_NO_DEX) == 0) {
6886                for (int i = 0; i < clientLibPkgs.size(); i++) {
6887                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6888                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6889                            null /* instruction sets */, forceDex,
6890                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6891                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6892                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6893                                "scanPackageLI failed to dexopt clientLibPkgs");
6894                    }
6895                }
6896            }
6897        }
6898
6899        // Also need to kill any apps that are dependent on the library.
6900        if (clientLibPkgs != null) {
6901            for (int i=0; i<clientLibPkgs.size(); i++) {
6902                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6903                killApplication(clientPkg.applicationInfo.packageName,
6904                        clientPkg.applicationInfo.uid, "update lib");
6905            }
6906        }
6907
6908        // Make sure we're not adding any bogus keyset info
6909        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6910        ksms.assertScannedPackageValid(pkg);
6911
6912        // writer
6913        synchronized (mPackages) {
6914            // We don't expect installation to fail beyond this point
6915
6916            // Add the new setting to mSettings
6917            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6918            // Add the new setting to mPackages
6919            mPackages.put(pkg.applicationInfo.packageName, pkg);
6920            // Make sure we don't accidentally delete its data.
6921            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6922            while (iter.hasNext()) {
6923                PackageCleanItem item = iter.next();
6924                if (pkgName.equals(item.packageName)) {
6925                    iter.remove();
6926                }
6927            }
6928
6929            // Take care of first install / last update times.
6930            if (currentTime != 0) {
6931                if (pkgSetting.firstInstallTime == 0) {
6932                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6933                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6934                    pkgSetting.lastUpdateTime = currentTime;
6935                }
6936            } else if (pkgSetting.firstInstallTime == 0) {
6937                // We need *something*.  Take time time stamp of the file.
6938                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6939            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6940                if (scanFileTime != pkgSetting.timeStamp) {
6941                    // A package on the system image has changed; consider this
6942                    // to be an update.
6943                    pkgSetting.lastUpdateTime = scanFileTime;
6944                }
6945            }
6946
6947            // Add the package's KeySets to the global KeySetManagerService
6948            ksms.addScannedPackageLPw(pkg);
6949
6950            int N = pkg.providers.size();
6951            StringBuilder r = null;
6952            int i;
6953            for (i=0; i<N; i++) {
6954                PackageParser.Provider p = pkg.providers.get(i);
6955                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6956                        p.info.processName, pkg.applicationInfo.uid);
6957                mProviders.addProvider(p);
6958                p.syncable = p.info.isSyncable;
6959                if (p.info.authority != null) {
6960                    String names[] = p.info.authority.split(";");
6961                    p.info.authority = null;
6962                    for (int j = 0; j < names.length; j++) {
6963                        if (j == 1 && p.syncable) {
6964                            // We only want the first authority for a provider to possibly be
6965                            // syncable, so if we already added this provider using a different
6966                            // authority clear the syncable flag. We copy the provider before
6967                            // changing it because the mProviders object contains a reference
6968                            // to a provider that we don't want to change.
6969                            // Only do this for the second authority since the resulting provider
6970                            // object can be the same for all future authorities for this provider.
6971                            p = new PackageParser.Provider(p);
6972                            p.syncable = false;
6973                        }
6974                        if (!mProvidersByAuthority.containsKey(names[j])) {
6975                            mProvidersByAuthority.put(names[j], p);
6976                            if (p.info.authority == null) {
6977                                p.info.authority = names[j];
6978                            } else {
6979                                p.info.authority = p.info.authority + ";" + names[j];
6980                            }
6981                            if (DEBUG_PACKAGE_SCANNING) {
6982                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6983                                    Log.d(TAG, "Registered content provider: " + names[j]
6984                                            + ", className = " + p.info.name + ", isSyncable = "
6985                                            + p.info.isSyncable);
6986                            }
6987                        } else {
6988                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6989                            Slog.w(TAG, "Skipping provider name " + names[j] +
6990                                    " (in package " + pkg.applicationInfo.packageName +
6991                                    "): name already used by "
6992                                    + ((other != null && other.getComponentName() != null)
6993                                            ? other.getComponentName().getPackageName() : "?"));
6994                        }
6995                    }
6996                }
6997                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6998                    if (r == null) {
6999                        r = new StringBuilder(256);
7000                    } else {
7001                        r.append(' ');
7002                    }
7003                    r.append(p.info.name);
7004                }
7005            }
7006            if (r != null) {
7007                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7008            }
7009
7010            N = pkg.services.size();
7011            r = null;
7012            for (i=0; i<N; i++) {
7013                PackageParser.Service s = pkg.services.get(i);
7014                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7015                        s.info.processName, pkg.applicationInfo.uid);
7016                mServices.addService(s);
7017                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7018                    if (r == null) {
7019                        r = new StringBuilder(256);
7020                    } else {
7021                        r.append(' ');
7022                    }
7023                    r.append(s.info.name);
7024                }
7025            }
7026            if (r != null) {
7027                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7028            }
7029
7030            N = pkg.receivers.size();
7031            r = null;
7032            for (i=0; i<N; i++) {
7033                PackageParser.Activity a = pkg.receivers.get(i);
7034                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7035                        a.info.processName, pkg.applicationInfo.uid);
7036                mReceivers.addActivity(a, "receiver");
7037                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7038                    if (r == null) {
7039                        r = new StringBuilder(256);
7040                    } else {
7041                        r.append(' ');
7042                    }
7043                    r.append(a.info.name);
7044                }
7045            }
7046            if (r != null) {
7047                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7048            }
7049
7050            N = pkg.activities.size();
7051            r = null;
7052            for (i=0; i<N; i++) {
7053                PackageParser.Activity a = pkg.activities.get(i);
7054                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7055                        a.info.processName, pkg.applicationInfo.uid);
7056                mActivities.addActivity(a, "activity");
7057                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7058                    if (r == null) {
7059                        r = new StringBuilder(256);
7060                    } else {
7061                        r.append(' ');
7062                    }
7063                    r.append(a.info.name);
7064                }
7065            }
7066            if (r != null) {
7067                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7068            }
7069
7070            N = pkg.permissionGroups.size();
7071            r = null;
7072            for (i=0; i<N; i++) {
7073                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7074                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7075                if (cur == null) {
7076                    mPermissionGroups.put(pg.info.name, pg);
7077                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7078                        if (r == null) {
7079                            r = new StringBuilder(256);
7080                        } else {
7081                            r.append(' ');
7082                        }
7083                        r.append(pg.info.name);
7084                    }
7085                } else {
7086                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7087                            + pg.info.packageName + " ignored: original from "
7088                            + cur.info.packageName);
7089                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7090                        if (r == null) {
7091                            r = new StringBuilder(256);
7092                        } else {
7093                            r.append(' ');
7094                        }
7095                        r.append("DUP:");
7096                        r.append(pg.info.name);
7097                    }
7098                }
7099            }
7100            if (r != null) {
7101                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7102            }
7103
7104            N = pkg.permissions.size();
7105            r = null;
7106            for (i=0; i<N; i++) {
7107                PackageParser.Permission p = pkg.permissions.get(i);
7108
7109                // Now that permission groups have a special meaning, we ignore permission
7110                // groups for legacy apps to prevent unexpected behavior. In particular,
7111                // permissions for one app being granted to someone just becuase they happen
7112                // to be in a group defined by another app (before this had no implications).
7113                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7114                    p.group = mPermissionGroups.get(p.info.group);
7115                    // Warn for a permission in an unknown group.
7116                    if (p.info.group != null && p.group == null) {
7117                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7118                                + p.info.packageName + " in an unknown group " + p.info.group);
7119                    }
7120                }
7121
7122                ArrayMap<String, BasePermission> permissionMap =
7123                        p.tree ? mSettings.mPermissionTrees
7124                                : mSettings.mPermissions;
7125                BasePermission bp = permissionMap.get(p.info.name);
7126
7127                // Allow system apps to redefine non-system permissions
7128                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7129                    final boolean currentOwnerIsSystem = (bp.perm != null
7130                            && isSystemApp(bp.perm.owner));
7131                    if (isSystemApp(p.owner)) {
7132                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7133                            // It's a built-in permission and no owner, take ownership now
7134                            bp.packageSetting = pkgSetting;
7135                            bp.perm = p;
7136                            bp.uid = pkg.applicationInfo.uid;
7137                            bp.sourcePackage = p.info.packageName;
7138                        } else if (!currentOwnerIsSystem) {
7139                            String msg = "New decl " + p.owner + " of permission  "
7140                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7141                            reportSettingsProblem(Log.WARN, msg);
7142                            bp = null;
7143                        }
7144                    }
7145                }
7146
7147                if (bp == null) {
7148                    bp = new BasePermission(p.info.name, p.info.packageName,
7149                            BasePermission.TYPE_NORMAL);
7150                    permissionMap.put(p.info.name, bp);
7151                }
7152
7153                if (bp.perm == null) {
7154                    if (bp.sourcePackage == null
7155                            || bp.sourcePackage.equals(p.info.packageName)) {
7156                        BasePermission tree = findPermissionTreeLP(p.info.name);
7157                        if (tree == null
7158                                || tree.sourcePackage.equals(p.info.packageName)) {
7159                            bp.packageSetting = pkgSetting;
7160                            bp.perm = p;
7161                            bp.uid = pkg.applicationInfo.uid;
7162                            bp.sourcePackage = p.info.packageName;
7163                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7164                                if (r == null) {
7165                                    r = new StringBuilder(256);
7166                                } else {
7167                                    r.append(' ');
7168                                }
7169                                r.append(p.info.name);
7170                            }
7171                        } else {
7172                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7173                                    + p.info.packageName + " ignored: base tree "
7174                                    + tree.name + " is from package "
7175                                    + tree.sourcePackage);
7176                        }
7177                    } else {
7178                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7179                                + p.info.packageName + " ignored: original from "
7180                                + bp.sourcePackage);
7181                    }
7182                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7183                    if (r == null) {
7184                        r = new StringBuilder(256);
7185                    } else {
7186                        r.append(' ');
7187                    }
7188                    r.append("DUP:");
7189                    r.append(p.info.name);
7190                }
7191                if (bp.perm == p) {
7192                    bp.protectionLevel = p.info.protectionLevel;
7193                }
7194            }
7195
7196            if (r != null) {
7197                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7198            }
7199
7200            N = pkg.instrumentation.size();
7201            r = null;
7202            for (i=0; i<N; i++) {
7203                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7204                a.info.packageName = pkg.applicationInfo.packageName;
7205                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7206                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7207                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7208                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7209                a.info.dataDir = pkg.applicationInfo.dataDir;
7210
7211                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7212                // need other information about the application, like the ABI and what not ?
7213                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7214                mInstrumentation.put(a.getComponentName(), a);
7215                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7216                    if (r == null) {
7217                        r = new StringBuilder(256);
7218                    } else {
7219                        r.append(' ');
7220                    }
7221                    r.append(a.info.name);
7222                }
7223            }
7224            if (r != null) {
7225                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7226            }
7227
7228            if (pkg.protectedBroadcasts != null) {
7229                N = pkg.protectedBroadcasts.size();
7230                for (i=0; i<N; i++) {
7231                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7232                }
7233            }
7234
7235            pkgSetting.setTimeStamp(scanFileTime);
7236
7237            // Create idmap files for pairs of (packages, overlay packages).
7238            // Note: "android", ie framework-res.apk, is handled by native layers.
7239            if (pkg.mOverlayTarget != null) {
7240                // This is an overlay package.
7241                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7242                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7243                        mOverlays.put(pkg.mOverlayTarget,
7244                                new ArrayMap<String, PackageParser.Package>());
7245                    }
7246                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7247                    map.put(pkg.packageName, pkg);
7248                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7249                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7250                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7251                                "scanPackageLI failed to createIdmap");
7252                    }
7253                }
7254            } else if (mOverlays.containsKey(pkg.packageName) &&
7255                    !pkg.packageName.equals("android")) {
7256                // This is a regular package, with one or more known overlay packages.
7257                createIdmapsForPackageLI(pkg);
7258            }
7259        }
7260
7261        return pkg;
7262    }
7263
7264    /**
7265     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7266     * is derived purely on the basis of the contents of {@code scanFile} and
7267     * {@code cpuAbiOverride}.
7268     *
7269     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7270     */
7271    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7272                                 String cpuAbiOverride, boolean extractLibs)
7273            throws PackageManagerException {
7274        // TODO: We can probably be smarter about this stuff. For installed apps,
7275        // we can calculate this information at install time once and for all. For
7276        // system apps, we can probably assume that this information doesn't change
7277        // after the first boot scan. As things stand, we do lots of unnecessary work.
7278
7279        // Give ourselves some initial paths; we'll come back for another
7280        // pass once we've determined ABI below.
7281        setNativeLibraryPaths(pkg);
7282
7283        // We would never need to extract libs for forward-locked and external packages,
7284        // since the container service will do it for us. We shouldn't attempt to
7285        // extract libs from system app when it was not updated.
7286        if (pkg.isForwardLocked() || isExternal(pkg) ||
7287            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7288            extractLibs = false;
7289        }
7290
7291        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7292        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7293
7294        NativeLibraryHelper.Handle handle = null;
7295        try {
7296            handle = NativeLibraryHelper.Handle.create(pkg);
7297            // TODO(multiArch): This can be null for apps that didn't go through the
7298            // usual installation process. We can calculate it again, like we
7299            // do during install time.
7300            //
7301            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7302            // unnecessary.
7303            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7304
7305            // Null out the abis so that they can be recalculated.
7306            pkg.applicationInfo.primaryCpuAbi = null;
7307            pkg.applicationInfo.secondaryCpuAbi = null;
7308            if (isMultiArch(pkg.applicationInfo)) {
7309                // Warn if we've set an abiOverride for multi-lib packages..
7310                // By definition, we need to copy both 32 and 64 bit libraries for
7311                // such packages.
7312                if (pkg.cpuAbiOverride != null
7313                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7314                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7315                }
7316
7317                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7318                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7319                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7320                    if (extractLibs) {
7321                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7322                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7323                                useIsaSpecificSubdirs);
7324                    } else {
7325                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7326                    }
7327                }
7328
7329                maybeThrowExceptionForMultiArchCopy(
7330                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7331
7332                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7333                    if (extractLibs) {
7334                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7335                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7336                                useIsaSpecificSubdirs);
7337                    } else {
7338                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7339                    }
7340                }
7341
7342                maybeThrowExceptionForMultiArchCopy(
7343                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7344
7345                if (abi64 >= 0) {
7346                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7347                }
7348
7349                if (abi32 >= 0) {
7350                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7351                    if (abi64 >= 0) {
7352                        pkg.applicationInfo.secondaryCpuAbi = abi;
7353                    } else {
7354                        pkg.applicationInfo.primaryCpuAbi = abi;
7355                    }
7356                }
7357            } else {
7358                String[] abiList = (cpuAbiOverride != null) ?
7359                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7360
7361                // Enable gross and lame hacks for apps that are built with old
7362                // SDK tools. We must scan their APKs for renderscript bitcode and
7363                // not launch them if it's present. Don't bother checking on devices
7364                // that don't have 64 bit support.
7365                boolean needsRenderScriptOverride = false;
7366                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7367                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7368                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7369                    needsRenderScriptOverride = true;
7370                }
7371
7372                final int copyRet;
7373                if (extractLibs) {
7374                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7375                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7376                } else {
7377                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7378                }
7379
7380                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7381                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7382                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7383                }
7384
7385                if (copyRet >= 0) {
7386                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7387                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7388                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7389                } else if (needsRenderScriptOverride) {
7390                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7391                }
7392            }
7393        } catch (IOException ioe) {
7394            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7395        } finally {
7396            IoUtils.closeQuietly(handle);
7397        }
7398
7399        // Now that we've calculated the ABIs and determined if it's an internal app,
7400        // we will go ahead and populate the nativeLibraryPath.
7401        setNativeLibraryPaths(pkg);
7402    }
7403
7404    /**
7405     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7406     * i.e, so that all packages can be run inside a single process if required.
7407     *
7408     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7409     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7410     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7411     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7412     * updating a package that belongs to a shared user.
7413     *
7414     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7415     * adds unnecessary complexity.
7416     */
7417    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7418            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7419        String requiredInstructionSet = null;
7420        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7421            requiredInstructionSet = VMRuntime.getInstructionSet(
7422                     scannedPackage.applicationInfo.primaryCpuAbi);
7423        }
7424
7425        PackageSetting requirer = null;
7426        for (PackageSetting ps : packagesForUser) {
7427            // If packagesForUser contains scannedPackage, we skip it. This will happen
7428            // when scannedPackage is an update of an existing package. Without this check,
7429            // we will never be able to change the ABI of any package belonging to a shared
7430            // user, even if it's compatible with other packages.
7431            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7432                if (ps.primaryCpuAbiString == null) {
7433                    continue;
7434                }
7435
7436                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7437                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7438                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7439                    // this but there's not much we can do.
7440                    String errorMessage = "Instruction set mismatch, "
7441                            + ((requirer == null) ? "[caller]" : requirer)
7442                            + " requires " + requiredInstructionSet + " whereas " + ps
7443                            + " requires " + instructionSet;
7444                    Slog.w(TAG, errorMessage);
7445                }
7446
7447                if (requiredInstructionSet == null) {
7448                    requiredInstructionSet = instructionSet;
7449                    requirer = ps;
7450                }
7451            }
7452        }
7453
7454        if (requiredInstructionSet != null) {
7455            String adjustedAbi;
7456            if (requirer != null) {
7457                // requirer != null implies that either scannedPackage was null or that scannedPackage
7458                // did not require an ABI, in which case we have to adjust scannedPackage to match
7459                // the ABI of the set (which is the same as requirer's ABI)
7460                adjustedAbi = requirer.primaryCpuAbiString;
7461                if (scannedPackage != null) {
7462                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7463                }
7464            } else {
7465                // requirer == null implies that we're updating all ABIs in the set to
7466                // match scannedPackage.
7467                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7468            }
7469
7470            for (PackageSetting ps : packagesForUser) {
7471                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7472                    if (ps.primaryCpuAbiString != null) {
7473                        continue;
7474                    }
7475
7476                    ps.primaryCpuAbiString = adjustedAbi;
7477                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7478                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7479                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7480
7481                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7482                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7483                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7484                            ps.primaryCpuAbiString = null;
7485                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7486                            return;
7487                        } else {
7488                            mInstaller.rmdex(ps.codePathString,
7489                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7490                        }
7491                    }
7492                }
7493            }
7494        }
7495    }
7496
7497    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7498        synchronized (mPackages) {
7499            mResolverReplaced = true;
7500            // Set up information for custom user intent resolution activity.
7501            mResolveActivity.applicationInfo = pkg.applicationInfo;
7502            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7503            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7504            mResolveActivity.processName = pkg.applicationInfo.packageName;
7505            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7506            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7507                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7508            mResolveActivity.theme = 0;
7509            mResolveActivity.exported = true;
7510            mResolveActivity.enabled = true;
7511            mResolveInfo.activityInfo = mResolveActivity;
7512            mResolveInfo.priority = 0;
7513            mResolveInfo.preferredOrder = 0;
7514            mResolveInfo.match = 0;
7515            mResolveComponentName = mCustomResolverComponentName;
7516            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7517                    mResolveComponentName);
7518        }
7519    }
7520
7521    private static String calculateBundledApkRoot(final String codePathString) {
7522        final File codePath = new File(codePathString);
7523        final File codeRoot;
7524        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7525            codeRoot = Environment.getRootDirectory();
7526        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7527            codeRoot = Environment.getOemDirectory();
7528        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7529            codeRoot = Environment.getVendorDirectory();
7530        } else {
7531            // Unrecognized code path; take its top real segment as the apk root:
7532            // e.g. /something/app/blah.apk => /something
7533            try {
7534                File f = codePath.getCanonicalFile();
7535                File parent = f.getParentFile();    // non-null because codePath is a file
7536                File tmp;
7537                while ((tmp = parent.getParentFile()) != null) {
7538                    f = parent;
7539                    parent = tmp;
7540                }
7541                codeRoot = f;
7542                Slog.w(TAG, "Unrecognized code path "
7543                        + codePath + " - using " + codeRoot);
7544            } catch (IOException e) {
7545                // Can't canonicalize the code path -- shenanigans?
7546                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7547                return Environment.getRootDirectory().getPath();
7548            }
7549        }
7550        return codeRoot.getPath();
7551    }
7552
7553    /**
7554     * Derive and set the location of native libraries for the given package,
7555     * which varies depending on where and how the package was installed.
7556     */
7557    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7558        final ApplicationInfo info = pkg.applicationInfo;
7559        final String codePath = pkg.codePath;
7560        final File codeFile = new File(codePath);
7561        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7562        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7563
7564        info.nativeLibraryRootDir = null;
7565        info.nativeLibraryRootRequiresIsa = false;
7566        info.nativeLibraryDir = null;
7567        info.secondaryNativeLibraryDir = null;
7568
7569        if (isApkFile(codeFile)) {
7570            // Monolithic install
7571            if (bundledApp) {
7572                // If "/system/lib64/apkname" exists, assume that is the per-package
7573                // native library directory to use; otherwise use "/system/lib/apkname".
7574                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7575                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7576                        getPrimaryInstructionSet(info));
7577
7578                // This is a bundled system app so choose the path based on the ABI.
7579                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7580                // is just the default path.
7581                final String apkName = deriveCodePathName(codePath);
7582                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7583                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7584                        apkName).getAbsolutePath();
7585
7586                if (info.secondaryCpuAbi != null) {
7587                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7588                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7589                            secondaryLibDir, apkName).getAbsolutePath();
7590                }
7591            } else if (asecApp) {
7592                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7593                        .getAbsolutePath();
7594            } else {
7595                final String apkName = deriveCodePathName(codePath);
7596                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7597                        .getAbsolutePath();
7598            }
7599
7600            info.nativeLibraryRootRequiresIsa = false;
7601            info.nativeLibraryDir = info.nativeLibraryRootDir;
7602        } else {
7603            // Cluster install
7604            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7605            info.nativeLibraryRootRequiresIsa = true;
7606
7607            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7608                    getPrimaryInstructionSet(info)).getAbsolutePath();
7609
7610            if (info.secondaryCpuAbi != null) {
7611                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7612                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7613            }
7614        }
7615    }
7616
7617    /**
7618     * Calculate the abis and roots for a bundled app. These can uniquely
7619     * be determined from the contents of the system partition, i.e whether
7620     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7621     * of this information, and instead assume that the system was built
7622     * sensibly.
7623     */
7624    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7625                                           PackageSetting pkgSetting) {
7626        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7627
7628        // If "/system/lib64/apkname" exists, assume that is the per-package
7629        // native library directory to use; otherwise use "/system/lib/apkname".
7630        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7631        setBundledAppAbi(pkg, apkRoot, apkName);
7632        // pkgSetting might be null during rescan following uninstall of updates
7633        // to a bundled app, so accommodate that possibility.  The settings in
7634        // that case will be established later from the parsed package.
7635        //
7636        // If the settings aren't null, sync them up with what we've just derived.
7637        // note that apkRoot isn't stored in the package settings.
7638        if (pkgSetting != null) {
7639            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7640            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7641        }
7642    }
7643
7644    /**
7645     * Deduces the ABI of a bundled app and sets the relevant fields on the
7646     * parsed pkg object.
7647     *
7648     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7649     *        under which system libraries are installed.
7650     * @param apkName the name of the installed package.
7651     */
7652    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7653        final File codeFile = new File(pkg.codePath);
7654
7655        final boolean has64BitLibs;
7656        final boolean has32BitLibs;
7657        if (isApkFile(codeFile)) {
7658            // Monolithic install
7659            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7660            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7661        } else {
7662            // Cluster install
7663            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7664            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7665                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7666                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7667                has64BitLibs = (new File(rootDir, isa)).exists();
7668            } else {
7669                has64BitLibs = false;
7670            }
7671            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7672                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7673                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7674                has32BitLibs = (new File(rootDir, isa)).exists();
7675            } else {
7676                has32BitLibs = false;
7677            }
7678        }
7679
7680        if (has64BitLibs && !has32BitLibs) {
7681            // The package has 64 bit libs, but not 32 bit libs. Its primary
7682            // ABI should be 64 bit. We can safely assume here that the bundled
7683            // native libraries correspond to the most preferred ABI in the list.
7684
7685            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7686            pkg.applicationInfo.secondaryCpuAbi = null;
7687        } else if (has32BitLibs && !has64BitLibs) {
7688            // The package has 32 bit libs but not 64 bit libs. Its primary
7689            // ABI should be 32 bit.
7690
7691            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7692            pkg.applicationInfo.secondaryCpuAbi = null;
7693        } else if (has32BitLibs && has64BitLibs) {
7694            // The application has both 64 and 32 bit bundled libraries. We check
7695            // here that the app declares multiArch support, and warn if it doesn't.
7696            //
7697            // We will be lenient here and record both ABIs. The primary will be the
7698            // ABI that's higher on the list, i.e, a device that's configured to prefer
7699            // 64 bit apps will see a 64 bit primary ABI,
7700
7701            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7702                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7703            }
7704
7705            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7706                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7707                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7708            } else {
7709                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7710                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7711            }
7712        } else {
7713            pkg.applicationInfo.primaryCpuAbi = null;
7714            pkg.applicationInfo.secondaryCpuAbi = null;
7715        }
7716    }
7717
7718    private void killApplication(String pkgName, int appId, String reason) {
7719        // Request the ActivityManager to kill the process(only for existing packages)
7720        // so that we do not end up in a confused state while the user is still using the older
7721        // version of the application while the new one gets installed.
7722        IActivityManager am = ActivityManagerNative.getDefault();
7723        if (am != null) {
7724            try {
7725                am.killApplicationWithAppId(pkgName, appId, reason);
7726            } catch (RemoteException e) {
7727            }
7728        }
7729    }
7730
7731    void removePackageLI(PackageSetting ps, boolean chatty) {
7732        if (DEBUG_INSTALL) {
7733            if (chatty)
7734                Log.d(TAG, "Removing package " + ps.name);
7735        }
7736
7737        // writer
7738        synchronized (mPackages) {
7739            mPackages.remove(ps.name);
7740            final PackageParser.Package pkg = ps.pkg;
7741            if (pkg != null) {
7742                cleanPackageDataStructuresLILPw(pkg, chatty);
7743            }
7744        }
7745    }
7746
7747    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7748        if (DEBUG_INSTALL) {
7749            if (chatty)
7750                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7751        }
7752
7753        // writer
7754        synchronized (mPackages) {
7755            mPackages.remove(pkg.applicationInfo.packageName);
7756            cleanPackageDataStructuresLILPw(pkg, chatty);
7757        }
7758    }
7759
7760    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7761        int N = pkg.providers.size();
7762        StringBuilder r = null;
7763        int i;
7764        for (i=0; i<N; i++) {
7765            PackageParser.Provider p = pkg.providers.get(i);
7766            mProviders.removeProvider(p);
7767            if (p.info.authority == null) {
7768
7769                /* There was another ContentProvider with this authority when
7770                 * this app was installed so this authority is null,
7771                 * Ignore it as we don't have to unregister the provider.
7772                 */
7773                continue;
7774            }
7775            String names[] = p.info.authority.split(";");
7776            for (int j = 0; j < names.length; j++) {
7777                if (mProvidersByAuthority.get(names[j]) == p) {
7778                    mProvidersByAuthority.remove(names[j]);
7779                    if (DEBUG_REMOVE) {
7780                        if (chatty)
7781                            Log.d(TAG, "Unregistered content provider: " + names[j]
7782                                    + ", className = " + p.info.name + ", isSyncable = "
7783                                    + p.info.isSyncable);
7784                    }
7785                }
7786            }
7787            if (DEBUG_REMOVE && chatty) {
7788                if (r == null) {
7789                    r = new StringBuilder(256);
7790                } else {
7791                    r.append(' ');
7792                }
7793                r.append(p.info.name);
7794            }
7795        }
7796        if (r != null) {
7797            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7798        }
7799
7800        N = pkg.services.size();
7801        r = null;
7802        for (i=0; i<N; i++) {
7803            PackageParser.Service s = pkg.services.get(i);
7804            mServices.removeService(s);
7805            if (chatty) {
7806                if (r == null) {
7807                    r = new StringBuilder(256);
7808                } else {
7809                    r.append(' ');
7810                }
7811                r.append(s.info.name);
7812            }
7813        }
7814        if (r != null) {
7815            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7816        }
7817
7818        N = pkg.receivers.size();
7819        r = null;
7820        for (i=0; i<N; i++) {
7821            PackageParser.Activity a = pkg.receivers.get(i);
7822            mReceivers.removeActivity(a, "receiver");
7823            if (DEBUG_REMOVE && chatty) {
7824                if (r == null) {
7825                    r = new StringBuilder(256);
7826                } else {
7827                    r.append(' ');
7828                }
7829                r.append(a.info.name);
7830            }
7831        }
7832        if (r != null) {
7833            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7834        }
7835
7836        N = pkg.activities.size();
7837        r = null;
7838        for (i=0; i<N; i++) {
7839            PackageParser.Activity a = pkg.activities.get(i);
7840            mActivities.removeActivity(a, "activity");
7841            if (DEBUG_REMOVE && chatty) {
7842                if (r == null) {
7843                    r = new StringBuilder(256);
7844                } else {
7845                    r.append(' ');
7846                }
7847                r.append(a.info.name);
7848            }
7849        }
7850        if (r != null) {
7851            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7852        }
7853
7854        N = pkg.permissions.size();
7855        r = null;
7856        for (i=0; i<N; i++) {
7857            PackageParser.Permission p = pkg.permissions.get(i);
7858            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7859            if (bp == null) {
7860                bp = mSettings.mPermissionTrees.get(p.info.name);
7861            }
7862            if (bp != null && bp.perm == p) {
7863                bp.perm = null;
7864                if (DEBUG_REMOVE && chatty) {
7865                    if (r == null) {
7866                        r = new StringBuilder(256);
7867                    } else {
7868                        r.append(' ');
7869                    }
7870                    r.append(p.info.name);
7871                }
7872            }
7873            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7874                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7875                if (appOpPerms != null) {
7876                    appOpPerms.remove(pkg.packageName);
7877                }
7878            }
7879        }
7880        if (r != null) {
7881            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7882        }
7883
7884        N = pkg.requestedPermissions.size();
7885        r = null;
7886        for (i=0; i<N; i++) {
7887            String perm = pkg.requestedPermissions.get(i);
7888            BasePermission bp = mSettings.mPermissions.get(perm);
7889            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7890                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7891                if (appOpPerms != null) {
7892                    appOpPerms.remove(pkg.packageName);
7893                    if (appOpPerms.isEmpty()) {
7894                        mAppOpPermissionPackages.remove(perm);
7895                    }
7896                }
7897            }
7898        }
7899        if (r != null) {
7900            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7901        }
7902
7903        N = pkg.instrumentation.size();
7904        r = null;
7905        for (i=0; i<N; i++) {
7906            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7907            mInstrumentation.remove(a.getComponentName());
7908            if (DEBUG_REMOVE && chatty) {
7909                if (r == null) {
7910                    r = new StringBuilder(256);
7911                } else {
7912                    r.append(' ');
7913                }
7914                r.append(a.info.name);
7915            }
7916        }
7917        if (r != null) {
7918            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7919        }
7920
7921        r = null;
7922        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7923            // Only system apps can hold shared libraries.
7924            if (pkg.libraryNames != null) {
7925                for (i=0; i<pkg.libraryNames.size(); i++) {
7926                    String name = pkg.libraryNames.get(i);
7927                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7928                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7929                        mSharedLibraries.remove(name);
7930                        if (DEBUG_REMOVE && chatty) {
7931                            if (r == null) {
7932                                r = new StringBuilder(256);
7933                            } else {
7934                                r.append(' ');
7935                            }
7936                            r.append(name);
7937                        }
7938                    }
7939                }
7940            }
7941        }
7942        if (r != null) {
7943            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7944        }
7945    }
7946
7947    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7948        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7949            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7950                return true;
7951            }
7952        }
7953        return false;
7954    }
7955
7956    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7957    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7958    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7959
7960    private void updatePermissionsLPw(String changingPkg,
7961            PackageParser.Package pkgInfo, int flags) {
7962        // Make sure there are no dangling permission trees.
7963        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7964        while (it.hasNext()) {
7965            final BasePermission bp = it.next();
7966            if (bp.packageSetting == null) {
7967                // We may not yet have parsed the package, so just see if
7968                // we still know about its settings.
7969                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7970            }
7971            if (bp.packageSetting == null) {
7972                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7973                        + " from package " + bp.sourcePackage);
7974                it.remove();
7975            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7976                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7977                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7978                            + " from package " + bp.sourcePackage);
7979                    flags |= UPDATE_PERMISSIONS_ALL;
7980                    it.remove();
7981                }
7982            }
7983        }
7984
7985        // Make sure all dynamic permissions have been assigned to a package,
7986        // and make sure there are no dangling permissions.
7987        it = mSettings.mPermissions.values().iterator();
7988        while (it.hasNext()) {
7989            final BasePermission bp = it.next();
7990            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7991                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7992                        + bp.name + " pkg=" + bp.sourcePackage
7993                        + " info=" + bp.pendingInfo);
7994                if (bp.packageSetting == null && bp.pendingInfo != null) {
7995                    final BasePermission tree = findPermissionTreeLP(bp.name);
7996                    if (tree != null && tree.perm != null) {
7997                        bp.packageSetting = tree.packageSetting;
7998                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7999                                new PermissionInfo(bp.pendingInfo));
8000                        bp.perm.info.packageName = tree.perm.info.packageName;
8001                        bp.perm.info.name = bp.name;
8002                        bp.uid = tree.uid;
8003                    }
8004                }
8005            }
8006            if (bp.packageSetting == null) {
8007                // We may not yet have parsed the package, so just see if
8008                // we still know about its settings.
8009                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8010            }
8011            if (bp.packageSetting == null) {
8012                Slog.w(TAG, "Removing dangling permission: " + bp.name
8013                        + " from package " + bp.sourcePackage);
8014                it.remove();
8015            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8016                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8017                    Slog.i(TAG, "Removing old permission: " + bp.name
8018                            + " from package " + bp.sourcePackage);
8019                    flags |= UPDATE_PERMISSIONS_ALL;
8020                    it.remove();
8021                }
8022            }
8023        }
8024
8025        // Now update the permissions for all packages, in particular
8026        // replace the granted permissions of the system packages.
8027        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8028            for (PackageParser.Package pkg : mPackages.values()) {
8029                if (pkg != pkgInfo) {
8030                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8031                            changingPkg);
8032                }
8033            }
8034        }
8035
8036        if (pkgInfo != null) {
8037            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8038        }
8039    }
8040
8041    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8042            String packageOfInterest) {
8043        // IMPORTANT: There are two types of permissions: install and runtime.
8044        // Install time permissions are granted when the app is installed to
8045        // all device users and users added in the future. Runtime permissions
8046        // are granted at runtime explicitly to specific users. Normal and signature
8047        // protected permissions are install time permissions. Dangerous permissions
8048        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8049        // otherwise they are runtime permissions. This function does not manage
8050        // runtime permissions except for the case an app targeting Lollipop MR1
8051        // being upgraded to target a newer SDK, in which case dangerous permissions
8052        // are transformed from install time to runtime ones.
8053
8054        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8055        if (ps == null) {
8056            return;
8057        }
8058
8059        PermissionsState permissionsState = ps.getPermissionsState();
8060        PermissionsState origPermissions = permissionsState;
8061
8062        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8063
8064        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8065
8066        boolean changedInstallPermission = false;
8067
8068        if (replace) {
8069            ps.installPermissionsFixed = false;
8070            if (!ps.isSharedUser()) {
8071                origPermissions = new PermissionsState(permissionsState);
8072                permissionsState.reset();
8073            }
8074        }
8075
8076        permissionsState.setGlobalGids(mGlobalGids);
8077
8078        final int N = pkg.requestedPermissions.size();
8079        for (int i=0; i<N; i++) {
8080            final String name = pkg.requestedPermissions.get(i);
8081            final BasePermission bp = mSettings.mPermissions.get(name);
8082
8083            if (DEBUG_INSTALL) {
8084                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8085            }
8086
8087            if (bp == null || bp.packageSetting == null) {
8088                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8089                    Slog.w(TAG, "Unknown permission " + name
8090                            + " in package " + pkg.packageName);
8091                }
8092                continue;
8093            }
8094
8095            final String perm = bp.name;
8096            boolean allowedSig = false;
8097            int grant = GRANT_DENIED;
8098
8099            // Keep track of app op permissions.
8100            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8101                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8102                if (pkgs == null) {
8103                    pkgs = new ArraySet<>();
8104                    mAppOpPermissionPackages.put(bp.name, pkgs);
8105                }
8106                pkgs.add(pkg.packageName);
8107            }
8108
8109            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8110            switch (level) {
8111                case PermissionInfo.PROTECTION_NORMAL: {
8112                    // For all apps normal permissions are install time ones.
8113                    grant = GRANT_INSTALL;
8114                } break;
8115
8116                case PermissionInfo.PROTECTION_DANGEROUS: {
8117                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8118                        // For legacy apps dangerous permissions are install time ones.
8119                        grant = GRANT_INSTALL_LEGACY;
8120                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8121                        // For legacy apps that became modern, install becomes runtime.
8122                        grant = GRANT_UPGRADE;
8123                    } else {
8124                        // For modern apps keep runtime permissions unchanged.
8125                        grant = GRANT_RUNTIME;
8126                    }
8127                } break;
8128
8129                case PermissionInfo.PROTECTION_SIGNATURE: {
8130                    // For all apps signature permissions are install time ones.
8131                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8132                    if (allowedSig) {
8133                        grant = GRANT_INSTALL;
8134                    }
8135                } break;
8136            }
8137
8138            if (DEBUG_INSTALL) {
8139                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8140            }
8141
8142            if (grant != GRANT_DENIED) {
8143                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8144                    // If this is an existing, non-system package, then
8145                    // we can't add any new permissions to it.
8146                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8147                        // Except...  if this is a permission that was added
8148                        // to the platform (note: need to only do this when
8149                        // updating the platform).
8150                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8151                            grant = GRANT_DENIED;
8152                        }
8153                    }
8154                }
8155
8156                switch (grant) {
8157                    case GRANT_INSTALL: {
8158                        // Revoke this as runtime permission to handle the case of
8159                        // a runtime permission being downgraded to an install one.
8160                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8161                            if (origPermissions.getRuntimePermissionState(
8162                                    bp.name, userId) != null) {
8163                                // Revoke the runtime permission and clear the flags.
8164                                origPermissions.revokeRuntimePermission(bp, userId);
8165                                origPermissions.updatePermissionFlags(bp, userId,
8166                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8167                                // If we revoked a permission permission, we have to write.
8168                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8169                                        changedRuntimePermissionUserIds, userId);
8170                            }
8171                        }
8172                        // Grant an install permission.
8173                        if (permissionsState.grantInstallPermission(bp) !=
8174                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8175                            changedInstallPermission = true;
8176                        }
8177                    } break;
8178
8179                    case GRANT_INSTALL_LEGACY: {
8180                        // Grant an install permission.
8181                        if (permissionsState.grantInstallPermission(bp) !=
8182                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8183                            changedInstallPermission = true;
8184                        }
8185                    } break;
8186
8187                    case GRANT_RUNTIME: {
8188                        // Grant previously granted runtime permissions.
8189                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8190                            PermissionState permissionState = origPermissions
8191                                    .getRuntimePermissionState(bp.name, userId);
8192                            final int flags = permissionState != null
8193                                    ? permissionState.getFlags() : 0;
8194                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8195                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8196                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8197                                    // If we cannot put the permission as it was, we have to write.
8198                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8199                                            changedRuntimePermissionUserIds, userId);
8200                                }
8201                            }
8202                            // Propagate the permission flags.
8203                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8204                        }
8205                    } break;
8206
8207                    case GRANT_UPGRADE: {
8208                        // Grant runtime permissions for a previously held install permission.
8209                        PermissionState permissionState = origPermissions
8210                                .getInstallPermissionState(bp.name);
8211                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8212
8213                        if (origPermissions.revokeInstallPermission(bp)
8214                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8215                            // We will be transferring the permission flags, so clear them.
8216                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8217                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8218                            changedInstallPermission = true;
8219                        }
8220
8221                        // If the permission is not to be promoted to runtime we ignore it and
8222                        // also its other flags as they are not applicable to install permissions.
8223                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8224                            for (int userId : currentUserIds) {
8225                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8226                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8227                                    // Transfer the permission flags.
8228                                    permissionsState.updatePermissionFlags(bp, userId,
8229                                            flags, flags);
8230                                    // If we granted the permission, we have to write.
8231                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8232                                            changedRuntimePermissionUserIds, userId);
8233                                }
8234                            }
8235                        }
8236                    } break;
8237
8238                    default: {
8239                        if (packageOfInterest == null
8240                                || packageOfInterest.equals(pkg.packageName)) {
8241                            Slog.w(TAG, "Not granting permission " + perm
8242                                    + " to package " + pkg.packageName
8243                                    + " because it was previously installed without");
8244                        }
8245                    } break;
8246                }
8247            } else {
8248                if (permissionsState.revokeInstallPermission(bp) !=
8249                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8250                    // Also drop the permission flags.
8251                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8252                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8253                    changedInstallPermission = true;
8254                    Slog.i(TAG, "Un-granting permission " + perm
8255                            + " from package " + pkg.packageName
8256                            + " (protectionLevel=" + bp.protectionLevel
8257                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8258                            + ")");
8259                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8260                    // Don't print warning for app op permissions, since it is fine for them
8261                    // not to be granted, there is a UI for the user to decide.
8262                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8263                        Slog.w(TAG, "Not granting permission " + perm
8264                                + " to package " + pkg.packageName
8265                                + " (protectionLevel=" + bp.protectionLevel
8266                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8267                                + ")");
8268                    }
8269                }
8270            }
8271        }
8272
8273        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8274                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8275            // This is the first that we have heard about this package, so the
8276            // permissions we have now selected are fixed until explicitly
8277            // changed.
8278            ps.installPermissionsFixed = true;
8279        }
8280
8281        // Persist the runtime permissions state for users with changes.
8282        for (int userId : changedRuntimePermissionUserIds) {
8283            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8284        }
8285    }
8286
8287    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8288        boolean allowed = false;
8289        final int NP = PackageParser.NEW_PERMISSIONS.length;
8290        for (int ip=0; ip<NP; ip++) {
8291            final PackageParser.NewPermissionInfo npi
8292                    = PackageParser.NEW_PERMISSIONS[ip];
8293            if (npi.name.equals(perm)
8294                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8295                allowed = true;
8296                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8297                        + pkg.packageName);
8298                break;
8299            }
8300        }
8301        return allowed;
8302    }
8303
8304    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8305            BasePermission bp, PermissionsState origPermissions) {
8306        boolean allowed;
8307        allowed = (compareSignatures(
8308                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8309                        == PackageManager.SIGNATURE_MATCH)
8310                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8311                        == PackageManager.SIGNATURE_MATCH);
8312        if (!allowed && (bp.protectionLevel
8313                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8314            if (isSystemApp(pkg)) {
8315                // For updated system applications, a system permission
8316                // is granted only if it had been defined by the original application.
8317                if (pkg.isUpdatedSystemApp()) {
8318                    final PackageSetting sysPs = mSettings
8319                            .getDisabledSystemPkgLPr(pkg.packageName);
8320                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8321                        // If the original was granted this permission, we take
8322                        // that grant decision as read and propagate it to the
8323                        // update.
8324                        if (sysPs.isPrivileged()) {
8325                            allowed = true;
8326                        }
8327                    } else {
8328                        // The system apk may have been updated with an older
8329                        // version of the one on the data partition, but which
8330                        // granted a new system permission that it didn't have
8331                        // before.  In this case we do want to allow the app to
8332                        // now get the new permission if the ancestral apk is
8333                        // privileged to get it.
8334                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8335                            for (int j=0;
8336                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8337                                if (perm.equals(
8338                                        sysPs.pkg.requestedPermissions.get(j))) {
8339                                    allowed = true;
8340                                    break;
8341                                }
8342                            }
8343                        }
8344                    }
8345                } else {
8346                    allowed = isPrivilegedApp(pkg);
8347                }
8348            }
8349        }
8350        if (!allowed && (bp.protectionLevel
8351                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8352            // For development permissions, a development permission
8353            // is granted only if it was already granted.
8354            allowed = origPermissions.hasInstallPermission(perm);
8355        }
8356        return allowed;
8357    }
8358
8359    final class ActivityIntentResolver
8360            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8361        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8362                boolean defaultOnly, int userId) {
8363            if (!sUserManager.exists(userId)) return null;
8364            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8365            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8366        }
8367
8368        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8369                int userId) {
8370            if (!sUserManager.exists(userId)) return null;
8371            mFlags = flags;
8372            return super.queryIntent(intent, resolvedType,
8373                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8374        }
8375
8376        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8377                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8378            if (!sUserManager.exists(userId)) return null;
8379            if (packageActivities == null) {
8380                return null;
8381            }
8382            mFlags = flags;
8383            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8384            final int N = packageActivities.size();
8385            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8386                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8387
8388            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8389            for (int i = 0; i < N; ++i) {
8390                intentFilters = packageActivities.get(i).intents;
8391                if (intentFilters != null && intentFilters.size() > 0) {
8392                    PackageParser.ActivityIntentInfo[] array =
8393                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8394                    intentFilters.toArray(array);
8395                    listCut.add(array);
8396                }
8397            }
8398            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8399        }
8400
8401        public final void addActivity(PackageParser.Activity a, String type) {
8402            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8403            mActivities.put(a.getComponentName(), a);
8404            if (DEBUG_SHOW_INFO)
8405                Log.v(
8406                TAG, "  " + type + " " +
8407                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8408            if (DEBUG_SHOW_INFO)
8409                Log.v(TAG, "    Class=" + a.info.name);
8410            final int NI = a.intents.size();
8411            for (int j=0; j<NI; j++) {
8412                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8413                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8414                    intent.setPriority(0);
8415                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8416                            + a.className + " with priority > 0, forcing to 0");
8417                }
8418                if (DEBUG_SHOW_INFO) {
8419                    Log.v(TAG, "    IntentFilter:");
8420                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8421                }
8422                if (!intent.debugCheck()) {
8423                    Log.w(TAG, "==> For Activity " + a.info.name);
8424                }
8425                addFilter(intent);
8426            }
8427        }
8428
8429        public final void removeActivity(PackageParser.Activity a, String type) {
8430            mActivities.remove(a.getComponentName());
8431            if (DEBUG_SHOW_INFO) {
8432                Log.v(TAG, "  " + type + " "
8433                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8434                                : a.info.name) + ":");
8435                Log.v(TAG, "    Class=" + a.info.name);
8436            }
8437            final int NI = a.intents.size();
8438            for (int j=0; j<NI; j++) {
8439                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8440                if (DEBUG_SHOW_INFO) {
8441                    Log.v(TAG, "    IntentFilter:");
8442                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8443                }
8444                removeFilter(intent);
8445            }
8446        }
8447
8448        @Override
8449        protected boolean allowFilterResult(
8450                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8451            ActivityInfo filterAi = filter.activity.info;
8452            for (int i=dest.size()-1; i>=0; i--) {
8453                ActivityInfo destAi = dest.get(i).activityInfo;
8454                if (destAi.name == filterAi.name
8455                        && destAi.packageName == filterAi.packageName) {
8456                    return false;
8457                }
8458            }
8459            return true;
8460        }
8461
8462        @Override
8463        protected ActivityIntentInfo[] newArray(int size) {
8464            return new ActivityIntentInfo[size];
8465        }
8466
8467        @Override
8468        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8469            if (!sUserManager.exists(userId)) return true;
8470            PackageParser.Package p = filter.activity.owner;
8471            if (p != null) {
8472                PackageSetting ps = (PackageSetting)p.mExtras;
8473                if (ps != null) {
8474                    // System apps are never considered stopped for purposes of
8475                    // filtering, because there may be no way for the user to
8476                    // actually re-launch them.
8477                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8478                            && ps.getStopped(userId);
8479                }
8480            }
8481            return false;
8482        }
8483
8484        @Override
8485        protected boolean isPackageForFilter(String packageName,
8486                PackageParser.ActivityIntentInfo info) {
8487            return packageName.equals(info.activity.owner.packageName);
8488        }
8489
8490        @Override
8491        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8492                int match, int userId) {
8493            if (!sUserManager.exists(userId)) return null;
8494            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8495                return null;
8496            }
8497            final PackageParser.Activity activity = info.activity;
8498            if (mSafeMode && (activity.info.applicationInfo.flags
8499                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8500                return null;
8501            }
8502            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8503            if (ps == null) {
8504                return null;
8505            }
8506            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8507                    ps.readUserState(userId), userId);
8508            if (ai == null) {
8509                return null;
8510            }
8511            final ResolveInfo res = new ResolveInfo();
8512            res.activityInfo = ai;
8513            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8514                res.filter = info;
8515            }
8516            if (info != null) {
8517                res.handleAllWebDataURI = info.handleAllWebDataURI();
8518            }
8519            res.priority = info.getPriority();
8520            res.preferredOrder = activity.owner.mPreferredOrder;
8521            //System.out.println("Result: " + res.activityInfo.className +
8522            //                   " = " + res.priority);
8523            res.match = match;
8524            res.isDefault = info.hasDefault;
8525            res.labelRes = info.labelRes;
8526            res.nonLocalizedLabel = info.nonLocalizedLabel;
8527            if (userNeedsBadging(userId)) {
8528                res.noResourceId = true;
8529            } else {
8530                res.icon = info.icon;
8531            }
8532            res.iconResourceId = info.icon;
8533            res.system = res.activityInfo.applicationInfo.isSystemApp();
8534            return res;
8535        }
8536
8537        @Override
8538        protected void sortResults(List<ResolveInfo> results) {
8539            Collections.sort(results, mResolvePrioritySorter);
8540        }
8541
8542        @Override
8543        protected void dumpFilter(PrintWriter out, String prefix,
8544                PackageParser.ActivityIntentInfo filter) {
8545            out.print(prefix); out.print(
8546                    Integer.toHexString(System.identityHashCode(filter.activity)));
8547                    out.print(' ');
8548                    filter.activity.printComponentShortName(out);
8549                    out.print(" filter ");
8550                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8551        }
8552
8553        @Override
8554        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8555            return filter.activity;
8556        }
8557
8558        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8559            PackageParser.Activity activity = (PackageParser.Activity)label;
8560            out.print(prefix); out.print(
8561                    Integer.toHexString(System.identityHashCode(activity)));
8562                    out.print(' ');
8563                    activity.printComponentShortName(out);
8564            if (count > 1) {
8565                out.print(" ("); out.print(count); out.print(" filters)");
8566            }
8567            out.println();
8568        }
8569
8570//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8571//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8572//            final List<ResolveInfo> retList = Lists.newArrayList();
8573//            while (i.hasNext()) {
8574//                final ResolveInfo resolveInfo = i.next();
8575//                if (isEnabledLP(resolveInfo.activityInfo)) {
8576//                    retList.add(resolveInfo);
8577//                }
8578//            }
8579//            return retList;
8580//        }
8581
8582        // Keys are String (activity class name), values are Activity.
8583        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8584                = new ArrayMap<ComponentName, PackageParser.Activity>();
8585        private int mFlags;
8586    }
8587
8588    private final class ServiceIntentResolver
8589            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8590        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8591                boolean defaultOnly, int userId) {
8592            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8593            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8594        }
8595
8596        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8597                int userId) {
8598            if (!sUserManager.exists(userId)) return null;
8599            mFlags = flags;
8600            return super.queryIntent(intent, resolvedType,
8601                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8602        }
8603
8604        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8605                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8606            if (!sUserManager.exists(userId)) return null;
8607            if (packageServices == null) {
8608                return null;
8609            }
8610            mFlags = flags;
8611            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8612            final int N = packageServices.size();
8613            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8614                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8615
8616            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8617            for (int i = 0; i < N; ++i) {
8618                intentFilters = packageServices.get(i).intents;
8619                if (intentFilters != null && intentFilters.size() > 0) {
8620                    PackageParser.ServiceIntentInfo[] array =
8621                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8622                    intentFilters.toArray(array);
8623                    listCut.add(array);
8624                }
8625            }
8626            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8627        }
8628
8629        public final void addService(PackageParser.Service s) {
8630            mServices.put(s.getComponentName(), s);
8631            if (DEBUG_SHOW_INFO) {
8632                Log.v(TAG, "  "
8633                        + (s.info.nonLocalizedLabel != null
8634                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8635                Log.v(TAG, "    Class=" + s.info.name);
8636            }
8637            final int NI = s.intents.size();
8638            int j;
8639            for (j=0; j<NI; j++) {
8640                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8641                if (DEBUG_SHOW_INFO) {
8642                    Log.v(TAG, "    IntentFilter:");
8643                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8644                }
8645                if (!intent.debugCheck()) {
8646                    Log.w(TAG, "==> For Service " + s.info.name);
8647                }
8648                addFilter(intent);
8649            }
8650        }
8651
8652        public final void removeService(PackageParser.Service s) {
8653            mServices.remove(s.getComponentName());
8654            if (DEBUG_SHOW_INFO) {
8655                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8656                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8657                Log.v(TAG, "    Class=" + s.info.name);
8658            }
8659            final int NI = s.intents.size();
8660            int j;
8661            for (j=0; j<NI; j++) {
8662                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8663                if (DEBUG_SHOW_INFO) {
8664                    Log.v(TAG, "    IntentFilter:");
8665                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8666                }
8667                removeFilter(intent);
8668            }
8669        }
8670
8671        @Override
8672        protected boolean allowFilterResult(
8673                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8674            ServiceInfo filterSi = filter.service.info;
8675            for (int i=dest.size()-1; i>=0; i--) {
8676                ServiceInfo destAi = dest.get(i).serviceInfo;
8677                if (destAi.name == filterSi.name
8678                        && destAi.packageName == filterSi.packageName) {
8679                    return false;
8680                }
8681            }
8682            return true;
8683        }
8684
8685        @Override
8686        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8687            return new PackageParser.ServiceIntentInfo[size];
8688        }
8689
8690        @Override
8691        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8692            if (!sUserManager.exists(userId)) return true;
8693            PackageParser.Package p = filter.service.owner;
8694            if (p != null) {
8695                PackageSetting ps = (PackageSetting)p.mExtras;
8696                if (ps != null) {
8697                    // System apps are never considered stopped for purposes of
8698                    // filtering, because there may be no way for the user to
8699                    // actually re-launch them.
8700                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8701                            && ps.getStopped(userId);
8702                }
8703            }
8704            return false;
8705        }
8706
8707        @Override
8708        protected boolean isPackageForFilter(String packageName,
8709                PackageParser.ServiceIntentInfo info) {
8710            return packageName.equals(info.service.owner.packageName);
8711        }
8712
8713        @Override
8714        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8715                int match, int userId) {
8716            if (!sUserManager.exists(userId)) return null;
8717            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8718            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8719                return null;
8720            }
8721            final PackageParser.Service service = info.service;
8722            if (mSafeMode && (service.info.applicationInfo.flags
8723                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8724                return null;
8725            }
8726            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8727            if (ps == null) {
8728                return null;
8729            }
8730            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8731                    ps.readUserState(userId), userId);
8732            if (si == null) {
8733                return null;
8734            }
8735            final ResolveInfo res = new ResolveInfo();
8736            res.serviceInfo = si;
8737            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8738                res.filter = filter;
8739            }
8740            res.priority = info.getPriority();
8741            res.preferredOrder = service.owner.mPreferredOrder;
8742            res.match = match;
8743            res.isDefault = info.hasDefault;
8744            res.labelRes = info.labelRes;
8745            res.nonLocalizedLabel = info.nonLocalizedLabel;
8746            res.icon = info.icon;
8747            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8748            return res;
8749        }
8750
8751        @Override
8752        protected void sortResults(List<ResolveInfo> results) {
8753            Collections.sort(results, mResolvePrioritySorter);
8754        }
8755
8756        @Override
8757        protected void dumpFilter(PrintWriter out, String prefix,
8758                PackageParser.ServiceIntentInfo filter) {
8759            out.print(prefix); out.print(
8760                    Integer.toHexString(System.identityHashCode(filter.service)));
8761                    out.print(' ');
8762                    filter.service.printComponentShortName(out);
8763                    out.print(" filter ");
8764                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8765        }
8766
8767        @Override
8768        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8769            return filter.service;
8770        }
8771
8772        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8773            PackageParser.Service service = (PackageParser.Service)label;
8774            out.print(prefix); out.print(
8775                    Integer.toHexString(System.identityHashCode(service)));
8776                    out.print(' ');
8777                    service.printComponentShortName(out);
8778            if (count > 1) {
8779                out.print(" ("); out.print(count); out.print(" filters)");
8780            }
8781            out.println();
8782        }
8783
8784//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8785//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8786//            final List<ResolveInfo> retList = Lists.newArrayList();
8787//            while (i.hasNext()) {
8788//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8789//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8790//                    retList.add(resolveInfo);
8791//                }
8792//            }
8793//            return retList;
8794//        }
8795
8796        // Keys are String (activity class name), values are Activity.
8797        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8798                = new ArrayMap<ComponentName, PackageParser.Service>();
8799        private int mFlags;
8800    };
8801
8802    private final class ProviderIntentResolver
8803            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8804        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8805                boolean defaultOnly, int userId) {
8806            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8807            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8808        }
8809
8810        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8811                int userId) {
8812            if (!sUserManager.exists(userId))
8813                return null;
8814            mFlags = flags;
8815            return super.queryIntent(intent, resolvedType,
8816                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8817        }
8818
8819        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8820                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8821            if (!sUserManager.exists(userId))
8822                return null;
8823            if (packageProviders == null) {
8824                return null;
8825            }
8826            mFlags = flags;
8827            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8828            final int N = packageProviders.size();
8829            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8830                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8831
8832            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8833            for (int i = 0; i < N; ++i) {
8834                intentFilters = packageProviders.get(i).intents;
8835                if (intentFilters != null && intentFilters.size() > 0) {
8836                    PackageParser.ProviderIntentInfo[] array =
8837                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8838                    intentFilters.toArray(array);
8839                    listCut.add(array);
8840                }
8841            }
8842            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8843        }
8844
8845        public final void addProvider(PackageParser.Provider p) {
8846            if (mProviders.containsKey(p.getComponentName())) {
8847                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8848                return;
8849            }
8850
8851            mProviders.put(p.getComponentName(), p);
8852            if (DEBUG_SHOW_INFO) {
8853                Log.v(TAG, "  "
8854                        + (p.info.nonLocalizedLabel != null
8855                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8856                Log.v(TAG, "    Class=" + p.info.name);
8857            }
8858            final int NI = p.intents.size();
8859            int j;
8860            for (j = 0; j < NI; j++) {
8861                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8862                if (DEBUG_SHOW_INFO) {
8863                    Log.v(TAG, "    IntentFilter:");
8864                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8865                }
8866                if (!intent.debugCheck()) {
8867                    Log.w(TAG, "==> For Provider " + p.info.name);
8868                }
8869                addFilter(intent);
8870            }
8871        }
8872
8873        public final void removeProvider(PackageParser.Provider p) {
8874            mProviders.remove(p.getComponentName());
8875            if (DEBUG_SHOW_INFO) {
8876                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8877                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8878                Log.v(TAG, "    Class=" + p.info.name);
8879            }
8880            final int NI = p.intents.size();
8881            int j;
8882            for (j = 0; j < NI; j++) {
8883                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8884                if (DEBUG_SHOW_INFO) {
8885                    Log.v(TAG, "    IntentFilter:");
8886                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8887                }
8888                removeFilter(intent);
8889            }
8890        }
8891
8892        @Override
8893        protected boolean allowFilterResult(
8894                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8895            ProviderInfo filterPi = filter.provider.info;
8896            for (int i = dest.size() - 1; i >= 0; i--) {
8897                ProviderInfo destPi = dest.get(i).providerInfo;
8898                if (destPi.name == filterPi.name
8899                        && destPi.packageName == filterPi.packageName) {
8900                    return false;
8901                }
8902            }
8903            return true;
8904        }
8905
8906        @Override
8907        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8908            return new PackageParser.ProviderIntentInfo[size];
8909        }
8910
8911        @Override
8912        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8913            if (!sUserManager.exists(userId))
8914                return true;
8915            PackageParser.Package p = filter.provider.owner;
8916            if (p != null) {
8917                PackageSetting ps = (PackageSetting) p.mExtras;
8918                if (ps != null) {
8919                    // System apps are never considered stopped for purposes of
8920                    // filtering, because there may be no way for the user to
8921                    // actually re-launch them.
8922                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8923                            && ps.getStopped(userId);
8924                }
8925            }
8926            return false;
8927        }
8928
8929        @Override
8930        protected boolean isPackageForFilter(String packageName,
8931                PackageParser.ProviderIntentInfo info) {
8932            return packageName.equals(info.provider.owner.packageName);
8933        }
8934
8935        @Override
8936        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8937                int match, int userId) {
8938            if (!sUserManager.exists(userId))
8939                return null;
8940            final PackageParser.ProviderIntentInfo info = filter;
8941            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8942                return null;
8943            }
8944            final PackageParser.Provider provider = info.provider;
8945            if (mSafeMode && (provider.info.applicationInfo.flags
8946                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8947                return null;
8948            }
8949            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8950            if (ps == null) {
8951                return null;
8952            }
8953            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8954                    ps.readUserState(userId), userId);
8955            if (pi == null) {
8956                return null;
8957            }
8958            final ResolveInfo res = new ResolveInfo();
8959            res.providerInfo = pi;
8960            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8961                res.filter = filter;
8962            }
8963            res.priority = info.getPriority();
8964            res.preferredOrder = provider.owner.mPreferredOrder;
8965            res.match = match;
8966            res.isDefault = info.hasDefault;
8967            res.labelRes = info.labelRes;
8968            res.nonLocalizedLabel = info.nonLocalizedLabel;
8969            res.icon = info.icon;
8970            res.system = res.providerInfo.applicationInfo.isSystemApp();
8971            return res;
8972        }
8973
8974        @Override
8975        protected void sortResults(List<ResolveInfo> results) {
8976            Collections.sort(results, mResolvePrioritySorter);
8977        }
8978
8979        @Override
8980        protected void dumpFilter(PrintWriter out, String prefix,
8981                PackageParser.ProviderIntentInfo filter) {
8982            out.print(prefix);
8983            out.print(
8984                    Integer.toHexString(System.identityHashCode(filter.provider)));
8985            out.print(' ');
8986            filter.provider.printComponentShortName(out);
8987            out.print(" filter ");
8988            out.println(Integer.toHexString(System.identityHashCode(filter)));
8989        }
8990
8991        @Override
8992        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8993            return filter.provider;
8994        }
8995
8996        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8997            PackageParser.Provider provider = (PackageParser.Provider)label;
8998            out.print(prefix); out.print(
8999                    Integer.toHexString(System.identityHashCode(provider)));
9000                    out.print(' ');
9001                    provider.printComponentShortName(out);
9002            if (count > 1) {
9003                out.print(" ("); out.print(count); out.print(" filters)");
9004            }
9005            out.println();
9006        }
9007
9008        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9009                = new ArrayMap<ComponentName, PackageParser.Provider>();
9010        private int mFlags;
9011    };
9012
9013    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9014            new Comparator<ResolveInfo>() {
9015        public int compare(ResolveInfo r1, ResolveInfo r2) {
9016            int v1 = r1.priority;
9017            int v2 = r2.priority;
9018            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9019            if (v1 != v2) {
9020                return (v1 > v2) ? -1 : 1;
9021            }
9022            v1 = r1.preferredOrder;
9023            v2 = r2.preferredOrder;
9024            if (v1 != v2) {
9025                return (v1 > v2) ? -1 : 1;
9026            }
9027            if (r1.isDefault != r2.isDefault) {
9028                return r1.isDefault ? -1 : 1;
9029            }
9030            v1 = r1.match;
9031            v2 = r2.match;
9032            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9033            if (v1 != v2) {
9034                return (v1 > v2) ? -1 : 1;
9035            }
9036            if (r1.system != r2.system) {
9037                return r1.system ? -1 : 1;
9038            }
9039            return 0;
9040        }
9041    };
9042
9043    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9044            new Comparator<ProviderInfo>() {
9045        public int compare(ProviderInfo p1, ProviderInfo p2) {
9046            final int v1 = p1.initOrder;
9047            final int v2 = p2.initOrder;
9048            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9049        }
9050    };
9051
9052    final void sendPackageBroadcast(final String action, final String pkg,
9053            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9054            final int[] userIds) {
9055        mHandler.post(new Runnable() {
9056            @Override
9057            public void run() {
9058                try {
9059                    final IActivityManager am = ActivityManagerNative.getDefault();
9060                    if (am == null) return;
9061                    final int[] resolvedUserIds;
9062                    if (userIds == null) {
9063                        resolvedUserIds = am.getRunningUserIds();
9064                    } else {
9065                        resolvedUserIds = userIds;
9066                    }
9067                    for (int id : resolvedUserIds) {
9068                        final Intent intent = new Intent(action,
9069                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9070                        if (extras != null) {
9071                            intent.putExtras(extras);
9072                        }
9073                        if (targetPkg != null) {
9074                            intent.setPackage(targetPkg);
9075                        }
9076                        // Modify the UID when posting to other users
9077                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9078                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9079                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9080                            intent.putExtra(Intent.EXTRA_UID, uid);
9081                        }
9082                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9083                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9084                        if (DEBUG_BROADCASTS) {
9085                            RuntimeException here = new RuntimeException("here");
9086                            here.fillInStackTrace();
9087                            Slog.d(TAG, "Sending to user " + id + ": "
9088                                    + intent.toShortString(false, true, false, false)
9089                                    + " " + intent.getExtras(), here);
9090                        }
9091                        am.broadcastIntent(null, intent, null, finishedReceiver,
9092                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9093                                null, finishedReceiver != null, false, id);
9094                    }
9095                } catch (RemoteException ex) {
9096                }
9097            }
9098        });
9099    }
9100
9101    /**
9102     * Check if the external storage media is available. This is true if there
9103     * is a mounted external storage medium or if the external storage is
9104     * emulated.
9105     */
9106    private boolean isExternalMediaAvailable() {
9107        return mMediaMounted || Environment.isExternalStorageEmulated();
9108    }
9109
9110    @Override
9111    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9112        // writer
9113        synchronized (mPackages) {
9114            if (!isExternalMediaAvailable()) {
9115                // If the external storage is no longer mounted at this point,
9116                // the caller may not have been able to delete all of this
9117                // packages files and can not delete any more.  Bail.
9118                return null;
9119            }
9120            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9121            if (lastPackage != null) {
9122                pkgs.remove(lastPackage);
9123            }
9124            if (pkgs.size() > 0) {
9125                return pkgs.get(0);
9126            }
9127        }
9128        return null;
9129    }
9130
9131    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9132        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9133                userId, andCode ? 1 : 0, packageName);
9134        if (mSystemReady) {
9135            msg.sendToTarget();
9136        } else {
9137            if (mPostSystemReadyMessages == null) {
9138                mPostSystemReadyMessages = new ArrayList<>();
9139            }
9140            mPostSystemReadyMessages.add(msg);
9141        }
9142    }
9143
9144    void startCleaningPackages() {
9145        // reader
9146        synchronized (mPackages) {
9147            if (!isExternalMediaAvailable()) {
9148                return;
9149            }
9150            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9151                return;
9152            }
9153        }
9154        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9155        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9156        IActivityManager am = ActivityManagerNative.getDefault();
9157        if (am != null) {
9158            try {
9159                am.startService(null, intent, null, UserHandle.USER_OWNER);
9160            } catch (RemoteException e) {
9161            }
9162        }
9163    }
9164
9165    @Override
9166    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9167            int installFlags, String installerPackageName, VerificationParams verificationParams,
9168            String packageAbiOverride) {
9169        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9170                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9171    }
9172
9173    @Override
9174    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9175            int installFlags, String installerPackageName, VerificationParams verificationParams,
9176            String packageAbiOverride, int userId) {
9177        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9178
9179        final int callingUid = Binder.getCallingUid();
9180        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9181
9182        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9183            try {
9184                if (observer != null) {
9185                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9186                }
9187            } catch (RemoteException re) {
9188            }
9189            return;
9190        }
9191
9192        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9193            installFlags |= PackageManager.INSTALL_FROM_ADB;
9194
9195        } else {
9196            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9197            // about installerPackageName.
9198
9199            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9200            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9201        }
9202
9203        UserHandle user;
9204        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9205            user = UserHandle.ALL;
9206        } else {
9207            user = new UserHandle(userId);
9208        }
9209
9210        // Only system components can circumvent runtime permissions when installing.
9211        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9212                && mContext.checkCallingOrSelfPermission(Manifest.permission
9213                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9214            throw new SecurityException("You need the "
9215                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9216                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9217        }
9218
9219        verificationParams.setInstallerUid(callingUid);
9220
9221        final File originFile = new File(originPath);
9222        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9223
9224        final Message msg = mHandler.obtainMessage(INIT_COPY);
9225        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9226                null, verificationParams, user, packageAbiOverride);
9227        mHandler.sendMessage(msg);
9228    }
9229
9230    void installStage(String packageName, File stagedDir, String stagedCid,
9231            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9232            String installerPackageName, int installerUid, UserHandle user) {
9233        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9234                params.referrerUri, installerUid, null);
9235        verifParams.setInstallerUid(installerUid);
9236
9237        final OriginInfo origin;
9238        if (stagedDir != null) {
9239            origin = OriginInfo.fromStagedFile(stagedDir);
9240        } else {
9241            origin = OriginInfo.fromStagedContainer(stagedCid);
9242        }
9243
9244        final Message msg = mHandler.obtainMessage(INIT_COPY);
9245        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9246                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9247        mHandler.sendMessage(msg);
9248    }
9249
9250    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9251        Bundle extras = new Bundle(1);
9252        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9253
9254        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9255                packageName, extras, null, null, new int[] {userId});
9256        try {
9257            IActivityManager am = ActivityManagerNative.getDefault();
9258            final boolean isSystem =
9259                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9260            if (isSystem && am.isUserRunning(userId, false)) {
9261                // The just-installed/enabled app is bundled on the system, so presumed
9262                // to be able to run automatically without needing an explicit launch.
9263                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9264                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9265                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9266                        .setPackage(packageName);
9267                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9268                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9269            }
9270        } catch (RemoteException e) {
9271            // shouldn't happen
9272            Slog.w(TAG, "Unable to bootstrap installed package", e);
9273        }
9274    }
9275
9276    @Override
9277    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9278            int userId) {
9279        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9280        PackageSetting pkgSetting;
9281        final int uid = Binder.getCallingUid();
9282        enforceCrossUserPermission(uid, userId, true, true,
9283                "setApplicationHiddenSetting for user " + userId);
9284
9285        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9286            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9287            return false;
9288        }
9289
9290        long callingId = Binder.clearCallingIdentity();
9291        try {
9292            boolean sendAdded = false;
9293            boolean sendRemoved = false;
9294            // writer
9295            synchronized (mPackages) {
9296                pkgSetting = mSettings.mPackages.get(packageName);
9297                if (pkgSetting == null) {
9298                    return false;
9299                }
9300                if (pkgSetting.getHidden(userId) != hidden) {
9301                    pkgSetting.setHidden(hidden, userId);
9302                    mSettings.writePackageRestrictionsLPr(userId);
9303                    if (hidden) {
9304                        sendRemoved = true;
9305                    } else {
9306                        sendAdded = true;
9307                    }
9308                }
9309            }
9310            if (sendAdded) {
9311                sendPackageAddedForUser(packageName, pkgSetting, userId);
9312                return true;
9313            }
9314            if (sendRemoved) {
9315                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9316                        "hiding pkg");
9317                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9318            }
9319        } finally {
9320            Binder.restoreCallingIdentity(callingId);
9321        }
9322        return false;
9323    }
9324
9325    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9326            int userId) {
9327        final PackageRemovedInfo info = new PackageRemovedInfo();
9328        info.removedPackage = packageName;
9329        info.removedUsers = new int[] {userId};
9330        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9331        info.sendBroadcast(false, false, false);
9332    }
9333
9334    /**
9335     * Returns true if application is not found or there was an error. Otherwise it returns
9336     * the hidden state of the package for the given user.
9337     */
9338    @Override
9339    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9340        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9341        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9342                false, "getApplicationHidden for user " + userId);
9343        PackageSetting pkgSetting;
9344        long callingId = Binder.clearCallingIdentity();
9345        try {
9346            // writer
9347            synchronized (mPackages) {
9348                pkgSetting = mSettings.mPackages.get(packageName);
9349                if (pkgSetting == null) {
9350                    return true;
9351                }
9352                return pkgSetting.getHidden(userId);
9353            }
9354        } finally {
9355            Binder.restoreCallingIdentity(callingId);
9356        }
9357    }
9358
9359    /**
9360     * @hide
9361     */
9362    @Override
9363    public int installExistingPackageAsUser(String packageName, int userId) {
9364        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9365                null);
9366        PackageSetting pkgSetting;
9367        final int uid = Binder.getCallingUid();
9368        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9369                + userId);
9370        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9371            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9372        }
9373
9374        long callingId = Binder.clearCallingIdentity();
9375        try {
9376            boolean sendAdded = false;
9377
9378            // writer
9379            synchronized (mPackages) {
9380                pkgSetting = mSettings.mPackages.get(packageName);
9381                if (pkgSetting == null) {
9382                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9383                }
9384                if (!pkgSetting.getInstalled(userId)) {
9385                    pkgSetting.setInstalled(true, userId);
9386                    pkgSetting.setHidden(false, userId);
9387                    mSettings.writePackageRestrictionsLPr(userId);
9388                    sendAdded = true;
9389                }
9390            }
9391
9392            if (sendAdded) {
9393                sendPackageAddedForUser(packageName, pkgSetting, userId);
9394            }
9395        } finally {
9396            Binder.restoreCallingIdentity(callingId);
9397        }
9398
9399        return PackageManager.INSTALL_SUCCEEDED;
9400    }
9401
9402    boolean isUserRestricted(int userId, String restrictionKey) {
9403        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9404        if (restrictions.getBoolean(restrictionKey, false)) {
9405            Log.w(TAG, "User is restricted: " + restrictionKey);
9406            return true;
9407        }
9408        return false;
9409    }
9410
9411    @Override
9412    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9413        mContext.enforceCallingOrSelfPermission(
9414                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9415                "Only package verification agents can verify applications");
9416
9417        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9418        final PackageVerificationResponse response = new PackageVerificationResponse(
9419                verificationCode, Binder.getCallingUid());
9420        msg.arg1 = id;
9421        msg.obj = response;
9422        mHandler.sendMessage(msg);
9423    }
9424
9425    @Override
9426    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9427            long millisecondsToDelay) {
9428        mContext.enforceCallingOrSelfPermission(
9429                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9430                "Only package verification agents can extend verification timeouts");
9431
9432        final PackageVerificationState state = mPendingVerification.get(id);
9433        final PackageVerificationResponse response = new PackageVerificationResponse(
9434                verificationCodeAtTimeout, Binder.getCallingUid());
9435
9436        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9437            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9438        }
9439        if (millisecondsToDelay < 0) {
9440            millisecondsToDelay = 0;
9441        }
9442        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9443                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9444            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9445        }
9446
9447        if ((state != null) && !state.timeoutExtended()) {
9448            state.extendTimeout();
9449
9450            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9451            msg.arg1 = id;
9452            msg.obj = response;
9453            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9454        }
9455    }
9456
9457    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9458            int verificationCode, UserHandle user) {
9459        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9460        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9461        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9462        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9463        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9464
9465        mContext.sendBroadcastAsUser(intent, user,
9466                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9467    }
9468
9469    private ComponentName matchComponentForVerifier(String packageName,
9470            List<ResolveInfo> receivers) {
9471        ActivityInfo targetReceiver = null;
9472
9473        final int NR = receivers.size();
9474        for (int i = 0; i < NR; i++) {
9475            final ResolveInfo info = receivers.get(i);
9476            if (info.activityInfo == null) {
9477                continue;
9478            }
9479
9480            if (packageName.equals(info.activityInfo.packageName)) {
9481                targetReceiver = info.activityInfo;
9482                break;
9483            }
9484        }
9485
9486        if (targetReceiver == null) {
9487            return null;
9488        }
9489
9490        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9491    }
9492
9493    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9494            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9495        if (pkgInfo.verifiers.length == 0) {
9496            return null;
9497        }
9498
9499        final int N = pkgInfo.verifiers.length;
9500        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9501        for (int i = 0; i < N; i++) {
9502            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9503
9504            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9505                    receivers);
9506            if (comp == null) {
9507                continue;
9508            }
9509
9510            final int verifierUid = getUidForVerifier(verifierInfo);
9511            if (verifierUid == -1) {
9512                continue;
9513            }
9514
9515            if (DEBUG_VERIFY) {
9516                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9517                        + " with the correct signature");
9518            }
9519            sufficientVerifiers.add(comp);
9520            verificationState.addSufficientVerifier(verifierUid);
9521        }
9522
9523        return sufficientVerifiers;
9524    }
9525
9526    private int getUidForVerifier(VerifierInfo verifierInfo) {
9527        synchronized (mPackages) {
9528            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9529            if (pkg == null) {
9530                return -1;
9531            } else if (pkg.mSignatures.length != 1) {
9532                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9533                        + " has more than one signature; ignoring");
9534                return -1;
9535            }
9536
9537            /*
9538             * If the public key of the package's signature does not match
9539             * our expected public key, then this is a different package and
9540             * we should skip.
9541             */
9542
9543            final byte[] expectedPublicKey;
9544            try {
9545                final Signature verifierSig = pkg.mSignatures[0];
9546                final PublicKey publicKey = verifierSig.getPublicKey();
9547                expectedPublicKey = publicKey.getEncoded();
9548            } catch (CertificateException e) {
9549                return -1;
9550            }
9551
9552            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9553
9554            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9555                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9556                        + " does not have the expected public key; ignoring");
9557                return -1;
9558            }
9559
9560            return pkg.applicationInfo.uid;
9561        }
9562    }
9563
9564    @Override
9565    public void finishPackageInstall(int token) {
9566        enforceSystemOrRoot("Only the system is allowed to finish installs");
9567
9568        if (DEBUG_INSTALL) {
9569            Slog.v(TAG, "BM finishing package install for " + token);
9570        }
9571
9572        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9573        mHandler.sendMessage(msg);
9574    }
9575
9576    /**
9577     * Get the verification agent timeout.
9578     *
9579     * @return verification timeout in milliseconds
9580     */
9581    private long getVerificationTimeout() {
9582        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9583                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9584                DEFAULT_VERIFICATION_TIMEOUT);
9585    }
9586
9587    /**
9588     * Get the default verification agent response code.
9589     *
9590     * @return default verification response code
9591     */
9592    private int getDefaultVerificationResponse() {
9593        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9594                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9595                DEFAULT_VERIFICATION_RESPONSE);
9596    }
9597
9598    /**
9599     * Check whether or not package verification has been enabled.
9600     *
9601     * @return true if verification should be performed
9602     */
9603    private boolean isVerificationEnabled(int userId, int installFlags) {
9604        if (!DEFAULT_VERIFY_ENABLE) {
9605            return false;
9606        }
9607
9608        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9609
9610        // Check if installing from ADB
9611        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9612            // Do not run verification in a test harness environment
9613            if (ActivityManager.isRunningInTestHarness()) {
9614                return false;
9615            }
9616            if (ensureVerifyAppsEnabled) {
9617                return true;
9618            }
9619            // Check if the developer does not want package verification for ADB installs
9620            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9621                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9622                return false;
9623            }
9624        }
9625
9626        if (ensureVerifyAppsEnabled) {
9627            return true;
9628        }
9629
9630        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9631                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9632    }
9633
9634    @Override
9635    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9636            throws RemoteException {
9637        mContext.enforceCallingOrSelfPermission(
9638                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9639                "Only intentfilter verification agents can verify applications");
9640
9641        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9642        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9643                Binder.getCallingUid(), verificationCode, failedDomains);
9644        msg.arg1 = id;
9645        msg.obj = response;
9646        mHandler.sendMessage(msg);
9647    }
9648
9649    @Override
9650    public int getIntentVerificationStatus(String packageName, int userId) {
9651        synchronized (mPackages) {
9652            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9653        }
9654    }
9655
9656    @Override
9657    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9658        mContext.enforceCallingOrSelfPermission(
9659                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9660
9661        boolean result = false;
9662        synchronized (mPackages) {
9663            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9664        }
9665        if (result) {
9666            scheduleWritePackageRestrictionsLocked(userId);
9667        }
9668        return result;
9669    }
9670
9671    @Override
9672    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9673        synchronized (mPackages) {
9674            return mSettings.getIntentFilterVerificationsLPr(packageName);
9675        }
9676    }
9677
9678    @Override
9679    public List<IntentFilter> getAllIntentFilters(String packageName) {
9680        if (TextUtils.isEmpty(packageName)) {
9681            return Collections.<IntentFilter>emptyList();
9682        }
9683        synchronized (mPackages) {
9684            PackageParser.Package pkg = mPackages.get(packageName);
9685            if (pkg == null || pkg.activities == null) {
9686                return Collections.<IntentFilter>emptyList();
9687            }
9688            final int count = pkg.activities.size();
9689            ArrayList<IntentFilter> result = new ArrayList<>();
9690            for (int n=0; n<count; n++) {
9691                PackageParser.Activity activity = pkg.activities.get(n);
9692                if (activity.intents != null || activity.intents.size() > 0) {
9693                    result.addAll(activity.intents);
9694                }
9695            }
9696            return result;
9697        }
9698    }
9699
9700    @Override
9701    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9702        mContext.enforceCallingOrSelfPermission(
9703                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9704
9705        synchronized (mPackages) {
9706            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9707            if (packageName != null) {
9708                result |= updateIntentVerificationStatus(packageName,
9709                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9710                        UserHandle.myUserId());
9711                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9712                        packageName, userId);
9713            }
9714            return result;
9715        }
9716    }
9717
9718    @Override
9719    public String getDefaultBrowserPackageName(int userId) {
9720        synchronized (mPackages) {
9721            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9722        }
9723    }
9724
9725    /**
9726     * Get the "allow unknown sources" setting.
9727     *
9728     * @return the current "allow unknown sources" setting
9729     */
9730    private int getUnknownSourcesSettings() {
9731        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9732                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9733                -1);
9734    }
9735
9736    @Override
9737    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9738        final int uid = Binder.getCallingUid();
9739        // writer
9740        synchronized (mPackages) {
9741            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9742            if (targetPackageSetting == null) {
9743                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9744            }
9745
9746            PackageSetting installerPackageSetting;
9747            if (installerPackageName != null) {
9748                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9749                if (installerPackageSetting == null) {
9750                    throw new IllegalArgumentException("Unknown installer package: "
9751                            + installerPackageName);
9752                }
9753            } else {
9754                installerPackageSetting = null;
9755            }
9756
9757            Signature[] callerSignature;
9758            Object obj = mSettings.getUserIdLPr(uid);
9759            if (obj != null) {
9760                if (obj instanceof SharedUserSetting) {
9761                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9762                } else if (obj instanceof PackageSetting) {
9763                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9764                } else {
9765                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9766                }
9767            } else {
9768                throw new SecurityException("Unknown calling uid " + uid);
9769            }
9770
9771            // Verify: can't set installerPackageName to a package that is
9772            // not signed with the same cert as the caller.
9773            if (installerPackageSetting != null) {
9774                if (compareSignatures(callerSignature,
9775                        installerPackageSetting.signatures.mSignatures)
9776                        != PackageManager.SIGNATURE_MATCH) {
9777                    throw new SecurityException(
9778                            "Caller does not have same cert as new installer package "
9779                            + installerPackageName);
9780                }
9781            }
9782
9783            // Verify: if target already has an installer package, it must
9784            // be signed with the same cert as the caller.
9785            if (targetPackageSetting.installerPackageName != null) {
9786                PackageSetting setting = mSettings.mPackages.get(
9787                        targetPackageSetting.installerPackageName);
9788                // If the currently set package isn't valid, then it's always
9789                // okay to change it.
9790                if (setting != null) {
9791                    if (compareSignatures(callerSignature,
9792                            setting.signatures.mSignatures)
9793                            != PackageManager.SIGNATURE_MATCH) {
9794                        throw new SecurityException(
9795                                "Caller does not have same cert as old installer package "
9796                                + targetPackageSetting.installerPackageName);
9797                    }
9798                }
9799            }
9800
9801            // Okay!
9802            targetPackageSetting.installerPackageName = installerPackageName;
9803            scheduleWriteSettingsLocked();
9804        }
9805    }
9806
9807    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9808        // Queue up an async operation since the package installation may take a little while.
9809        mHandler.post(new Runnable() {
9810            public void run() {
9811                mHandler.removeCallbacks(this);
9812                 // Result object to be returned
9813                PackageInstalledInfo res = new PackageInstalledInfo();
9814                res.returnCode = currentStatus;
9815                res.uid = -1;
9816                res.pkg = null;
9817                res.removedInfo = new PackageRemovedInfo();
9818                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9819                    args.doPreInstall(res.returnCode);
9820                    synchronized (mInstallLock) {
9821                        installPackageLI(args, res);
9822                    }
9823                    args.doPostInstall(res.returnCode, res.uid);
9824                }
9825
9826                // A restore should be performed at this point if (a) the install
9827                // succeeded, (b) the operation is not an update, and (c) the new
9828                // package has not opted out of backup participation.
9829                final boolean update = res.removedInfo.removedPackage != null;
9830                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9831                boolean doRestore = !update
9832                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9833
9834                // Set up the post-install work request bookkeeping.  This will be used
9835                // and cleaned up by the post-install event handling regardless of whether
9836                // there's a restore pass performed.  Token values are >= 1.
9837                int token;
9838                if (mNextInstallToken < 0) mNextInstallToken = 1;
9839                token = mNextInstallToken++;
9840
9841                PostInstallData data = new PostInstallData(args, res);
9842                mRunningInstalls.put(token, data);
9843                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9844
9845                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9846                    // Pass responsibility to the Backup Manager.  It will perform a
9847                    // restore if appropriate, then pass responsibility back to the
9848                    // Package Manager to run the post-install observer callbacks
9849                    // and broadcasts.
9850                    IBackupManager bm = IBackupManager.Stub.asInterface(
9851                            ServiceManager.getService(Context.BACKUP_SERVICE));
9852                    if (bm != null) {
9853                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9854                                + " to BM for possible restore");
9855                        try {
9856                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9857                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9858                            } else {
9859                                doRestore = false;
9860                            }
9861                        } catch (RemoteException e) {
9862                            // can't happen; the backup manager is local
9863                        } catch (Exception e) {
9864                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9865                            doRestore = false;
9866                        }
9867                    } else {
9868                        Slog.e(TAG, "Backup Manager not found!");
9869                        doRestore = false;
9870                    }
9871                }
9872
9873                if (!doRestore) {
9874                    // No restore possible, or the Backup Manager was mysteriously not
9875                    // available -- just fire the post-install work request directly.
9876                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9877                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9878                    mHandler.sendMessage(msg);
9879                }
9880            }
9881        });
9882    }
9883
9884    private abstract class HandlerParams {
9885        private static final int MAX_RETRIES = 4;
9886
9887        /**
9888         * Number of times startCopy() has been attempted and had a non-fatal
9889         * error.
9890         */
9891        private int mRetries = 0;
9892
9893        /** User handle for the user requesting the information or installation. */
9894        private final UserHandle mUser;
9895
9896        HandlerParams(UserHandle user) {
9897            mUser = user;
9898        }
9899
9900        UserHandle getUser() {
9901            return mUser;
9902        }
9903
9904        final boolean startCopy() {
9905            boolean res;
9906            try {
9907                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9908
9909                if (++mRetries > MAX_RETRIES) {
9910                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9911                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9912                    handleServiceError();
9913                    return false;
9914                } else {
9915                    handleStartCopy();
9916                    res = true;
9917                }
9918            } catch (RemoteException e) {
9919                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9920                mHandler.sendEmptyMessage(MCS_RECONNECT);
9921                res = false;
9922            }
9923            handleReturnCode();
9924            return res;
9925        }
9926
9927        final void serviceError() {
9928            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9929            handleServiceError();
9930            handleReturnCode();
9931        }
9932
9933        abstract void handleStartCopy() throws RemoteException;
9934        abstract void handleServiceError();
9935        abstract void handleReturnCode();
9936    }
9937
9938    class MeasureParams extends HandlerParams {
9939        private final PackageStats mStats;
9940        private boolean mSuccess;
9941
9942        private final IPackageStatsObserver mObserver;
9943
9944        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9945            super(new UserHandle(stats.userHandle));
9946            mObserver = observer;
9947            mStats = stats;
9948        }
9949
9950        @Override
9951        public String toString() {
9952            return "MeasureParams{"
9953                + Integer.toHexString(System.identityHashCode(this))
9954                + " " + mStats.packageName + "}";
9955        }
9956
9957        @Override
9958        void handleStartCopy() throws RemoteException {
9959            synchronized (mInstallLock) {
9960                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9961            }
9962
9963            if (mSuccess) {
9964                final boolean mounted;
9965                if (Environment.isExternalStorageEmulated()) {
9966                    mounted = true;
9967                } else {
9968                    final String status = Environment.getExternalStorageState();
9969                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9970                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9971                }
9972
9973                if (mounted) {
9974                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9975
9976                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9977                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9978
9979                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9980                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9981
9982                    // Always subtract cache size, since it's a subdirectory
9983                    mStats.externalDataSize -= mStats.externalCacheSize;
9984
9985                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9986                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9987
9988                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9989                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9990                }
9991            }
9992        }
9993
9994        @Override
9995        void handleReturnCode() {
9996            if (mObserver != null) {
9997                try {
9998                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9999                } catch (RemoteException e) {
10000                    Slog.i(TAG, "Observer no longer exists.");
10001                }
10002            }
10003        }
10004
10005        @Override
10006        void handleServiceError() {
10007            Slog.e(TAG, "Could not measure application " + mStats.packageName
10008                            + " external storage");
10009        }
10010    }
10011
10012    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10013            throws RemoteException {
10014        long result = 0;
10015        for (File path : paths) {
10016            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10017        }
10018        return result;
10019    }
10020
10021    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10022        for (File path : paths) {
10023            try {
10024                mcs.clearDirectory(path.getAbsolutePath());
10025            } catch (RemoteException e) {
10026            }
10027        }
10028    }
10029
10030    static class OriginInfo {
10031        /**
10032         * Location where install is coming from, before it has been
10033         * copied/renamed into place. This could be a single monolithic APK
10034         * file, or a cluster directory. This location may be untrusted.
10035         */
10036        final File file;
10037        final String cid;
10038
10039        /**
10040         * Flag indicating that {@link #file} or {@link #cid} has already been
10041         * staged, meaning downstream users don't need to defensively copy the
10042         * contents.
10043         */
10044        final boolean staged;
10045
10046        /**
10047         * Flag indicating that {@link #file} or {@link #cid} is an already
10048         * installed app that is being moved.
10049         */
10050        final boolean existing;
10051
10052        final String resolvedPath;
10053        final File resolvedFile;
10054
10055        static OriginInfo fromNothing() {
10056            return new OriginInfo(null, null, false, false);
10057        }
10058
10059        static OriginInfo fromUntrustedFile(File file) {
10060            return new OriginInfo(file, null, false, false);
10061        }
10062
10063        static OriginInfo fromExistingFile(File file) {
10064            return new OriginInfo(file, null, false, true);
10065        }
10066
10067        static OriginInfo fromStagedFile(File file) {
10068            return new OriginInfo(file, null, true, false);
10069        }
10070
10071        static OriginInfo fromStagedContainer(String cid) {
10072            return new OriginInfo(null, cid, true, false);
10073        }
10074
10075        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10076            this.file = file;
10077            this.cid = cid;
10078            this.staged = staged;
10079            this.existing = existing;
10080
10081            if (cid != null) {
10082                resolvedPath = PackageHelper.getSdDir(cid);
10083                resolvedFile = new File(resolvedPath);
10084            } else if (file != null) {
10085                resolvedPath = file.getAbsolutePath();
10086                resolvedFile = file;
10087            } else {
10088                resolvedPath = null;
10089                resolvedFile = null;
10090            }
10091        }
10092    }
10093
10094    class MoveInfo {
10095        final int moveId;
10096        final String fromUuid;
10097        final String toUuid;
10098        final String packageName;
10099        final String dataAppName;
10100        final int appId;
10101        final String seinfo;
10102
10103        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10104                String dataAppName, int appId, String seinfo) {
10105            this.moveId = moveId;
10106            this.fromUuid = fromUuid;
10107            this.toUuid = toUuid;
10108            this.packageName = packageName;
10109            this.dataAppName = dataAppName;
10110            this.appId = appId;
10111            this.seinfo = seinfo;
10112        }
10113    }
10114
10115    class InstallParams extends HandlerParams {
10116        final OriginInfo origin;
10117        final MoveInfo move;
10118        final IPackageInstallObserver2 observer;
10119        int installFlags;
10120        final String installerPackageName;
10121        final String volumeUuid;
10122        final VerificationParams verificationParams;
10123        private InstallArgs mArgs;
10124        private int mRet;
10125        final String packageAbiOverride;
10126
10127        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10128                int installFlags, String installerPackageName, String volumeUuid,
10129                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10130            super(user);
10131            this.origin = origin;
10132            this.move = move;
10133            this.observer = observer;
10134            this.installFlags = installFlags;
10135            this.installerPackageName = installerPackageName;
10136            this.volumeUuid = volumeUuid;
10137            this.verificationParams = verificationParams;
10138            this.packageAbiOverride = packageAbiOverride;
10139        }
10140
10141        @Override
10142        public String toString() {
10143            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10144                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10145        }
10146
10147        public ManifestDigest getManifestDigest() {
10148            if (verificationParams == null) {
10149                return null;
10150            }
10151            return verificationParams.getManifestDigest();
10152        }
10153
10154        private int installLocationPolicy(PackageInfoLite pkgLite) {
10155            String packageName = pkgLite.packageName;
10156            int installLocation = pkgLite.installLocation;
10157            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10158            // reader
10159            synchronized (mPackages) {
10160                PackageParser.Package pkg = mPackages.get(packageName);
10161                if (pkg != null) {
10162                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10163                        // Check for downgrading.
10164                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10165                            try {
10166                                checkDowngrade(pkg, pkgLite);
10167                            } catch (PackageManagerException e) {
10168                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10169                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10170                            }
10171                        }
10172                        // Check for updated system application.
10173                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10174                            if (onSd) {
10175                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10176                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10177                            }
10178                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10179                        } else {
10180                            if (onSd) {
10181                                // Install flag overrides everything.
10182                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10183                            }
10184                            // If current upgrade specifies particular preference
10185                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10186                                // Application explicitly specified internal.
10187                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10188                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10189                                // App explictly prefers external. Let policy decide
10190                            } else {
10191                                // Prefer previous location
10192                                if (isExternal(pkg)) {
10193                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10194                                }
10195                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10196                            }
10197                        }
10198                    } else {
10199                        // Invalid install. Return error code
10200                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10201                    }
10202                }
10203            }
10204            // All the special cases have been taken care of.
10205            // Return result based on recommended install location.
10206            if (onSd) {
10207                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10208            }
10209            return pkgLite.recommendedInstallLocation;
10210        }
10211
10212        /*
10213         * Invoke remote method to get package information and install
10214         * location values. Override install location based on default
10215         * policy if needed and then create install arguments based
10216         * on the install location.
10217         */
10218        public void handleStartCopy() throws RemoteException {
10219            int ret = PackageManager.INSTALL_SUCCEEDED;
10220
10221            // If we're already staged, we've firmly committed to an install location
10222            if (origin.staged) {
10223                if (origin.file != null) {
10224                    installFlags |= PackageManager.INSTALL_INTERNAL;
10225                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10226                } else if (origin.cid != null) {
10227                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10228                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10229                } else {
10230                    throw new IllegalStateException("Invalid stage location");
10231                }
10232            }
10233
10234            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10235            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10236
10237            PackageInfoLite pkgLite = null;
10238
10239            if (onInt && onSd) {
10240                // Check if both bits are set.
10241                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10242                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10243            } else {
10244                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10245                        packageAbiOverride);
10246
10247                /*
10248                 * If we have too little free space, try to free cache
10249                 * before giving up.
10250                 */
10251                if (!origin.staged && pkgLite.recommendedInstallLocation
10252                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10253                    // TODO: focus freeing disk space on the target device
10254                    final StorageManager storage = StorageManager.from(mContext);
10255                    final long lowThreshold = storage.getStorageLowBytes(
10256                            Environment.getDataDirectory());
10257
10258                    final long sizeBytes = mContainerService.calculateInstalledSize(
10259                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10260
10261                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10262                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10263                                installFlags, packageAbiOverride);
10264                    }
10265
10266                    /*
10267                     * The cache free must have deleted the file we
10268                     * downloaded to install.
10269                     *
10270                     * TODO: fix the "freeCache" call to not delete
10271                     *       the file we care about.
10272                     */
10273                    if (pkgLite.recommendedInstallLocation
10274                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10275                        pkgLite.recommendedInstallLocation
10276                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10277                    }
10278                }
10279            }
10280
10281            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10282                int loc = pkgLite.recommendedInstallLocation;
10283                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10284                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10285                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10286                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10287                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10288                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10289                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10290                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10291                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10292                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10293                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10294                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10295                } else {
10296                    // Override with defaults if needed.
10297                    loc = installLocationPolicy(pkgLite);
10298                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10299                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10300                    } else if (!onSd && !onInt) {
10301                        // Override install location with flags
10302                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10303                            // Set the flag to install on external media.
10304                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10305                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10306                        } else {
10307                            // Make sure the flag for installing on external
10308                            // media is unset
10309                            installFlags |= PackageManager.INSTALL_INTERNAL;
10310                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10311                        }
10312                    }
10313                }
10314            }
10315
10316            final InstallArgs args = createInstallArgs(this);
10317            mArgs = args;
10318
10319            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10320                 /*
10321                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10322                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10323                 */
10324                int userIdentifier = getUser().getIdentifier();
10325                if (userIdentifier == UserHandle.USER_ALL
10326                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10327                    userIdentifier = UserHandle.USER_OWNER;
10328                }
10329
10330                /*
10331                 * Determine if we have any installed package verifiers. If we
10332                 * do, then we'll defer to them to verify the packages.
10333                 */
10334                final int requiredUid = mRequiredVerifierPackage == null ? -1
10335                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10336                if (!origin.existing && requiredUid != -1
10337                        && isVerificationEnabled(userIdentifier, installFlags)) {
10338                    final Intent verification = new Intent(
10339                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10340                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10341                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10342                            PACKAGE_MIME_TYPE);
10343                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10344
10345                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10346                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10347                            0 /* TODO: Which userId? */);
10348
10349                    if (DEBUG_VERIFY) {
10350                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10351                                + verification.toString() + " with " + pkgLite.verifiers.length
10352                                + " optional verifiers");
10353                    }
10354
10355                    final int verificationId = mPendingVerificationToken++;
10356
10357                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10358
10359                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10360                            installerPackageName);
10361
10362                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10363                            installFlags);
10364
10365                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10366                            pkgLite.packageName);
10367
10368                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10369                            pkgLite.versionCode);
10370
10371                    if (verificationParams != null) {
10372                        if (verificationParams.getVerificationURI() != null) {
10373                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10374                                 verificationParams.getVerificationURI());
10375                        }
10376                        if (verificationParams.getOriginatingURI() != null) {
10377                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10378                                  verificationParams.getOriginatingURI());
10379                        }
10380                        if (verificationParams.getReferrer() != null) {
10381                            verification.putExtra(Intent.EXTRA_REFERRER,
10382                                  verificationParams.getReferrer());
10383                        }
10384                        if (verificationParams.getOriginatingUid() >= 0) {
10385                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10386                                  verificationParams.getOriginatingUid());
10387                        }
10388                        if (verificationParams.getInstallerUid() >= 0) {
10389                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10390                                  verificationParams.getInstallerUid());
10391                        }
10392                    }
10393
10394                    final PackageVerificationState verificationState = new PackageVerificationState(
10395                            requiredUid, args);
10396
10397                    mPendingVerification.append(verificationId, verificationState);
10398
10399                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10400                            receivers, verificationState);
10401
10402                    /*
10403                     * If any sufficient verifiers were listed in the package
10404                     * manifest, attempt to ask them.
10405                     */
10406                    if (sufficientVerifiers != null) {
10407                        final int N = sufficientVerifiers.size();
10408                        if (N == 0) {
10409                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10410                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10411                        } else {
10412                            for (int i = 0; i < N; i++) {
10413                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10414
10415                                final Intent sufficientIntent = new Intent(verification);
10416                                sufficientIntent.setComponent(verifierComponent);
10417
10418                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10419                            }
10420                        }
10421                    }
10422
10423                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10424                            mRequiredVerifierPackage, receivers);
10425                    if (ret == PackageManager.INSTALL_SUCCEEDED
10426                            && mRequiredVerifierPackage != null) {
10427                        /*
10428                         * Send the intent to the required verification agent,
10429                         * but only start the verification timeout after the
10430                         * target BroadcastReceivers have run.
10431                         */
10432                        verification.setComponent(requiredVerifierComponent);
10433                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10434                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10435                                new BroadcastReceiver() {
10436                                    @Override
10437                                    public void onReceive(Context context, Intent intent) {
10438                                        final Message msg = mHandler
10439                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10440                                        msg.arg1 = verificationId;
10441                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10442                                    }
10443                                }, null, 0, null, null);
10444
10445                        /*
10446                         * We don't want the copy to proceed until verification
10447                         * succeeds, so null out this field.
10448                         */
10449                        mArgs = null;
10450                    }
10451                } else {
10452                    /*
10453                     * No package verification is enabled, so immediately start
10454                     * the remote call to initiate copy using temporary file.
10455                     */
10456                    ret = args.copyApk(mContainerService, true);
10457                }
10458            }
10459
10460            mRet = ret;
10461        }
10462
10463        @Override
10464        void handleReturnCode() {
10465            // If mArgs is null, then MCS couldn't be reached. When it
10466            // reconnects, it will try again to install. At that point, this
10467            // will succeed.
10468            if (mArgs != null) {
10469                processPendingInstall(mArgs, mRet);
10470            }
10471        }
10472
10473        @Override
10474        void handleServiceError() {
10475            mArgs = createInstallArgs(this);
10476            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10477        }
10478
10479        public boolean isForwardLocked() {
10480            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10481        }
10482    }
10483
10484    /**
10485     * Used during creation of InstallArgs
10486     *
10487     * @param installFlags package installation flags
10488     * @return true if should be installed on external storage
10489     */
10490    private static boolean installOnExternalAsec(int installFlags) {
10491        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10492            return false;
10493        }
10494        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10495            return true;
10496        }
10497        return false;
10498    }
10499
10500    /**
10501     * Used during creation of InstallArgs
10502     *
10503     * @param installFlags package installation flags
10504     * @return true if should be installed as forward locked
10505     */
10506    private static boolean installForwardLocked(int installFlags) {
10507        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10508    }
10509
10510    private InstallArgs createInstallArgs(InstallParams params) {
10511        if (params.move != null) {
10512            return new MoveInstallArgs(params);
10513        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10514            return new AsecInstallArgs(params);
10515        } else {
10516            return new FileInstallArgs(params);
10517        }
10518    }
10519
10520    /**
10521     * Create args that describe an existing installed package. Typically used
10522     * when cleaning up old installs, or used as a move source.
10523     */
10524    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10525            String resourcePath, String[] instructionSets) {
10526        final boolean isInAsec;
10527        if (installOnExternalAsec(installFlags)) {
10528            /* Apps on SD card are always in ASEC containers. */
10529            isInAsec = true;
10530        } else if (installForwardLocked(installFlags)
10531                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10532            /*
10533             * Forward-locked apps are only in ASEC containers if they're the
10534             * new style
10535             */
10536            isInAsec = true;
10537        } else {
10538            isInAsec = false;
10539        }
10540
10541        if (isInAsec) {
10542            return new AsecInstallArgs(codePath, instructionSets,
10543                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10544        } else {
10545            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10546        }
10547    }
10548
10549    static abstract class InstallArgs {
10550        /** @see InstallParams#origin */
10551        final OriginInfo origin;
10552        /** @see InstallParams#move */
10553        final MoveInfo move;
10554
10555        final IPackageInstallObserver2 observer;
10556        // Always refers to PackageManager flags only
10557        final int installFlags;
10558        final String installerPackageName;
10559        final String volumeUuid;
10560        final ManifestDigest manifestDigest;
10561        final UserHandle user;
10562        final String abiOverride;
10563
10564        // The list of instruction sets supported by this app. This is currently
10565        // only used during the rmdex() phase to clean up resources. We can get rid of this
10566        // if we move dex files under the common app path.
10567        /* nullable */ String[] instructionSets;
10568
10569        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10570                int installFlags, String installerPackageName, String volumeUuid,
10571                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10572                String abiOverride) {
10573            this.origin = origin;
10574            this.move = move;
10575            this.installFlags = installFlags;
10576            this.observer = observer;
10577            this.installerPackageName = installerPackageName;
10578            this.volumeUuid = volumeUuid;
10579            this.manifestDigest = manifestDigest;
10580            this.user = user;
10581            this.instructionSets = instructionSets;
10582            this.abiOverride = abiOverride;
10583        }
10584
10585        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10586        abstract int doPreInstall(int status);
10587
10588        /**
10589         * Rename package into final resting place. All paths on the given
10590         * scanned package should be updated to reflect the rename.
10591         */
10592        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10593        abstract int doPostInstall(int status, int uid);
10594
10595        /** @see PackageSettingBase#codePathString */
10596        abstract String getCodePath();
10597        /** @see PackageSettingBase#resourcePathString */
10598        abstract String getResourcePath();
10599
10600        // Need installer lock especially for dex file removal.
10601        abstract void cleanUpResourcesLI();
10602        abstract boolean doPostDeleteLI(boolean delete);
10603
10604        /**
10605         * Called before the source arguments are copied. This is used mostly
10606         * for MoveParams when it needs to read the source file to put it in the
10607         * destination.
10608         */
10609        int doPreCopy() {
10610            return PackageManager.INSTALL_SUCCEEDED;
10611        }
10612
10613        /**
10614         * Called after the source arguments are copied. This is used mostly for
10615         * MoveParams when it needs to read the source file to put it in the
10616         * destination.
10617         *
10618         * @return
10619         */
10620        int doPostCopy(int uid) {
10621            return PackageManager.INSTALL_SUCCEEDED;
10622        }
10623
10624        protected boolean isFwdLocked() {
10625            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10626        }
10627
10628        protected boolean isExternalAsec() {
10629            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10630        }
10631
10632        UserHandle getUser() {
10633            return user;
10634        }
10635    }
10636
10637    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10638        if (!allCodePaths.isEmpty()) {
10639            if (instructionSets == null) {
10640                throw new IllegalStateException("instructionSet == null");
10641            }
10642            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10643            for (String codePath : allCodePaths) {
10644                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10645                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10646                    if (retCode < 0) {
10647                        Slog.w(TAG, "Couldn't remove dex file for package: "
10648                                + " at location " + codePath + ", retcode=" + retCode);
10649                        // we don't consider this to be a failure of the core package deletion
10650                    }
10651                }
10652            }
10653        }
10654    }
10655
10656    /**
10657     * Logic to handle installation of non-ASEC applications, including copying
10658     * and renaming logic.
10659     */
10660    class FileInstallArgs extends InstallArgs {
10661        private File codeFile;
10662        private File resourceFile;
10663
10664        // Example topology:
10665        // /data/app/com.example/base.apk
10666        // /data/app/com.example/split_foo.apk
10667        // /data/app/com.example/lib/arm/libfoo.so
10668        // /data/app/com.example/lib/arm64/libfoo.so
10669        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10670
10671        /** New install */
10672        FileInstallArgs(InstallParams params) {
10673            super(params.origin, params.move, params.observer, params.installFlags,
10674                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10675                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10676            if (isFwdLocked()) {
10677                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10678            }
10679        }
10680
10681        /** Existing install */
10682        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10683            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10684                    null);
10685            this.codeFile = (codePath != null) ? new File(codePath) : null;
10686            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10687        }
10688
10689        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10690            if (origin.staged) {
10691                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10692                codeFile = origin.file;
10693                resourceFile = origin.file;
10694                return PackageManager.INSTALL_SUCCEEDED;
10695            }
10696
10697            try {
10698                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10699                codeFile = tempDir;
10700                resourceFile = tempDir;
10701            } catch (IOException e) {
10702                Slog.w(TAG, "Failed to create copy file: " + e);
10703                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10704            }
10705
10706            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10707                @Override
10708                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10709                    if (!FileUtils.isValidExtFilename(name)) {
10710                        throw new IllegalArgumentException("Invalid filename: " + name);
10711                    }
10712                    try {
10713                        final File file = new File(codeFile, name);
10714                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10715                                O_RDWR | O_CREAT, 0644);
10716                        Os.chmod(file.getAbsolutePath(), 0644);
10717                        return new ParcelFileDescriptor(fd);
10718                    } catch (ErrnoException e) {
10719                        throw new RemoteException("Failed to open: " + e.getMessage());
10720                    }
10721                }
10722            };
10723
10724            int ret = PackageManager.INSTALL_SUCCEEDED;
10725            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10726            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10727                Slog.e(TAG, "Failed to copy package");
10728                return ret;
10729            }
10730
10731            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10732            NativeLibraryHelper.Handle handle = null;
10733            try {
10734                handle = NativeLibraryHelper.Handle.create(codeFile);
10735                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10736                        abiOverride);
10737            } catch (IOException e) {
10738                Slog.e(TAG, "Copying native libraries failed", e);
10739                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10740            } finally {
10741                IoUtils.closeQuietly(handle);
10742            }
10743
10744            return ret;
10745        }
10746
10747        int doPreInstall(int status) {
10748            if (status != PackageManager.INSTALL_SUCCEEDED) {
10749                cleanUp();
10750            }
10751            return status;
10752        }
10753
10754        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10755            if (status != PackageManager.INSTALL_SUCCEEDED) {
10756                cleanUp();
10757                return false;
10758            }
10759
10760            final File targetDir = codeFile.getParentFile();
10761            final File beforeCodeFile = codeFile;
10762            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10763
10764            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10765            try {
10766                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10767            } catch (ErrnoException e) {
10768                Slog.w(TAG, "Failed to rename", e);
10769                return false;
10770            }
10771
10772            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10773                Slog.w(TAG, "Failed to restorecon");
10774                return false;
10775            }
10776
10777            // Reflect the rename internally
10778            codeFile = afterCodeFile;
10779            resourceFile = afterCodeFile;
10780
10781            // Reflect the rename in scanned details
10782            pkg.codePath = afterCodeFile.getAbsolutePath();
10783            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10784                    pkg.baseCodePath);
10785            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10786                    pkg.splitCodePaths);
10787
10788            // Reflect the rename in app info
10789            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10790            pkg.applicationInfo.setCodePath(pkg.codePath);
10791            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10792            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10793            pkg.applicationInfo.setResourcePath(pkg.codePath);
10794            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10795            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10796
10797            return true;
10798        }
10799
10800        int doPostInstall(int status, int uid) {
10801            if (status != PackageManager.INSTALL_SUCCEEDED) {
10802                cleanUp();
10803            }
10804            return status;
10805        }
10806
10807        @Override
10808        String getCodePath() {
10809            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10810        }
10811
10812        @Override
10813        String getResourcePath() {
10814            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10815        }
10816
10817        private boolean cleanUp() {
10818            if (codeFile == null || !codeFile.exists()) {
10819                return false;
10820            }
10821
10822            if (codeFile.isDirectory()) {
10823                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10824            } else {
10825                codeFile.delete();
10826            }
10827
10828            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10829                resourceFile.delete();
10830            }
10831
10832            return true;
10833        }
10834
10835        void cleanUpResourcesLI() {
10836            // Try enumerating all code paths before deleting
10837            List<String> allCodePaths = Collections.EMPTY_LIST;
10838            if (codeFile != null && codeFile.exists()) {
10839                try {
10840                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10841                    allCodePaths = pkg.getAllCodePaths();
10842                } catch (PackageParserException e) {
10843                    // Ignored; we tried our best
10844                }
10845            }
10846
10847            cleanUp();
10848            removeDexFiles(allCodePaths, instructionSets);
10849        }
10850
10851        boolean doPostDeleteLI(boolean delete) {
10852            // XXX err, shouldn't we respect the delete flag?
10853            cleanUpResourcesLI();
10854            return true;
10855        }
10856    }
10857
10858    private boolean isAsecExternal(String cid) {
10859        final String asecPath = PackageHelper.getSdFilesystem(cid);
10860        return !asecPath.startsWith(mAsecInternalPath);
10861    }
10862
10863    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10864            PackageManagerException {
10865        if (copyRet < 0) {
10866            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10867                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10868                throw new PackageManagerException(copyRet, message);
10869            }
10870        }
10871    }
10872
10873    /**
10874     * Extract the MountService "container ID" from the full code path of an
10875     * .apk.
10876     */
10877    static String cidFromCodePath(String fullCodePath) {
10878        int eidx = fullCodePath.lastIndexOf("/");
10879        String subStr1 = fullCodePath.substring(0, eidx);
10880        int sidx = subStr1.lastIndexOf("/");
10881        return subStr1.substring(sidx+1, eidx);
10882    }
10883
10884    /**
10885     * Logic to handle installation of ASEC applications, including copying and
10886     * renaming logic.
10887     */
10888    class AsecInstallArgs extends InstallArgs {
10889        static final String RES_FILE_NAME = "pkg.apk";
10890        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10891
10892        String cid;
10893        String packagePath;
10894        String resourcePath;
10895
10896        /** New install */
10897        AsecInstallArgs(InstallParams params) {
10898            super(params.origin, params.move, params.observer, params.installFlags,
10899                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10900                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10901        }
10902
10903        /** Existing install */
10904        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10905                        boolean isExternal, boolean isForwardLocked) {
10906            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10907                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10908                    instructionSets, null);
10909            // Hackily pretend we're still looking at a full code path
10910            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10911                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10912            }
10913
10914            // Extract cid from fullCodePath
10915            int eidx = fullCodePath.lastIndexOf("/");
10916            String subStr1 = fullCodePath.substring(0, eidx);
10917            int sidx = subStr1.lastIndexOf("/");
10918            cid = subStr1.substring(sidx+1, eidx);
10919            setMountPath(subStr1);
10920        }
10921
10922        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10923            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10924                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10925                    instructionSets, null);
10926            this.cid = cid;
10927            setMountPath(PackageHelper.getSdDir(cid));
10928        }
10929
10930        void createCopyFile() {
10931            cid = mInstallerService.allocateExternalStageCidLegacy();
10932        }
10933
10934        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10935            if (origin.staged) {
10936                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10937                cid = origin.cid;
10938                setMountPath(PackageHelper.getSdDir(cid));
10939                return PackageManager.INSTALL_SUCCEEDED;
10940            }
10941
10942            if (temp) {
10943                createCopyFile();
10944            } else {
10945                /*
10946                 * Pre-emptively destroy the container since it's destroyed if
10947                 * copying fails due to it existing anyway.
10948                 */
10949                PackageHelper.destroySdDir(cid);
10950            }
10951
10952            final String newMountPath = imcs.copyPackageToContainer(
10953                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10954                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10955
10956            if (newMountPath != null) {
10957                setMountPath(newMountPath);
10958                return PackageManager.INSTALL_SUCCEEDED;
10959            } else {
10960                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10961            }
10962        }
10963
10964        @Override
10965        String getCodePath() {
10966            return packagePath;
10967        }
10968
10969        @Override
10970        String getResourcePath() {
10971            return resourcePath;
10972        }
10973
10974        int doPreInstall(int status) {
10975            if (status != PackageManager.INSTALL_SUCCEEDED) {
10976                // Destroy container
10977                PackageHelper.destroySdDir(cid);
10978            } else {
10979                boolean mounted = PackageHelper.isContainerMounted(cid);
10980                if (!mounted) {
10981                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10982                            Process.SYSTEM_UID);
10983                    if (newMountPath != null) {
10984                        setMountPath(newMountPath);
10985                    } else {
10986                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10987                    }
10988                }
10989            }
10990            return status;
10991        }
10992
10993        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10994            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10995            String newMountPath = null;
10996            if (PackageHelper.isContainerMounted(cid)) {
10997                // Unmount the container
10998                if (!PackageHelper.unMountSdDir(cid)) {
10999                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11000                    return false;
11001                }
11002            }
11003            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11004                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11005                        " which might be stale. Will try to clean up.");
11006                // Clean up the stale container and proceed to recreate.
11007                if (!PackageHelper.destroySdDir(newCacheId)) {
11008                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11009                    return false;
11010                }
11011                // Successfully cleaned up stale container. Try to rename again.
11012                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11013                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11014                            + " inspite of cleaning it up.");
11015                    return false;
11016                }
11017            }
11018            if (!PackageHelper.isContainerMounted(newCacheId)) {
11019                Slog.w(TAG, "Mounting container " + newCacheId);
11020                newMountPath = PackageHelper.mountSdDir(newCacheId,
11021                        getEncryptKey(), Process.SYSTEM_UID);
11022            } else {
11023                newMountPath = PackageHelper.getSdDir(newCacheId);
11024            }
11025            if (newMountPath == null) {
11026                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11027                return false;
11028            }
11029            Log.i(TAG, "Succesfully renamed " + cid +
11030                    " to " + newCacheId +
11031                    " at new path: " + newMountPath);
11032            cid = newCacheId;
11033
11034            final File beforeCodeFile = new File(packagePath);
11035            setMountPath(newMountPath);
11036            final File afterCodeFile = new File(packagePath);
11037
11038            // Reflect the rename in scanned details
11039            pkg.codePath = afterCodeFile.getAbsolutePath();
11040            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11041                    pkg.baseCodePath);
11042            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11043                    pkg.splitCodePaths);
11044
11045            // Reflect the rename in app info
11046            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11047            pkg.applicationInfo.setCodePath(pkg.codePath);
11048            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11049            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11050            pkg.applicationInfo.setResourcePath(pkg.codePath);
11051            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11052            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11053
11054            return true;
11055        }
11056
11057        private void setMountPath(String mountPath) {
11058            final File mountFile = new File(mountPath);
11059
11060            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11061            if (monolithicFile.exists()) {
11062                packagePath = monolithicFile.getAbsolutePath();
11063                if (isFwdLocked()) {
11064                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11065                } else {
11066                    resourcePath = packagePath;
11067                }
11068            } else {
11069                packagePath = mountFile.getAbsolutePath();
11070                resourcePath = packagePath;
11071            }
11072        }
11073
11074        int doPostInstall(int status, int uid) {
11075            if (status != PackageManager.INSTALL_SUCCEEDED) {
11076                cleanUp();
11077            } else {
11078                final int groupOwner;
11079                final String protectedFile;
11080                if (isFwdLocked()) {
11081                    groupOwner = UserHandle.getSharedAppGid(uid);
11082                    protectedFile = RES_FILE_NAME;
11083                } else {
11084                    groupOwner = -1;
11085                    protectedFile = null;
11086                }
11087
11088                if (uid < Process.FIRST_APPLICATION_UID
11089                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11090                    Slog.e(TAG, "Failed to finalize " + cid);
11091                    PackageHelper.destroySdDir(cid);
11092                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11093                }
11094
11095                boolean mounted = PackageHelper.isContainerMounted(cid);
11096                if (!mounted) {
11097                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11098                }
11099            }
11100            return status;
11101        }
11102
11103        private void cleanUp() {
11104            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11105
11106            // Destroy secure container
11107            PackageHelper.destroySdDir(cid);
11108        }
11109
11110        private List<String> getAllCodePaths() {
11111            final File codeFile = new File(getCodePath());
11112            if (codeFile != null && codeFile.exists()) {
11113                try {
11114                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11115                    return pkg.getAllCodePaths();
11116                } catch (PackageParserException e) {
11117                    // Ignored; we tried our best
11118                }
11119            }
11120            return Collections.EMPTY_LIST;
11121        }
11122
11123        void cleanUpResourcesLI() {
11124            // Enumerate all code paths before deleting
11125            cleanUpResourcesLI(getAllCodePaths());
11126        }
11127
11128        private void cleanUpResourcesLI(List<String> allCodePaths) {
11129            cleanUp();
11130            removeDexFiles(allCodePaths, instructionSets);
11131        }
11132
11133        String getPackageName() {
11134            return getAsecPackageName(cid);
11135        }
11136
11137        boolean doPostDeleteLI(boolean delete) {
11138            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11139            final List<String> allCodePaths = getAllCodePaths();
11140            boolean mounted = PackageHelper.isContainerMounted(cid);
11141            if (mounted) {
11142                // Unmount first
11143                if (PackageHelper.unMountSdDir(cid)) {
11144                    mounted = false;
11145                }
11146            }
11147            if (!mounted && delete) {
11148                cleanUpResourcesLI(allCodePaths);
11149            }
11150            return !mounted;
11151        }
11152
11153        @Override
11154        int doPreCopy() {
11155            if (isFwdLocked()) {
11156                if (!PackageHelper.fixSdPermissions(cid,
11157                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11158                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11159                }
11160            }
11161
11162            return PackageManager.INSTALL_SUCCEEDED;
11163        }
11164
11165        @Override
11166        int doPostCopy(int uid) {
11167            if (isFwdLocked()) {
11168                if (uid < Process.FIRST_APPLICATION_UID
11169                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11170                                RES_FILE_NAME)) {
11171                    Slog.e(TAG, "Failed to finalize " + cid);
11172                    PackageHelper.destroySdDir(cid);
11173                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11174                }
11175            }
11176
11177            return PackageManager.INSTALL_SUCCEEDED;
11178        }
11179    }
11180
11181    /**
11182     * Logic to handle movement of existing installed applications.
11183     */
11184    class MoveInstallArgs extends InstallArgs {
11185        private File codeFile;
11186        private File resourceFile;
11187
11188        /** New install */
11189        MoveInstallArgs(InstallParams params) {
11190            super(params.origin, params.move, params.observer, params.installFlags,
11191                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11192                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11193        }
11194
11195        int copyApk(IMediaContainerService imcs, boolean temp) {
11196            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11197                    + move.fromUuid + " to " + move.toUuid);
11198            synchronized (mInstaller) {
11199                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11200                        move.dataAppName, move.appId, move.seinfo) != 0) {
11201                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11202                }
11203            }
11204
11205            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11206            resourceFile = codeFile;
11207            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11208
11209            return PackageManager.INSTALL_SUCCEEDED;
11210        }
11211
11212        int doPreInstall(int status) {
11213            if (status != PackageManager.INSTALL_SUCCEEDED) {
11214                cleanUp();
11215            }
11216            return status;
11217        }
11218
11219        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11220            if (status != PackageManager.INSTALL_SUCCEEDED) {
11221                cleanUp();
11222                return false;
11223            }
11224
11225            // Reflect the move in app info
11226            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11227            pkg.applicationInfo.setCodePath(pkg.codePath);
11228            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11229            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11230            pkg.applicationInfo.setResourcePath(pkg.codePath);
11231            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11232            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11233
11234            return true;
11235        }
11236
11237        int doPostInstall(int status, int uid) {
11238            if (status != PackageManager.INSTALL_SUCCEEDED) {
11239                cleanUp();
11240            }
11241            return status;
11242        }
11243
11244        @Override
11245        String getCodePath() {
11246            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11247        }
11248
11249        @Override
11250        String getResourcePath() {
11251            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11252        }
11253
11254        private boolean cleanUp() {
11255            if (codeFile == null || !codeFile.exists()) {
11256                return false;
11257            }
11258
11259            if (codeFile.isDirectory()) {
11260                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11261            } else {
11262                codeFile.delete();
11263            }
11264
11265            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11266                resourceFile.delete();
11267            }
11268
11269            return true;
11270        }
11271
11272        void cleanUpResourcesLI() {
11273            cleanUp();
11274        }
11275
11276        boolean doPostDeleteLI(boolean delete) {
11277            // XXX err, shouldn't we respect the delete flag?
11278            cleanUpResourcesLI();
11279            return true;
11280        }
11281    }
11282
11283    static String getAsecPackageName(String packageCid) {
11284        int idx = packageCid.lastIndexOf("-");
11285        if (idx == -1) {
11286            return packageCid;
11287        }
11288        return packageCid.substring(0, idx);
11289    }
11290
11291    // Utility method used to create code paths based on package name and available index.
11292    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11293        String idxStr = "";
11294        int idx = 1;
11295        // Fall back to default value of idx=1 if prefix is not
11296        // part of oldCodePath
11297        if (oldCodePath != null) {
11298            String subStr = oldCodePath;
11299            // Drop the suffix right away
11300            if (suffix != null && subStr.endsWith(suffix)) {
11301                subStr = subStr.substring(0, subStr.length() - suffix.length());
11302            }
11303            // If oldCodePath already contains prefix find out the
11304            // ending index to either increment or decrement.
11305            int sidx = subStr.lastIndexOf(prefix);
11306            if (sidx != -1) {
11307                subStr = subStr.substring(sidx + prefix.length());
11308                if (subStr != null) {
11309                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11310                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11311                    }
11312                    try {
11313                        idx = Integer.parseInt(subStr);
11314                        if (idx <= 1) {
11315                            idx++;
11316                        } else {
11317                            idx--;
11318                        }
11319                    } catch(NumberFormatException e) {
11320                    }
11321                }
11322            }
11323        }
11324        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11325        return prefix + idxStr;
11326    }
11327
11328    private File getNextCodePath(File targetDir, String packageName) {
11329        int suffix = 1;
11330        File result;
11331        do {
11332            result = new File(targetDir, packageName + "-" + suffix);
11333            suffix++;
11334        } while (result.exists());
11335        return result;
11336    }
11337
11338    // Utility method that returns the relative package path with respect
11339    // to the installation directory. Like say for /data/data/com.test-1.apk
11340    // string com.test-1 is returned.
11341    static String deriveCodePathName(String codePath) {
11342        if (codePath == null) {
11343            return null;
11344        }
11345        final File codeFile = new File(codePath);
11346        final String name = codeFile.getName();
11347        if (codeFile.isDirectory()) {
11348            return name;
11349        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11350            final int lastDot = name.lastIndexOf('.');
11351            return name.substring(0, lastDot);
11352        } else {
11353            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11354            return null;
11355        }
11356    }
11357
11358    class PackageInstalledInfo {
11359        String name;
11360        int uid;
11361        // The set of users that originally had this package installed.
11362        int[] origUsers;
11363        // The set of users that now have this package installed.
11364        int[] newUsers;
11365        PackageParser.Package pkg;
11366        int returnCode;
11367        String returnMsg;
11368        PackageRemovedInfo removedInfo;
11369
11370        public void setError(int code, String msg) {
11371            returnCode = code;
11372            returnMsg = msg;
11373            Slog.w(TAG, msg);
11374        }
11375
11376        public void setError(String msg, PackageParserException e) {
11377            returnCode = e.error;
11378            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11379            Slog.w(TAG, msg, e);
11380        }
11381
11382        public void setError(String msg, PackageManagerException e) {
11383            returnCode = e.error;
11384            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11385            Slog.w(TAG, msg, e);
11386        }
11387
11388        // In some error cases we want to convey more info back to the observer
11389        String origPackage;
11390        String origPermission;
11391    }
11392
11393    /*
11394     * Install a non-existing package.
11395     */
11396    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11397            UserHandle user, String installerPackageName, String volumeUuid,
11398            PackageInstalledInfo res) {
11399        // Remember this for later, in case we need to rollback this install
11400        String pkgName = pkg.packageName;
11401
11402        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11403        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11404                UserHandle.USER_OWNER).exists();
11405        synchronized(mPackages) {
11406            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11407                // A package with the same name is already installed, though
11408                // it has been renamed to an older name.  The package we
11409                // are trying to install should be installed as an update to
11410                // the existing one, but that has not been requested, so bail.
11411                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11412                        + " without first uninstalling package running as "
11413                        + mSettings.mRenamedPackages.get(pkgName));
11414                return;
11415            }
11416            if (mPackages.containsKey(pkgName)) {
11417                // Don't allow installation over an existing package with the same name.
11418                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11419                        + " without first uninstalling.");
11420                return;
11421            }
11422        }
11423
11424        try {
11425            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11426                    System.currentTimeMillis(), user);
11427
11428            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11429            // delete the partially installed application. the data directory will have to be
11430            // restored if it was already existing
11431            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11432                // remove package from internal structures.  Note that we want deletePackageX to
11433                // delete the package data and cache directories that it created in
11434                // scanPackageLocked, unless those directories existed before we even tried to
11435                // install.
11436                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11437                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11438                                res.removedInfo, true);
11439            }
11440
11441        } catch (PackageManagerException e) {
11442            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11443        }
11444    }
11445
11446    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11447        // Can't rotate keys during boot or if sharedUser.
11448        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11449                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11450            return false;
11451        }
11452        // app is using upgradeKeySets; make sure all are valid
11453        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11454        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11455        for (int i = 0; i < upgradeKeySets.length; i++) {
11456            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11457                Slog.wtf(TAG, "Package "
11458                         + (oldPs.name != null ? oldPs.name : "<null>")
11459                         + " contains upgrade-key-set reference to unknown key-set: "
11460                         + upgradeKeySets[i]
11461                         + " reverting to signatures check.");
11462                return false;
11463            }
11464        }
11465        return true;
11466    }
11467
11468    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11469        // Upgrade keysets are being used.  Determine if new package has a superset of the
11470        // required keys.
11471        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11472        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11473        for (int i = 0; i < upgradeKeySets.length; i++) {
11474            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11475            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11476                return true;
11477            }
11478        }
11479        return false;
11480    }
11481
11482    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11483            UserHandle user, String installerPackageName, String volumeUuid,
11484            PackageInstalledInfo res) {
11485        final PackageParser.Package oldPackage;
11486        final String pkgName = pkg.packageName;
11487        final int[] allUsers;
11488        final boolean[] perUserInstalled;
11489        final boolean weFroze;
11490
11491        // First find the old package info and check signatures
11492        synchronized(mPackages) {
11493            oldPackage = mPackages.get(pkgName);
11494            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11495            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11496            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11497                if(!checkUpgradeKeySetLP(ps, pkg)) {
11498                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11499                            "New package not signed by keys specified by upgrade-keysets: "
11500                            + pkgName);
11501                    return;
11502                }
11503            } else {
11504                // default to original signature matching
11505                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11506                    != PackageManager.SIGNATURE_MATCH) {
11507                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11508                            "New package has a different signature: " + pkgName);
11509                    return;
11510                }
11511            }
11512
11513            // In case of rollback, remember per-user/profile install state
11514            allUsers = sUserManager.getUserIds();
11515            perUserInstalled = new boolean[allUsers.length];
11516            for (int i = 0; i < allUsers.length; i++) {
11517                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11518            }
11519
11520            // Mark the app as frozen to prevent launching during the upgrade
11521            // process, and then kill all running instances
11522            if (!ps.frozen) {
11523                ps.frozen = true;
11524                weFroze = true;
11525            } else {
11526                weFroze = false;
11527            }
11528        }
11529
11530        // Now that we're guarded by frozen state, kill app during upgrade
11531        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11532
11533        try {
11534            boolean sysPkg = (isSystemApp(oldPackage));
11535            if (sysPkg) {
11536                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11537                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11538            } else {
11539                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11540                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11541            }
11542        } finally {
11543            // Regardless of success or failure of upgrade steps above, always
11544            // unfreeze the package if we froze it
11545            if (weFroze) {
11546                unfreezePackage(pkgName);
11547            }
11548        }
11549    }
11550
11551    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11552            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11553            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11554            String volumeUuid, PackageInstalledInfo res) {
11555        String pkgName = deletedPackage.packageName;
11556        boolean deletedPkg = true;
11557        boolean updatedSettings = false;
11558
11559        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11560                + deletedPackage);
11561        long origUpdateTime;
11562        if (pkg.mExtras != null) {
11563            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11564        } else {
11565            origUpdateTime = 0;
11566        }
11567
11568        // First delete the existing package while retaining the data directory
11569        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11570                res.removedInfo, true)) {
11571            // If the existing package wasn't successfully deleted
11572            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11573            deletedPkg = false;
11574        } else {
11575            // Successfully deleted the old package; proceed with replace.
11576
11577            // If deleted package lived in a container, give users a chance to
11578            // relinquish resources before killing.
11579            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11580                if (DEBUG_INSTALL) {
11581                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11582                }
11583                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11584                final ArrayList<String> pkgList = new ArrayList<String>(1);
11585                pkgList.add(deletedPackage.applicationInfo.packageName);
11586                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11587            }
11588
11589            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11590            try {
11591                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11592                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11593                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11594                        perUserInstalled, res, user);
11595                updatedSettings = true;
11596            } catch (PackageManagerException e) {
11597                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11598            }
11599        }
11600
11601        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11602            // remove package from internal structures.  Note that we want deletePackageX to
11603            // delete the package data and cache directories that it created in
11604            // scanPackageLocked, unless those directories existed before we even tried to
11605            // install.
11606            if(updatedSettings) {
11607                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11608                deletePackageLI(
11609                        pkgName, null, true, allUsers, perUserInstalled,
11610                        PackageManager.DELETE_KEEP_DATA,
11611                                res.removedInfo, true);
11612            }
11613            // Since we failed to install the new package we need to restore the old
11614            // package that we deleted.
11615            if (deletedPkg) {
11616                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11617                File restoreFile = new File(deletedPackage.codePath);
11618                // Parse old package
11619                boolean oldExternal = isExternal(deletedPackage);
11620                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11621                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11622                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11623                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11624                try {
11625                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11626                } catch (PackageManagerException e) {
11627                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11628                            + e.getMessage());
11629                    return;
11630                }
11631                // Restore of old package succeeded. Update permissions.
11632                // writer
11633                synchronized (mPackages) {
11634                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11635                            UPDATE_PERMISSIONS_ALL);
11636                    // can downgrade to reader
11637                    mSettings.writeLPr();
11638                }
11639                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11640            }
11641        }
11642    }
11643
11644    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11645            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11646            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11647            String volumeUuid, PackageInstalledInfo res) {
11648        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11649                + ", old=" + deletedPackage);
11650        boolean disabledSystem = false;
11651        boolean updatedSettings = false;
11652        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11653        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11654                != 0) {
11655            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11656        }
11657        String packageName = deletedPackage.packageName;
11658        if (packageName == null) {
11659            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11660                    "Attempt to delete null packageName.");
11661            return;
11662        }
11663        PackageParser.Package oldPkg;
11664        PackageSetting oldPkgSetting;
11665        // reader
11666        synchronized (mPackages) {
11667            oldPkg = mPackages.get(packageName);
11668            oldPkgSetting = mSettings.mPackages.get(packageName);
11669            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11670                    (oldPkgSetting == null)) {
11671                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11672                        "Couldn't find package:" + packageName + " information");
11673                return;
11674            }
11675        }
11676
11677        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11678        res.removedInfo.removedPackage = packageName;
11679        // Remove existing system package
11680        removePackageLI(oldPkgSetting, true);
11681        // writer
11682        synchronized (mPackages) {
11683            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11684            if (!disabledSystem && deletedPackage != null) {
11685                // We didn't need to disable the .apk as a current system package,
11686                // which means we are replacing another update that is already
11687                // installed.  We need to make sure to delete the older one's .apk.
11688                res.removedInfo.args = createInstallArgsForExisting(0,
11689                        deletedPackage.applicationInfo.getCodePath(),
11690                        deletedPackage.applicationInfo.getResourcePath(),
11691                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11692            } else {
11693                res.removedInfo.args = null;
11694            }
11695        }
11696
11697        // Successfully disabled the old package. Now proceed with re-installation
11698        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11699
11700        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11701        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11702
11703        PackageParser.Package newPackage = null;
11704        try {
11705            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11706            if (newPackage.mExtras != null) {
11707                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11708                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11709                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11710
11711                // is the update attempting to change shared user? that isn't going to work...
11712                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11713                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11714                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11715                            + " to " + newPkgSetting.sharedUser);
11716                    updatedSettings = true;
11717                }
11718            }
11719
11720            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11721                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11722                        perUserInstalled, res, user);
11723                updatedSettings = true;
11724            }
11725
11726        } catch (PackageManagerException e) {
11727            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11728        }
11729
11730        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11731            // Re installation failed. Restore old information
11732            // Remove new pkg information
11733            if (newPackage != null) {
11734                removeInstalledPackageLI(newPackage, true);
11735            }
11736            // Add back the old system package
11737            try {
11738                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11739            } catch (PackageManagerException e) {
11740                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11741            }
11742            // Restore the old system information in Settings
11743            synchronized (mPackages) {
11744                if (disabledSystem) {
11745                    mSettings.enableSystemPackageLPw(packageName);
11746                }
11747                if (updatedSettings) {
11748                    mSettings.setInstallerPackageName(packageName,
11749                            oldPkgSetting.installerPackageName);
11750                }
11751                mSettings.writeLPr();
11752            }
11753        }
11754    }
11755
11756    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11757            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11758            UserHandle user) {
11759        String pkgName = newPackage.packageName;
11760        synchronized (mPackages) {
11761            //write settings. the installStatus will be incomplete at this stage.
11762            //note that the new package setting would have already been
11763            //added to mPackages. It hasn't been persisted yet.
11764            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11765            mSettings.writeLPr();
11766        }
11767
11768        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11769
11770        synchronized (mPackages) {
11771            updatePermissionsLPw(newPackage.packageName, newPackage,
11772                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11773                            ? UPDATE_PERMISSIONS_ALL : 0));
11774            // For system-bundled packages, we assume that installing an upgraded version
11775            // of the package implies that the user actually wants to run that new code,
11776            // so we enable the package.
11777            PackageSetting ps = mSettings.mPackages.get(pkgName);
11778            if (ps != null) {
11779                if (isSystemApp(newPackage)) {
11780                    // NB: implicit assumption that system package upgrades apply to all users
11781                    if (DEBUG_INSTALL) {
11782                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11783                    }
11784                    if (res.origUsers != null) {
11785                        for (int userHandle : res.origUsers) {
11786                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11787                                    userHandle, installerPackageName);
11788                        }
11789                    }
11790                    // Also convey the prior install/uninstall state
11791                    if (allUsers != null && perUserInstalled != null) {
11792                        for (int i = 0; i < allUsers.length; i++) {
11793                            if (DEBUG_INSTALL) {
11794                                Slog.d(TAG, "    user " + allUsers[i]
11795                                        + " => " + perUserInstalled[i]);
11796                            }
11797                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11798                        }
11799                        // these install state changes will be persisted in the
11800                        // upcoming call to mSettings.writeLPr().
11801                    }
11802                }
11803                // It's implied that when a user requests installation, they want the app to be
11804                // installed and enabled.
11805                int userId = user.getIdentifier();
11806                if (userId != UserHandle.USER_ALL) {
11807                    ps.setInstalled(true, userId);
11808                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11809                }
11810            }
11811            res.name = pkgName;
11812            res.uid = newPackage.applicationInfo.uid;
11813            res.pkg = newPackage;
11814            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11815            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11816            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11817            //to update install status
11818            mSettings.writeLPr();
11819        }
11820    }
11821
11822    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11823        final int installFlags = args.installFlags;
11824        final String installerPackageName = args.installerPackageName;
11825        final String volumeUuid = args.volumeUuid;
11826        final File tmpPackageFile = new File(args.getCodePath());
11827        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11828        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11829                || (args.volumeUuid != null));
11830        boolean replace = false;
11831        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11832        if (args.move != null) {
11833            // moving a complete application; perfom an initial scan on the new install location
11834            scanFlags |= SCAN_INITIAL;
11835        }
11836        // Result object to be returned
11837        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11838
11839        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11840        // Retrieve PackageSettings and parse package
11841        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11842                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11843                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11844        PackageParser pp = new PackageParser();
11845        pp.setSeparateProcesses(mSeparateProcesses);
11846        pp.setDisplayMetrics(mMetrics);
11847
11848        final PackageParser.Package pkg;
11849        try {
11850            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11851        } catch (PackageParserException e) {
11852            res.setError("Failed parse during installPackageLI", e);
11853            return;
11854        }
11855
11856        // Mark that we have an install time CPU ABI override.
11857        pkg.cpuAbiOverride = args.abiOverride;
11858
11859        String pkgName = res.name = pkg.packageName;
11860        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11861            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11862                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11863                return;
11864            }
11865        }
11866
11867        try {
11868            pp.collectCertificates(pkg, parseFlags);
11869            pp.collectManifestDigest(pkg);
11870        } catch (PackageParserException e) {
11871            res.setError("Failed collect during installPackageLI", e);
11872            return;
11873        }
11874
11875        /* If the installer passed in a manifest digest, compare it now. */
11876        if (args.manifestDigest != null) {
11877            if (DEBUG_INSTALL) {
11878                final String parsedManifest = pkg.manifestDigest == null ? "null"
11879                        : pkg.manifestDigest.toString();
11880                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11881                        + parsedManifest);
11882            }
11883
11884            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11885                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11886                return;
11887            }
11888        } else if (DEBUG_INSTALL) {
11889            final String parsedManifest = pkg.manifestDigest == null
11890                    ? "null" : pkg.manifestDigest.toString();
11891            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11892        }
11893
11894        // Get rid of all references to package scan path via parser.
11895        pp = null;
11896        String oldCodePath = null;
11897        boolean systemApp = false;
11898        synchronized (mPackages) {
11899            // Check if installing already existing package
11900            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11901                String oldName = mSettings.mRenamedPackages.get(pkgName);
11902                if (pkg.mOriginalPackages != null
11903                        && pkg.mOriginalPackages.contains(oldName)
11904                        && mPackages.containsKey(oldName)) {
11905                    // This package is derived from an original package,
11906                    // and this device has been updating from that original
11907                    // name.  We must continue using the original name, so
11908                    // rename the new package here.
11909                    pkg.setPackageName(oldName);
11910                    pkgName = pkg.packageName;
11911                    replace = true;
11912                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11913                            + oldName + " pkgName=" + pkgName);
11914                } else if (mPackages.containsKey(pkgName)) {
11915                    // This package, under its official name, already exists
11916                    // on the device; we should replace it.
11917                    replace = true;
11918                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11919                }
11920
11921                // Prevent apps opting out from runtime permissions
11922                if (replace) {
11923                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11924                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11925                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11926                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11927                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11928                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11929                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11930                                        + " doesn't support runtime permissions but the old"
11931                                        + " target SDK " + oldTargetSdk + " does.");
11932                        return;
11933                    }
11934                }
11935            }
11936
11937            PackageSetting ps = mSettings.mPackages.get(pkgName);
11938            if (ps != null) {
11939                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11940
11941                // Quick sanity check that we're signed correctly if updating;
11942                // we'll check this again later when scanning, but we want to
11943                // bail early here before tripping over redefined permissions.
11944                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11945                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11946                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11947                                + pkg.packageName + " upgrade keys do not match the "
11948                                + "previously installed version");
11949                        return;
11950                    }
11951                } else {
11952                    try {
11953                        verifySignaturesLP(ps, pkg);
11954                    } catch (PackageManagerException e) {
11955                        res.setError(e.error, e.getMessage());
11956                        return;
11957                    }
11958                }
11959
11960                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11961                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11962                    systemApp = (ps.pkg.applicationInfo.flags &
11963                            ApplicationInfo.FLAG_SYSTEM) != 0;
11964                }
11965                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11966            }
11967
11968            // Check whether the newly-scanned package wants to define an already-defined perm
11969            int N = pkg.permissions.size();
11970            for (int i = N-1; i >= 0; i--) {
11971                PackageParser.Permission perm = pkg.permissions.get(i);
11972                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11973                if (bp != null) {
11974                    // If the defining package is signed with our cert, it's okay.  This
11975                    // also includes the "updating the same package" case, of course.
11976                    // "updating same package" could also involve key-rotation.
11977                    final boolean sigsOk;
11978                    if (bp.sourcePackage.equals(pkg.packageName)
11979                            && (bp.packageSetting instanceof PackageSetting)
11980                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11981                                    scanFlags))) {
11982                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11983                    } else {
11984                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11985                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11986                    }
11987                    if (!sigsOk) {
11988                        // If the owning package is the system itself, we log but allow
11989                        // install to proceed; we fail the install on all other permission
11990                        // redefinitions.
11991                        if (!bp.sourcePackage.equals("android")) {
11992                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11993                                    + pkg.packageName + " attempting to redeclare permission "
11994                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11995                            res.origPermission = perm.info.name;
11996                            res.origPackage = bp.sourcePackage;
11997                            return;
11998                        } else {
11999                            Slog.w(TAG, "Package " + pkg.packageName
12000                                    + " attempting to redeclare system permission "
12001                                    + perm.info.name + "; ignoring new declaration");
12002                            pkg.permissions.remove(i);
12003                        }
12004                    }
12005                }
12006            }
12007
12008        }
12009
12010        if (systemApp && onExternal) {
12011            // Disable updates to system apps on sdcard
12012            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12013                    "Cannot install updates to system apps on sdcard");
12014            return;
12015        }
12016
12017        if (args.move != null) {
12018            // We did an in-place move, so dex is ready to roll
12019            scanFlags |= SCAN_NO_DEX;
12020            scanFlags |= SCAN_MOVE;
12021        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12022            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12023            scanFlags |= SCAN_NO_DEX;
12024
12025            try {
12026                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12027                        true /* extract libs */);
12028            } catch (PackageManagerException pme) {
12029                Slog.e(TAG, "Error deriving application ABI", pme);
12030                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12031                return;
12032            }
12033
12034            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12035            int result = mPackageDexOptimizer
12036                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12037                            false /* defer */, false /* inclDependencies */);
12038            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12039                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12040                return;
12041            }
12042        }
12043
12044        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12045            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12046            return;
12047        }
12048
12049        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12050
12051        if (replace) {
12052            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12053                    installerPackageName, volumeUuid, res);
12054        } else {
12055            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12056                    args.user, installerPackageName, volumeUuid, res);
12057        }
12058        synchronized (mPackages) {
12059            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12060            if (ps != null) {
12061                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12062            }
12063        }
12064    }
12065
12066    private void startIntentFilterVerifications(int userId, boolean replacing,
12067            PackageParser.Package pkg) {
12068        if (mIntentFilterVerifierComponent == null) {
12069            Slog.w(TAG, "No IntentFilter verification will not be done as "
12070                    + "there is no IntentFilterVerifier available!");
12071            return;
12072        }
12073
12074        final int verifierUid = getPackageUid(
12075                mIntentFilterVerifierComponent.getPackageName(),
12076                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12077
12078        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12079        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12080        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12081        mHandler.sendMessage(msg);
12082    }
12083
12084    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12085            PackageParser.Package pkg) {
12086        int size = pkg.activities.size();
12087        if (size == 0) {
12088            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12089                    "No activity, so no need to verify any IntentFilter!");
12090            return;
12091        }
12092
12093        final boolean hasDomainURLs = hasDomainURLs(pkg);
12094        if (!hasDomainURLs) {
12095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12096                    "No domain URLs, so no need to verify any IntentFilter!");
12097            return;
12098        }
12099
12100        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12101                + " if any IntentFilter from the " + size
12102                + " Activities needs verification ...");
12103
12104        int count = 0;
12105        final String packageName = pkg.packageName;
12106
12107        synchronized (mPackages) {
12108            // If this is a new install and we see that we've already run verification for this
12109            // package, we have nothing to do: it means the state was restored from backup.
12110            if (!replacing) {
12111                IntentFilterVerificationInfo ivi =
12112                        mSettings.getIntentFilterVerificationLPr(packageName);
12113                if (ivi != null) {
12114                    if (DEBUG_DOMAIN_VERIFICATION) {
12115                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12116                                + ivi.getStatusString());
12117                    }
12118                    return;
12119                }
12120            }
12121
12122            // If any filters need to be verified, then all need to be.
12123            boolean needToVerify = false;
12124            for (PackageParser.Activity a : pkg.activities) {
12125                for (ActivityIntentInfo filter : a.intents) {
12126                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12127                        if (DEBUG_DOMAIN_VERIFICATION) {
12128                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12129                        }
12130                        needToVerify = true;
12131                        break;
12132                    }
12133                }
12134            }
12135
12136            if (needToVerify) {
12137                final int verificationId = mIntentFilterVerificationToken++;
12138                for (PackageParser.Activity a : pkg.activities) {
12139                    for (ActivityIntentInfo filter : a.intents) {
12140                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12141                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12142                                    "Verification needed for IntentFilter:" + filter.toString());
12143                            mIntentFilterVerifier.addOneIntentFilterVerification(
12144                                    verifierUid, userId, verificationId, filter, packageName);
12145                            count++;
12146                        }
12147                    }
12148                }
12149            }
12150        }
12151
12152        if (count > 0) {
12153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12154                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12155                    +  " for userId:" + userId);
12156            mIntentFilterVerifier.startVerifications(userId);
12157        } else {
12158            if (DEBUG_DOMAIN_VERIFICATION) {
12159                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12160            }
12161        }
12162    }
12163
12164    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12165        final ComponentName cn  = filter.activity.getComponentName();
12166        final String packageName = cn.getPackageName();
12167
12168        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12169                packageName);
12170        if (ivi == null) {
12171            return true;
12172        }
12173        int status = ivi.getStatus();
12174        switch (status) {
12175            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12176            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12177                return true;
12178
12179            default:
12180                // Nothing to do
12181                return false;
12182        }
12183    }
12184
12185    private static boolean isMultiArch(PackageSetting ps) {
12186        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12187    }
12188
12189    private static boolean isMultiArch(ApplicationInfo info) {
12190        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12191    }
12192
12193    private static boolean isExternal(PackageParser.Package pkg) {
12194        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12195    }
12196
12197    private static boolean isExternal(PackageSetting ps) {
12198        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12199    }
12200
12201    private static boolean isExternal(ApplicationInfo info) {
12202        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12203    }
12204
12205    private static boolean isSystemApp(PackageParser.Package pkg) {
12206        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12207    }
12208
12209    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12210        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12211    }
12212
12213    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12214        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12215    }
12216
12217    private static boolean isSystemApp(PackageSetting ps) {
12218        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12219    }
12220
12221    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12222        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12223    }
12224
12225    private int packageFlagsToInstallFlags(PackageSetting ps) {
12226        int installFlags = 0;
12227        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12228            // This existing package was an external ASEC install when we have
12229            // the external flag without a UUID
12230            installFlags |= PackageManager.INSTALL_EXTERNAL;
12231        }
12232        if (ps.isForwardLocked()) {
12233            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12234        }
12235        return installFlags;
12236    }
12237
12238    private void deleteTempPackageFiles() {
12239        final FilenameFilter filter = new FilenameFilter() {
12240            public boolean accept(File dir, String name) {
12241                return name.startsWith("vmdl") && name.endsWith(".tmp");
12242            }
12243        };
12244        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12245            file.delete();
12246        }
12247    }
12248
12249    @Override
12250    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12251            int flags) {
12252        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12253                flags);
12254    }
12255
12256    @Override
12257    public void deletePackage(final String packageName,
12258            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12259        mContext.enforceCallingOrSelfPermission(
12260                android.Manifest.permission.DELETE_PACKAGES, null);
12261        final int uid = Binder.getCallingUid();
12262        if (UserHandle.getUserId(uid) != userId) {
12263            mContext.enforceCallingPermission(
12264                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12265                    "deletePackage for user " + userId);
12266        }
12267        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12268            try {
12269                observer.onPackageDeleted(packageName,
12270                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12271            } catch (RemoteException re) {
12272            }
12273            return;
12274        }
12275
12276        boolean uninstallBlocked = false;
12277        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12278            int[] users = sUserManager.getUserIds();
12279            for (int i = 0; i < users.length; ++i) {
12280                if (getBlockUninstallForUser(packageName, users[i])) {
12281                    uninstallBlocked = true;
12282                    break;
12283                }
12284            }
12285        } else {
12286            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12287        }
12288        if (uninstallBlocked) {
12289            try {
12290                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12291                        null);
12292            } catch (RemoteException re) {
12293            }
12294            return;
12295        }
12296
12297        if (DEBUG_REMOVE) {
12298            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12299        }
12300        // Queue up an async operation since the package deletion may take a little while.
12301        mHandler.post(new Runnable() {
12302            public void run() {
12303                mHandler.removeCallbacks(this);
12304                final int returnCode = deletePackageX(packageName, userId, flags);
12305                if (observer != null) {
12306                    try {
12307                        observer.onPackageDeleted(packageName, returnCode, null);
12308                    } catch (RemoteException e) {
12309                        Log.i(TAG, "Observer no longer exists.");
12310                    } //end catch
12311                } //end if
12312            } //end run
12313        });
12314    }
12315
12316    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12317        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12318                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12319        try {
12320            if (dpm != null) {
12321                if (dpm.isDeviceOwner(packageName)) {
12322                    return true;
12323                }
12324                int[] users;
12325                if (userId == UserHandle.USER_ALL) {
12326                    users = sUserManager.getUserIds();
12327                } else {
12328                    users = new int[]{userId};
12329                }
12330                for (int i = 0; i < users.length; ++i) {
12331                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12332                        return true;
12333                    }
12334                }
12335            }
12336        } catch (RemoteException e) {
12337        }
12338        return false;
12339    }
12340
12341    /**
12342     *  This method is an internal method that could be get invoked either
12343     *  to delete an installed package or to clean up a failed installation.
12344     *  After deleting an installed package, a broadcast is sent to notify any
12345     *  listeners that the package has been installed. For cleaning up a failed
12346     *  installation, the broadcast is not necessary since the package's
12347     *  installation wouldn't have sent the initial broadcast either
12348     *  The key steps in deleting a package are
12349     *  deleting the package information in internal structures like mPackages,
12350     *  deleting the packages base directories through installd
12351     *  updating mSettings to reflect current status
12352     *  persisting settings for later use
12353     *  sending a broadcast if necessary
12354     */
12355    private int deletePackageX(String packageName, int userId, int flags) {
12356        final PackageRemovedInfo info = new PackageRemovedInfo();
12357        final boolean res;
12358
12359        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12360                ? UserHandle.ALL : new UserHandle(userId);
12361
12362        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12363            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12364            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12365        }
12366
12367        boolean removedForAllUsers = false;
12368        boolean systemUpdate = false;
12369
12370        // for the uninstall-updates case and restricted profiles, remember the per-
12371        // userhandle installed state
12372        int[] allUsers;
12373        boolean[] perUserInstalled;
12374        synchronized (mPackages) {
12375            PackageSetting ps = mSettings.mPackages.get(packageName);
12376            allUsers = sUserManager.getUserIds();
12377            perUserInstalled = new boolean[allUsers.length];
12378            for (int i = 0; i < allUsers.length; i++) {
12379                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12380            }
12381        }
12382
12383        synchronized (mInstallLock) {
12384            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12385            res = deletePackageLI(packageName, removeForUser,
12386                    true, allUsers, perUserInstalled,
12387                    flags | REMOVE_CHATTY, info, true);
12388            systemUpdate = info.isRemovedPackageSystemUpdate;
12389            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12390                removedForAllUsers = true;
12391            }
12392            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12393                    + " removedForAllUsers=" + removedForAllUsers);
12394        }
12395
12396        if (res) {
12397            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12398
12399            // If the removed package was a system update, the old system package
12400            // was re-enabled; we need to broadcast this information
12401            if (systemUpdate) {
12402                Bundle extras = new Bundle(1);
12403                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12404                        ? info.removedAppId : info.uid);
12405                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12406
12407                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12408                        extras, null, null, null);
12409                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12410                        extras, null, null, null);
12411                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12412                        null, packageName, null, null);
12413            }
12414        }
12415        // Force a gc here.
12416        Runtime.getRuntime().gc();
12417        // Delete the resources here after sending the broadcast to let
12418        // other processes clean up before deleting resources.
12419        if (info.args != null) {
12420            synchronized (mInstallLock) {
12421                info.args.doPostDeleteLI(true);
12422            }
12423        }
12424
12425        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12426    }
12427
12428    class PackageRemovedInfo {
12429        String removedPackage;
12430        int uid = -1;
12431        int removedAppId = -1;
12432        int[] removedUsers = null;
12433        boolean isRemovedPackageSystemUpdate = false;
12434        // Clean up resources deleted packages.
12435        InstallArgs args = null;
12436
12437        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12438            Bundle extras = new Bundle(1);
12439            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12440            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12441            if (replacing) {
12442                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12443            }
12444            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12445            if (removedPackage != null) {
12446                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12447                        extras, null, null, removedUsers);
12448                if (fullRemove && !replacing) {
12449                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12450                            extras, null, null, removedUsers);
12451                }
12452            }
12453            if (removedAppId >= 0) {
12454                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12455                        removedUsers);
12456            }
12457        }
12458    }
12459
12460    /*
12461     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12462     * flag is not set, the data directory is removed as well.
12463     * make sure this flag is set for partially installed apps. If not its meaningless to
12464     * delete a partially installed application.
12465     */
12466    private void removePackageDataLI(PackageSetting ps,
12467            int[] allUserHandles, boolean[] perUserInstalled,
12468            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12469        String packageName = ps.name;
12470        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12471        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12472        // Retrieve object to delete permissions for shared user later on
12473        final PackageSetting deletedPs;
12474        // reader
12475        synchronized (mPackages) {
12476            deletedPs = mSettings.mPackages.get(packageName);
12477            if (outInfo != null) {
12478                outInfo.removedPackage = packageName;
12479                outInfo.removedUsers = deletedPs != null
12480                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12481                        : null;
12482            }
12483        }
12484        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12485            removeDataDirsLI(ps.volumeUuid, packageName);
12486            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12487        }
12488        // writer
12489        synchronized (mPackages) {
12490            if (deletedPs != null) {
12491                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12492                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12493                    clearDefaultBrowserIfNeeded(packageName);
12494                    if (outInfo != null) {
12495                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12496                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12497                    }
12498                    updatePermissionsLPw(deletedPs.name, null, 0);
12499                    if (deletedPs.sharedUser != null) {
12500                        // Remove permissions associated with package. Since runtime
12501                        // permissions are per user we have to kill the removed package
12502                        // or packages running under the shared user of the removed
12503                        // package if revoking the permissions requested only by the removed
12504                        // package is successful and this causes a change in gids.
12505                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12506                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12507                                    userId);
12508                            if (userIdToKill == UserHandle.USER_ALL
12509                                    || userIdToKill >= UserHandle.USER_OWNER) {
12510                                // If gids changed for this user, kill all affected packages.
12511                                mHandler.post(new Runnable() {
12512                                    @Override
12513                                    public void run() {
12514                                        // This has to happen with no lock held.
12515                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12516                                                KILL_APP_REASON_GIDS_CHANGED);
12517                                    }
12518                                });
12519                            break;
12520                            }
12521                        }
12522                    }
12523                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12524                }
12525                // make sure to preserve per-user disabled state if this removal was just
12526                // a downgrade of a system app to the factory package
12527                if (allUserHandles != null && perUserInstalled != null) {
12528                    if (DEBUG_REMOVE) {
12529                        Slog.d(TAG, "Propagating install state across downgrade");
12530                    }
12531                    for (int i = 0; i < allUserHandles.length; i++) {
12532                        if (DEBUG_REMOVE) {
12533                            Slog.d(TAG, "    user " + allUserHandles[i]
12534                                    + " => " + perUserInstalled[i]);
12535                        }
12536                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12537                    }
12538                }
12539            }
12540            // can downgrade to reader
12541            if (writeSettings) {
12542                // Save settings now
12543                mSettings.writeLPr();
12544            }
12545        }
12546        if (outInfo != null) {
12547            // A user ID was deleted here. Go through all users and remove it
12548            // from KeyStore.
12549            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12550        }
12551    }
12552
12553    static boolean locationIsPrivileged(File path) {
12554        try {
12555            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12556                    .getCanonicalPath();
12557            return path.getCanonicalPath().startsWith(privilegedAppDir);
12558        } catch (IOException e) {
12559            Slog.e(TAG, "Unable to access code path " + path);
12560        }
12561        return false;
12562    }
12563
12564    /*
12565     * Tries to delete system package.
12566     */
12567    private boolean deleteSystemPackageLI(PackageSetting newPs,
12568            int[] allUserHandles, boolean[] perUserInstalled,
12569            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12570        final boolean applyUserRestrictions
12571                = (allUserHandles != null) && (perUserInstalled != null);
12572        PackageSetting disabledPs = null;
12573        // Confirm if the system package has been updated
12574        // An updated system app can be deleted. This will also have to restore
12575        // the system pkg from system partition
12576        // reader
12577        synchronized (mPackages) {
12578            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12579        }
12580        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12581                + " disabledPs=" + disabledPs);
12582        if (disabledPs == null) {
12583            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12584            return false;
12585        } else if (DEBUG_REMOVE) {
12586            Slog.d(TAG, "Deleting system pkg from data partition");
12587        }
12588        if (DEBUG_REMOVE) {
12589            if (applyUserRestrictions) {
12590                Slog.d(TAG, "Remembering install states:");
12591                for (int i = 0; i < allUserHandles.length; i++) {
12592                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12593                }
12594            }
12595        }
12596        // Delete the updated package
12597        outInfo.isRemovedPackageSystemUpdate = true;
12598        if (disabledPs.versionCode < newPs.versionCode) {
12599            // Delete data for downgrades
12600            flags &= ~PackageManager.DELETE_KEEP_DATA;
12601        } else {
12602            // Preserve data by setting flag
12603            flags |= PackageManager.DELETE_KEEP_DATA;
12604        }
12605        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12606                allUserHandles, perUserInstalled, outInfo, writeSettings);
12607        if (!ret) {
12608            return false;
12609        }
12610        // writer
12611        synchronized (mPackages) {
12612            // Reinstate the old system package
12613            mSettings.enableSystemPackageLPw(newPs.name);
12614            // Remove any native libraries from the upgraded package.
12615            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12616        }
12617        // Install the system package
12618        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12619        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12620        if (locationIsPrivileged(disabledPs.codePath)) {
12621            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12622        }
12623
12624        final PackageParser.Package newPkg;
12625        try {
12626            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12627        } catch (PackageManagerException e) {
12628            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12629            return false;
12630        }
12631
12632        // writer
12633        synchronized (mPackages) {
12634            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12635            updatePermissionsLPw(newPkg.packageName, newPkg,
12636                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12637            if (applyUserRestrictions) {
12638                if (DEBUG_REMOVE) {
12639                    Slog.d(TAG, "Propagating install state across reinstall");
12640                }
12641                for (int i = 0; i < allUserHandles.length; i++) {
12642                    if (DEBUG_REMOVE) {
12643                        Slog.d(TAG, "    user " + allUserHandles[i]
12644                                + " => " + perUserInstalled[i]);
12645                    }
12646                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12647                }
12648                // Regardless of writeSettings we need to ensure that this restriction
12649                // state propagation is persisted
12650                mSettings.writeAllUsersPackageRestrictionsLPr();
12651            }
12652            // can downgrade to reader here
12653            if (writeSettings) {
12654                mSettings.writeLPr();
12655            }
12656        }
12657        return true;
12658    }
12659
12660    private boolean deleteInstalledPackageLI(PackageSetting ps,
12661            boolean deleteCodeAndResources, int flags,
12662            int[] allUserHandles, boolean[] perUserInstalled,
12663            PackageRemovedInfo outInfo, boolean writeSettings) {
12664        if (outInfo != null) {
12665            outInfo.uid = ps.appId;
12666        }
12667
12668        // Delete package data from internal structures and also remove data if flag is set
12669        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12670
12671        // Delete application code and resources
12672        if (deleteCodeAndResources && (outInfo != null)) {
12673            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12674                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12675            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12676        }
12677        return true;
12678    }
12679
12680    @Override
12681    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12682            int userId) {
12683        mContext.enforceCallingOrSelfPermission(
12684                android.Manifest.permission.DELETE_PACKAGES, null);
12685        synchronized (mPackages) {
12686            PackageSetting ps = mSettings.mPackages.get(packageName);
12687            if (ps == null) {
12688                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12689                return false;
12690            }
12691            if (!ps.getInstalled(userId)) {
12692                // Can't block uninstall for an app that is not installed or enabled.
12693                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12694                return false;
12695            }
12696            ps.setBlockUninstall(blockUninstall, userId);
12697            mSettings.writePackageRestrictionsLPr(userId);
12698        }
12699        return true;
12700    }
12701
12702    @Override
12703    public boolean getBlockUninstallForUser(String packageName, int userId) {
12704        synchronized (mPackages) {
12705            PackageSetting ps = mSettings.mPackages.get(packageName);
12706            if (ps == null) {
12707                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12708                return false;
12709            }
12710            return ps.getBlockUninstall(userId);
12711        }
12712    }
12713
12714    /*
12715     * This method handles package deletion in general
12716     */
12717    private boolean deletePackageLI(String packageName, UserHandle user,
12718            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12719            int flags, PackageRemovedInfo outInfo,
12720            boolean writeSettings) {
12721        if (packageName == null) {
12722            Slog.w(TAG, "Attempt to delete null packageName.");
12723            return false;
12724        }
12725        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12726        PackageSetting ps;
12727        boolean dataOnly = false;
12728        int removeUser = -1;
12729        int appId = -1;
12730        synchronized (mPackages) {
12731            ps = mSettings.mPackages.get(packageName);
12732            if (ps == null) {
12733                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12734                return false;
12735            }
12736            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12737                    && user.getIdentifier() != UserHandle.USER_ALL) {
12738                // The caller is asking that the package only be deleted for a single
12739                // user.  To do this, we just mark its uninstalled state and delete
12740                // its data.  If this is a system app, we only allow this to happen if
12741                // they have set the special DELETE_SYSTEM_APP which requests different
12742                // semantics than normal for uninstalling system apps.
12743                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12744                ps.setUserState(user.getIdentifier(),
12745                        COMPONENT_ENABLED_STATE_DEFAULT,
12746                        false, //installed
12747                        true,  //stopped
12748                        true,  //notLaunched
12749                        false, //hidden
12750                        null, null, null,
12751                        false, // blockUninstall
12752                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12753                if (!isSystemApp(ps)) {
12754                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12755                        // Other user still have this package installed, so all
12756                        // we need to do is clear this user's data and save that
12757                        // it is uninstalled.
12758                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12759                        removeUser = user.getIdentifier();
12760                        appId = ps.appId;
12761                        scheduleWritePackageRestrictionsLocked(removeUser);
12762                    } else {
12763                        // We need to set it back to 'installed' so the uninstall
12764                        // broadcasts will be sent correctly.
12765                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12766                        ps.setInstalled(true, user.getIdentifier());
12767                    }
12768                } else {
12769                    // This is a system app, so we assume that the
12770                    // other users still have this package installed, so all
12771                    // we need to do is clear this user's data and save that
12772                    // it is uninstalled.
12773                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12774                    removeUser = user.getIdentifier();
12775                    appId = ps.appId;
12776                    scheduleWritePackageRestrictionsLocked(removeUser);
12777                }
12778            }
12779        }
12780
12781        if (removeUser >= 0) {
12782            // From above, we determined that we are deleting this only
12783            // for a single user.  Continue the work here.
12784            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12785            if (outInfo != null) {
12786                outInfo.removedPackage = packageName;
12787                outInfo.removedAppId = appId;
12788                outInfo.removedUsers = new int[] {removeUser};
12789            }
12790            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12791            removeKeystoreDataIfNeeded(removeUser, appId);
12792            schedulePackageCleaning(packageName, removeUser, false);
12793            synchronized (mPackages) {
12794                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12795                    scheduleWritePackageRestrictionsLocked(removeUser);
12796                }
12797                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12798                        removeUser);
12799            }
12800            return true;
12801        }
12802
12803        if (dataOnly) {
12804            // Delete application data first
12805            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12806            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12807            return true;
12808        }
12809
12810        boolean ret = false;
12811        if (isSystemApp(ps)) {
12812            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12813            // When an updated system application is deleted we delete the existing resources as well and
12814            // fall back to existing code in system partition
12815            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12816                    flags, outInfo, writeSettings);
12817        } else {
12818            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12819            // Kill application pre-emptively especially for apps on sd.
12820            killApplication(packageName, ps.appId, "uninstall pkg");
12821            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12822                    allUserHandles, perUserInstalled,
12823                    outInfo, writeSettings);
12824        }
12825
12826        return ret;
12827    }
12828
12829    private final class ClearStorageConnection implements ServiceConnection {
12830        IMediaContainerService mContainerService;
12831
12832        @Override
12833        public void onServiceConnected(ComponentName name, IBinder service) {
12834            synchronized (this) {
12835                mContainerService = IMediaContainerService.Stub.asInterface(service);
12836                notifyAll();
12837            }
12838        }
12839
12840        @Override
12841        public void onServiceDisconnected(ComponentName name) {
12842        }
12843    }
12844
12845    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12846        final boolean mounted;
12847        if (Environment.isExternalStorageEmulated()) {
12848            mounted = true;
12849        } else {
12850            final String status = Environment.getExternalStorageState();
12851
12852            mounted = status.equals(Environment.MEDIA_MOUNTED)
12853                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12854        }
12855
12856        if (!mounted) {
12857            return;
12858        }
12859
12860        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12861        int[] users;
12862        if (userId == UserHandle.USER_ALL) {
12863            users = sUserManager.getUserIds();
12864        } else {
12865            users = new int[] { userId };
12866        }
12867        final ClearStorageConnection conn = new ClearStorageConnection();
12868        if (mContext.bindServiceAsUser(
12869                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12870            try {
12871                for (int curUser : users) {
12872                    long timeout = SystemClock.uptimeMillis() + 5000;
12873                    synchronized (conn) {
12874                        long now = SystemClock.uptimeMillis();
12875                        while (conn.mContainerService == null && now < timeout) {
12876                            try {
12877                                conn.wait(timeout - now);
12878                            } catch (InterruptedException e) {
12879                            }
12880                        }
12881                    }
12882                    if (conn.mContainerService == null) {
12883                        return;
12884                    }
12885
12886                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12887                    clearDirectory(conn.mContainerService,
12888                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12889                    if (allData) {
12890                        clearDirectory(conn.mContainerService,
12891                                userEnv.buildExternalStorageAppDataDirs(packageName));
12892                        clearDirectory(conn.mContainerService,
12893                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12894                    }
12895                }
12896            } finally {
12897                mContext.unbindService(conn);
12898            }
12899        }
12900    }
12901
12902    @Override
12903    public void clearApplicationUserData(final String packageName,
12904            final IPackageDataObserver observer, final int userId) {
12905        mContext.enforceCallingOrSelfPermission(
12906                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12907        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12908        // Queue up an async operation since the package deletion may take a little while.
12909        mHandler.post(new Runnable() {
12910            public void run() {
12911                mHandler.removeCallbacks(this);
12912                final boolean succeeded;
12913                synchronized (mInstallLock) {
12914                    succeeded = clearApplicationUserDataLI(packageName, userId);
12915                }
12916                clearExternalStorageDataSync(packageName, userId, true);
12917                if (succeeded) {
12918                    // invoke DeviceStorageMonitor's update method to clear any notifications
12919                    DeviceStorageMonitorInternal
12920                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12921                    if (dsm != null) {
12922                        dsm.checkMemory();
12923                    }
12924                }
12925                if(observer != null) {
12926                    try {
12927                        observer.onRemoveCompleted(packageName, succeeded);
12928                    } catch (RemoteException e) {
12929                        Log.i(TAG, "Observer no longer exists.");
12930                    }
12931                } //end if observer
12932            } //end run
12933        });
12934    }
12935
12936    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12937        if (packageName == null) {
12938            Slog.w(TAG, "Attempt to delete null packageName.");
12939            return false;
12940        }
12941
12942        // Try finding details about the requested package
12943        PackageParser.Package pkg;
12944        synchronized (mPackages) {
12945            pkg = mPackages.get(packageName);
12946            if (pkg == null) {
12947                final PackageSetting ps = mSettings.mPackages.get(packageName);
12948                if (ps != null) {
12949                    pkg = ps.pkg;
12950                }
12951            }
12952
12953            if (pkg == null) {
12954                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12955                return false;
12956            }
12957
12958            PackageSetting ps = (PackageSetting) pkg.mExtras;
12959            PermissionsState permissionsState = ps.getPermissionsState();
12960            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12961        }
12962
12963        // Always delete data directories for package, even if we found no other
12964        // record of app. This helps users recover from UID mismatches without
12965        // resorting to a full data wipe.
12966        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12967        if (retCode < 0) {
12968            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12969            return false;
12970        }
12971
12972        final int appId = pkg.applicationInfo.uid;
12973        removeKeystoreDataIfNeeded(userId, appId);
12974
12975        // Create a native library symlink only if we have native libraries
12976        // and if the native libraries are 32 bit libraries. We do not provide
12977        // this symlink for 64 bit libraries.
12978        if (pkg.applicationInfo.primaryCpuAbi != null &&
12979                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12980            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12981            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12982                    nativeLibPath, userId) < 0) {
12983                Slog.w(TAG, "Failed linking native library dir");
12984                return false;
12985            }
12986        }
12987
12988        return true;
12989    }
12990
12991
12992    /**
12993     * Revokes granted runtime permissions and clears resettable flags
12994     * which are flags that can be set by a user interaction.
12995     *
12996     * @param permissionsState The permission state to reset.
12997     * @param userId The device user for which to do a reset.
12998     */
12999    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13000            PermissionsState permissionsState, int userId) {
13001        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13002                | PackageManager.FLAG_PERMISSION_USER_FIXED
13003                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13004
13005        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13006    }
13007
13008    /**
13009     * Revokes granted runtime permissions and clears all flags.
13010     *
13011     * @param permissionsState The permission state to reset.
13012     * @param userId The device user for which to do a reset.
13013     */
13014    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13015            PermissionsState permissionsState, int userId) {
13016        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13017                PackageManager.MASK_PERMISSION_FLAGS);
13018    }
13019
13020    /**
13021     * Revokes granted runtime permissions and clears certain flags.
13022     *
13023     * @param permissionsState The permission state to reset.
13024     * @param userId The device user for which to do a reset.
13025     * @param flags The flags that is going to be reset.
13026     */
13027    private void revokeRuntimePermissionsAndClearFlagsLocked(
13028            PermissionsState permissionsState, final int userId, int flags) {
13029        boolean needsWrite = false;
13030
13031        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13032            BasePermission bp = mSettings.mPermissions.get(state.getName());
13033            if (bp != null) {
13034                permissionsState.revokeRuntimePermission(bp, userId);
13035                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13036                needsWrite = true;
13037            }
13038        }
13039
13040        // Ensure default permissions are never cleared.
13041        mHandler.post(new Runnable() {
13042            @Override
13043            public void run() {
13044                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13045            }
13046        });
13047
13048        if (needsWrite) {
13049            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13050        }
13051    }
13052
13053    /**
13054     * Remove entries from the keystore daemon. Will only remove it if the
13055     * {@code appId} is valid.
13056     */
13057    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13058        if (appId < 0) {
13059            return;
13060        }
13061
13062        final KeyStore keyStore = KeyStore.getInstance();
13063        if (keyStore != null) {
13064            if (userId == UserHandle.USER_ALL) {
13065                for (final int individual : sUserManager.getUserIds()) {
13066                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13067                }
13068            } else {
13069                keyStore.clearUid(UserHandle.getUid(userId, appId));
13070            }
13071        } else {
13072            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13073        }
13074    }
13075
13076    @Override
13077    public void deleteApplicationCacheFiles(final String packageName,
13078            final IPackageDataObserver observer) {
13079        mContext.enforceCallingOrSelfPermission(
13080                android.Manifest.permission.DELETE_CACHE_FILES, null);
13081        // Queue up an async operation since the package deletion may take a little while.
13082        final int userId = UserHandle.getCallingUserId();
13083        mHandler.post(new Runnable() {
13084            public void run() {
13085                mHandler.removeCallbacks(this);
13086                final boolean succeded;
13087                synchronized (mInstallLock) {
13088                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13089                }
13090                clearExternalStorageDataSync(packageName, userId, false);
13091                if (observer != null) {
13092                    try {
13093                        observer.onRemoveCompleted(packageName, succeded);
13094                    } catch (RemoteException e) {
13095                        Log.i(TAG, "Observer no longer exists.");
13096                    }
13097                } //end if observer
13098            } //end run
13099        });
13100    }
13101
13102    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13103        if (packageName == null) {
13104            Slog.w(TAG, "Attempt to delete null packageName.");
13105            return false;
13106        }
13107        PackageParser.Package p;
13108        synchronized (mPackages) {
13109            p = mPackages.get(packageName);
13110        }
13111        if (p == null) {
13112            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13113            return false;
13114        }
13115        final ApplicationInfo applicationInfo = p.applicationInfo;
13116        if (applicationInfo == null) {
13117            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13118            return false;
13119        }
13120        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13121        if (retCode < 0) {
13122            Slog.w(TAG, "Couldn't remove cache files for package: "
13123                       + packageName + " u" + userId);
13124            return false;
13125        }
13126        return true;
13127    }
13128
13129    @Override
13130    public void getPackageSizeInfo(final String packageName, int userHandle,
13131            final IPackageStatsObserver observer) {
13132        mContext.enforceCallingOrSelfPermission(
13133                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13134        if (packageName == null) {
13135            throw new IllegalArgumentException("Attempt to get size of null packageName");
13136        }
13137
13138        PackageStats stats = new PackageStats(packageName, userHandle);
13139
13140        /*
13141         * Queue up an async operation since the package measurement may take a
13142         * little while.
13143         */
13144        Message msg = mHandler.obtainMessage(INIT_COPY);
13145        msg.obj = new MeasureParams(stats, observer);
13146        mHandler.sendMessage(msg);
13147    }
13148
13149    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13150            PackageStats pStats) {
13151        if (packageName == null) {
13152            Slog.w(TAG, "Attempt to get size of null packageName.");
13153            return false;
13154        }
13155        PackageParser.Package p;
13156        boolean dataOnly = false;
13157        String libDirRoot = null;
13158        String asecPath = null;
13159        PackageSetting ps = null;
13160        synchronized (mPackages) {
13161            p = mPackages.get(packageName);
13162            ps = mSettings.mPackages.get(packageName);
13163            if(p == null) {
13164                dataOnly = true;
13165                if((ps == null) || (ps.pkg == null)) {
13166                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13167                    return false;
13168                }
13169                p = ps.pkg;
13170            }
13171            if (ps != null) {
13172                libDirRoot = ps.legacyNativeLibraryPathString;
13173            }
13174            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13175                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13176                if (secureContainerId != null) {
13177                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13178                }
13179            }
13180        }
13181        String publicSrcDir = null;
13182        if(!dataOnly) {
13183            final ApplicationInfo applicationInfo = p.applicationInfo;
13184            if (applicationInfo == null) {
13185                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13186                return false;
13187            }
13188            if (p.isForwardLocked()) {
13189                publicSrcDir = applicationInfo.getBaseResourcePath();
13190            }
13191        }
13192        // TODO: extend to measure size of split APKs
13193        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13194        // not just the first level.
13195        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13196        // just the primary.
13197        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13198        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13199                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13200        if (res < 0) {
13201            return false;
13202        }
13203
13204        // Fix-up for forward-locked applications in ASEC containers.
13205        if (!isExternal(p)) {
13206            pStats.codeSize += pStats.externalCodeSize;
13207            pStats.externalCodeSize = 0L;
13208        }
13209
13210        return true;
13211    }
13212
13213
13214    @Override
13215    public void addPackageToPreferred(String packageName) {
13216        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13217    }
13218
13219    @Override
13220    public void removePackageFromPreferred(String packageName) {
13221        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13222    }
13223
13224    @Override
13225    public List<PackageInfo> getPreferredPackages(int flags) {
13226        return new ArrayList<PackageInfo>();
13227    }
13228
13229    private int getUidTargetSdkVersionLockedLPr(int uid) {
13230        Object obj = mSettings.getUserIdLPr(uid);
13231        if (obj instanceof SharedUserSetting) {
13232            final SharedUserSetting sus = (SharedUserSetting) obj;
13233            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13234            final Iterator<PackageSetting> it = sus.packages.iterator();
13235            while (it.hasNext()) {
13236                final PackageSetting ps = it.next();
13237                if (ps.pkg != null) {
13238                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13239                    if (v < vers) vers = v;
13240                }
13241            }
13242            return vers;
13243        } else if (obj instanceof PackageSetting) {
13244            final PackageSetting ps = (PackageSetting) obj;
13245            if (ps.pkg != null) {
13246                return ps.pkg.applicationInfo.targetSdkVersion;
13247            }
13248        }
13249        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13250    }
13251
13252    @Override
13253    public void addPreferredActivity(IntentFilter filter, int match,
13254            ComponentName[] set, ComponentName activity, int userId) {
13255        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13256                "Adding preferred");
13257    }
13258
13259    private void addPreferredActivityInternal(IntentFilter filter, int match,
13260            ComponentName[] set, ComponentName activity, boolean always, int userId,
13261            String opname) {
13262        // writer
13263        int callingUid = Binder.getCallingUid();
13264        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13265        if (filter.countActions() == 0) {
13266            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13267            return;
13268        }
13269        synchronized (mPackages) {
13270            if (mContext.checkCallingOrSelfPermission(
13271                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13272                    != PackageManager.PERMISSION_GRANTED) {
13273                if (getUidTargetSdkVersionLockedLPr(callingUid)
13274                        < Build.VERSION_CODES.FROYO) {
13275                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13276                            + callingUid);
13277                    return;
13278                }
13279                mContext.enforceCallingOrSelfPermission(
13280                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13281            }
13282
13283            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13284            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13285                    + userId + ":");
13286            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13287            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13288            scheduleWritePackageRestrictionsLocked(userId);
13289        }
13290    }
13291
13292    @Override
13293    public void replacePreferredActivity(IntentFilter filter, int match,
13294            ComponentName[] set, ComponentName activity, int userId) {
13295        if (filter.countActions() != 1) {
13296            throw new IllegalArgumentException(
13297                    "replacePreferredActivity expects filter to have only 1 action.");
13298        }
13299        if (filter.countDataAuthorities() != 0
13300                || filter.countDataPaths() != 0
13301                || filter.countDataSchemes() > 1
13302                || filter.countDataTypes() != 0) {
13303            throw new IllegalArgumentException(
13304                    "replacePreferredActivity expects filter to have no data authorities, " +
13305                    "paths, or types; and at most one scheme.");
13306        }
13307
13308        final int callingUid = Binder.getCallingUid();
13309        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13310        synchronized (mPackages) {
13311            if (mContext.checkCallingOrSelfPermission(
13312                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13313                    != PackageManager.PERMISSION_GRANTED) {
13314                if (getUidTargetSdkVersionLockedLPr(callingUid)
13315                        < Build.VERSION_CODES.FROYO) {
13316                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13317                            + Binder.getCallingUid());
13318                    return;
13319                }
13320                mContext.enforceCallingOrSelfPermission(
13321                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13322            }
13323
13324            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13325            if (pir != null) {
13326                // Get all of the existing entries that exactly match this filter.
13327                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13328                if (existing != null && existing.size() == 1) {
13329                    PreferredActivity cur = existing.get(0);
13330                    if (DEBUG_PREFERRED) {
13331                        Slog.i(TAG, "Checking replace of preferred:");
13332                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13333                        if (!cur.mPref.mAlways) {
13334                            Slog.i(TAG, "  -- CUR; not mAlways!");
13335                        } else {
13336                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13337                            Slog.i(TAG, "  -- CUR: mSet="
13338                                    + Arrays.toString(cur.mPref.mSetComponents));
13339                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13340                            Slog.i(TAG, "  -- NEW: mMatch="
13341                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13342                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13343                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13344                        }
13345                    }
13346                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13347                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13348                            && cur.mPref.sameSet(set)) {
13349                        // Setting the preferred activity to what it happens to be already
13350                        if (DEBUG_PREFERRED) {
13351                            Slog.i(TAG, "Replacing with same preferred activity "
13352                                    + cur.mPref.mShortComponent + " for user "
13353                                    + userId + ":");
13354                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13355                        }
13356                        return;
13357                    }
13358                }
13359
13360                if (existing != null) {
13361                    if (DEBUG_PREFERRED) {
13362                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13363                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13364                    }
13365                    for (int i = 0; i < existing.size(); i++) {
13366                        PreferredActivity pa = existing.get(i);
13367                        if (DEBUG_PREFERRED) {
13368                            Slog.i(TAG, "Removing existing preferred activity "
13369                                    + pa.mPref.mComponent + ":");
13370                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13371                        }
13372                        pir.removeFilter(pa);
13373                    }
13374                }
13375            }
13376            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13377                    "Replacing preferred");
13378        }
13379    }
13380
13381    @Override
13382    public void clearPackagePreferredActivities(String packageName) {
13383        final int uid = Binder.getCallingUid();
13384        // writer
13385        synchronized (mPackages) {
13386            PackageParser.Package pkg = mPackages.get(packageName);
13387            if (pkg == null || pkg.applicationInfo.uid != uid) {
13388                if (mContext.checkCallingOrSelfPermission(
13389                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13390                        != PackageManager.PERMISSION_GRANTED) {
13391                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13392                            < Build.VERSION_CODES.FROYO) {
13393                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13394                                + Binder.getCallingUid());
13395                        return;
13396                    }
13397                    mContext.enforceCallingOrSelfPermission(
13398                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13399                }
13400            }
13401
13402            int user = UserHandle.getCallingUserId();
13403            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13404                scheduleWritePackageRestrictionsLocked(user);
13405            }
13406        }
13407    }
13408
13409    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13410    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13411        ArrayList<PreferredActivity> removed = null;
13412        boolean changed = false;
13413        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13414            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13415            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13416            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13417                continue;
13418            }
13419            Iterator<PreferredActivity> it = pir.filterIterator();
13420            while (it.hasNext()) {
13421                PreferredActivity pa = it.next();
13422                // Mark entry for removal only if it matches the package name
13423                // and the entry is of type "always".
13424                if (packageName == null ||
13425                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13426                                && pa.mPref.mAlways)) {
13427                    if (removed == null) {
13428                        removed = new ArrayList<PreferredActivity>();
13429                    }
13430                    removed.add(pa);
13431                }
13432            }
13433            if (removed != null) {
13434                for (int j=0; j<removed.size(); j++) {
13435                    PreferredActivity pa = removed.get(j);
13436                    pir.removeFilter(pa);
13437                }
13438                changed = true;
13439            }
13440        }
13441        return changed;
13442    }
13443
13444    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13445    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13446        if (userId == UserHandle.USER_ALL) {
13447            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13448                    sUserManager.getUserIds())) {
13449                for (int oneUserId : sUserManager.getUserIds()) {
13450                    scheduleWritePackageRestrictionsLocked(oneUserId);
13451                }
13452            }
13453        } else {
13454            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13455                scheduleWritePackageRestrictionsLocked(userId);
13456            }
13457        }
13458    }
13459
13460
13461    void clearDefaultBrowserIfNeeded(String packageName) {
13462        for (int oneUserId : sUserManager.getUserIds()) {
13463            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13464            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13465            if (packageName.equals(defaultBrowserPackageName)) {
13466                setDefaultBrowserPackageName(null, oneUserId);
13467            }
13468        }
13469    }
13470
13471    @Override
13472    public void resetPreferredActivities(int userId) {
13473        mContext.enforceCallingOrSelfPermission(
13474                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13475        // writer
13476        synchronized (mPackages) {
13477            clearPackagePreferredActivitiesLPw(null, userId);
13478            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13479            applyFactoryDefaultBrowserLPw(userId);
13480
13481            scheduleWritePackageRestrictionsLocked(userId);
13482        }
13483    }
13484
13485    @Override
13486    public int getPreferredActivities(List<IntentFilter> outFilters,
13487            List<ComponentName> outActivities, String packageName) {
13488
13489        int num = 0;
13490        final int userId = UserHandle.getCallingUserId();
13491        // reader
13492        synchronized (mPackages) {
13493            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13494            if (pir != null) {
13495                final Iterator<PreferredActivity> it = pir.filterIterator();
13496                while (it.hasNext()) {
13497                    final PreferredActivity pa = it.next();
13498                    if (packageName == null
13499                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13500                                    && pa.mPref.mAlways)) {
13501                        if (outFilters != null) {
13502                            outFilters.add(new IntentFilter(pa));
13503                        }
13504                        if (outActivities != null) {
13505                            outActivities.add(pa.mPref.mComponent);
13506                        }
13507                    }
13508                }
13509            }
13510        }
13511
13512        return num;
13513    }
13514
13515    @Override
13516    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13517            int userId) {
13518        int callingUid = Binder.getCallingUid();
13519        if (callingUid != Process.SYSTEM_UID) {
13520            throw new SecurityException(
13521                    "addPersistentPreferredActivity can only be run by the system");
13522        }
13523        if (filter.countActions() == 0) {
13524            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13525            return;
13526        }
13527        synchronized (mPackages) {
13528            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13529                    " :");
13530            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13531            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13532                    new PersistentPreferredActivity(filter, activity));
13533            scheduleWritePackageRestrictionsLocked(userId);
13534        }
13535    }
13536
13537    @Override
13538    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13539        int callingUid = Binder.getCallingUid();
13540        if (callingUid != Process.SYSTEM_UID) {
13541            throw new SecurityException(
13542                    "clearPackagePersistentPreferredActivities can only be run by the system");
13543        }
13544        ArrayList<PersistentPreferredActivity> removed = null;
13545        boolean changed = false;
13546        synchronized (mPackages) {
13547            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13548                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13549                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13550                        .valueAt(i);
13551                if (userId != thisUserId) {
13552                    continue;
13553                }
13554                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13555                while (it.hasNext()) {
13556                    PersistentPreferredActivity ppa = it.next();
13557                    // Mark entry for removal only if it matches the package name.
13558                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13559                        if (removed == null) {
13560                            removed = new ArrayList<PersistentPreferredActivity>();
13561                        }
13562                        removed.add(ppa);
13563                    }
13564                }
13565                if (removed != null) {
13566                    for (int j=0; j<removed.size(); j++) {
13567                        PersistentPreferredActivity ppa = removed.get(j);
13568                        ppir.removeFilter(ppa);
13569                    }
13570                    changed = true;
13571                }
13572            }
13573
13574            if (changed) {
13575                scheduleWritePackageRestrictionsLocked(userId);
13576            }
13577        }
13578    }
13579
13580    /**
13581     * Common machinery for picking apart a restored XML blob and passing
13582     * it to a caller-supplied functor to be applied to the running system.
13583     */
13584    private void restoreFromXml(XmlPullParser parser, int userId,
13585            String expectedStartTag, BlobXmlRestorer functor)
13586            throws IOException, XmlPullParserException {
13587        int type;
13588        while ((type = parser.next()) != XmlPullParser.START_TAG
13589                && type != XmlPullParser.END_DOCUMENT) {
13590        }
13591        if (type != XmlPullParser.START_TAG) {
13592            // oops didn't find a start tag?!
13593            if (DEBUG_BACKUP) {
13594                Slog.e(TAG, "Didn't find start tag during restore");
13595            }
13596            return;
13597        }
13598
13599        // this is supposed to be TAG_PREFERRED_BACKUP
13600        if (!expectedStartTag.equals(parser.getName())) {
13601            if (DEBUG_BACKUP) {
13602                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13603            }
13604            return;
13605        }
13606
13607        // skip interfering stuff, then we're aligned with the backing implementation
13608        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13609        functor.apply(parser, userId);
13610    }
13611
13612    private interface BlobXmlRestorer {
13613        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13614    }
13615
13616    /**
13617     * Non-Binder method, support for the backup/restore mechanism: write the
13618     * full set of preferred activities in its canonical XML format.  Returns the
13619     * XML output as a byte array, or null if there is none.
13620     */
13621    @Override
13622    public byte[] getPreferredActivityBackup(int userId) {
13623        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13624            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13625        }
13626
13627        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13628        try {
13629            final XmlSerializer serializer = new FastXmlSerializer();
13630            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13631            serializer.startDocument(null, true);
13632            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13633
13634            synchronized (mPackages) {
13635                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13636            }
13637
13638            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13639            serializer.endDocument();
13640            serializer.flush();
13641        } catch (Exception e) {
13642            if (DEBUG_BACKUP) {
13643                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13644            }
13645            return null;
13646        }
13647
13648        return dataStream.toByteArray();
13649    }
13650
13651    @Override
13652    public void restorePreferredActivities(byte[] backup, int userId) {
13653        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13654            throw new SecurityException("Only the system may call restorePreferredActivities()");
13655        }
13656
13657        try {
13658            final XmlPullParser parser = Xml.newPullParser();
13659            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13660            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13661                    new BlobXmlRestorer() {
13662                        @Override
13663                        public void apply(XmlPullParser parser, int userId)
13664                                throws XmlPullParserException, IOException {
13665                            synchronized (mPackages) {
13666                                mSettings.readPreferredActivitiesLPw(parser, userId);
13667                            }
13668                        }
13669                    } );
13670        } catch (Exception e) {
13671            if (DEBUG_BACKUP) {
13672                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13673            }
13674        }
13675    }
13676
13677    /**
13678     * Non-Binder method, support for the backup/restore mechanism: write the
13679     * default browser (etc) settings in its canonical XML format.  Returns the default
13680     * browser XML representation as a byte array, or null if there is none.
13681     */
13682    @Override
13683    public byte[] getDefaultAppsBackup(int userId) {
13684        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13685            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13686        }
13687
13688        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13689        try {
13690            final XmlSerializer serializer = new FastXmlSerializer();
13691            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13692            serializer.startDocument(null, true);
13693            serializer.startTag(null, TAG_DEFAULT_APPS);
13694
13695            synchronized (mPackages) {
13696                mSettings.writeDefaultAppsLPr(serializer, userId);
13697            }
13698
13699            serializer.endTag(null, TAG_DEFAULT_APPS);
13700            serializer.endDocument();
13701            serializer.flush();
13702        } catch (Exception e) {
13703            if (DEBUG_BACKUP) {
13704                Slog.e(TAG, "Unable to write default apps for backup", e);
13705            }
13706            return null;
13707        }
13708
13709        return dataStream.toByteArray();
13710    }
13711
13712    @Override
13713    public void restoreDefaultApps(byte[] backup, int userId) {
13714        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13715            throw new SecurityException("Only the system may call restoreDefaultApps()");
13716        }
13717
13718        try {
13719            final XmlPullParser parser = Xml.newPullParser();
13720            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13721            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13722                    new BlobXmlRestorer() {
13723                        @Override
13724                        public void apply(XmlPullParser parser, int userId)
13725                                throws XmlPullParserException, IOException {
13726                            synchronized (mPackages) {
13727                                mSettings.readDefaultAppsLPw(parser, userId);
13728                            }
13729                        }
13730                    } );
13731        } catch (Exception e) {
13732            if (DEBUG_BACKUP) {
13733                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13734            }
13735        }
13736    }
13737
13738    @Override
13739    public byte[] getIntentFilterVerificationBackup(int userId) {
13740        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13741            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13742        }
13743
13744        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13745        try {
13746            final XmlSerializer serializer = new FastXmlSerializer();
13747            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13748            serializer.startDocument(null, true);
13749            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13750
13751            synchronized (mPackages) {
13752                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13753            }
13754
13755            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13756            serializer.endDocument();
13757            serializer.flush();
13758        } catch (Exception e) {
13759            if (DEBUG_BACKUP) {
13760                Slog.e(TAG, "Unable to write default apps for backup", e);
13761            }
13762            return null;
13763        }
13764
13765        return dataStream.toByteArray();
13766    }
13767
13768    @Override
13769    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13770        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13771            throw new SecurityException("Only the system may call restorePreferredActivities()");
13772        }
13773
13774        try {
13775            final XmlPullParser parser = Xml.newPullParser();
13776            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13777            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13778                    new BlobXmlRestorer() {
13779                        @Override
13780                        public void apply(XmlPullParser parser, int userId)
13781                                throws XmlPullParserException, IOException {
13782                            synchronized (mPackages) {
13783                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13784                                mSettings.writeLPr();
13785                            }
13786                        }
13787                    } );
13788        } catch (Exception e) {
13789            if (DEBUG_BACKUP) {
13790                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13791            }
13792        }
13793    }
13794
13795    @Override
13796    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13797            int sourceUserId, int targetUserId, int flags) {
13798        mContext.enforceCallingOrSelfPermission(
13799                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13800        int callingUid = Binder.getCallingUid();
13801        enforceOwnerRights(ownerPackage, callingUid);
13802        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13803        if (intentFilter.countActions() == 0) {
13804            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13805            return;
13806        }
13807        synchronized (mPackages) {
13808            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13809                    ownerPackage, targetUserId, flags);
13810            CrossProfileIntentResolver resolver =
13811                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13812            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13813            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13814            if (existing != null) {
13815                int size = existing.size();
13816                for (int i = 0; i < size; i++) {
13817                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13818                        return;
13819                    }
13820                }
13821            }
13822            resolver.addFilter(newFilter);
13823            scheduleWritePackageRestrictionsLocked(sourceUserId);
13824        }
13825    }
13826
13827    @Override
13828    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13829        mContext.enforceCallingOrSelfPermission(
13830                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13831        int callingUid = Binder.getCallingUid();
13832        enforceOwnerRights(ownerPackage, callingUid);
13833        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13834        synchronized (mPackages) {
13835            CrossProfileIntentResolver resolver =
13836                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13837            ArraySet<CrossProfileIntentFilter> set =
13838                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13839            for (CrossProfileIntentFilter filter : set) {
13840                if (filter.getOwnerPackage().equals(ownerPackage)) {
13841                    resolver.removeFilter(filter);
13842                }
13843            }
13844            scheduleWritePackageRestrictionsLocked(sourceUserId);
13845        }
13846    }
13847
13848    // Enforcing that callingUid is owning pkg on userId
13849    private void enforceOwnerRights(String pkg, int callingUid) {
13850        // The system owns everything.
13851        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13852            return;
13853        }
13854        int callingUserId = UserHandle.getUserId(callingUid);
13855        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13856        if (pi == null) {
13857            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13858                    + callingUserId);
13859        }
13860        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13861            throw new SecurityException("Calling uid " + callingUid
13862                    + " does not own package " + pkg);
13863        }
13864    }
13865
13866    @Override
13867    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13868        Intent intent = new Intent(Intent.ACTION_MAIN);
13869        intent.addCategory(Intent.CATEGORY_HOME);
13870
13871        final int callingUserId = UserHandle.getCallingUserId();
13872        List<ResolveInfo> list = queryIntentActivities(intent, null,
13873                PackageManager.GET_META_DATA, callingUserId);
13874        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13875                true, false, false, callingUserId);
13876
13877        allHomeCandidates.clear();
13878        if (list != null) {
13879            for (ResolveInfo ri : list) {
13880                allHomeCandidates.add(ri);
13881            }
13882        }
13883        return (preferred == null || preferred.activityInfo == null)
13884                ? null
13885                : new ComponentName(preferred.activityInfo.packageName,
13886                        preferred.activityInfo.name);
13887    }
13888
13889    @Override
13890    public void setApplicationEnabledSetting(String appPackageName,
13891            int newState, int flags, int userId, String callingPackage) {
13892        if (!sUserManager.exists(userId)) return;
13893        if (callingPackage == null) {
13894            callingPackage = Integer.toString(Binder.getCallingUid());
13895        }
13896        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13897    }
13898
13899    @Override
13900    public void setComponentEnabledSetting(ComponentName componentName,
13901            int newState, int flags, int userId) {
13902        if (!sUserManager.exists(userId)) return;
13903        setEnabledSetting(componentName.getPackageName(),
13904                componentName.getClassName(), newState, flags, userId, null);
13905    }
13906
13907    private void setEnabledSetting(final String packageName, String className, int newState,
13908            final int flags, int userId, String callingPackage) {
13909        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13910              || newState == COMPONENT_ENABLED_STATE_ENABLED
13911              || newState == COMPONENT_ENABLED_STATE_DISABLED
13912              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13913              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13914            throw new IllegalArgumentException("Invalid new component state: "
13915                    + newState);
13916        }
13917        PackageSetting pkgSetting;
13918        final int uid = Binder.getCallingUid();
13919        final int permission = mContext.checkCallingOrSelfPermission(
13920                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13921        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13922        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13923        boolean sendNow = false;
13924        boolean isApp = (className == null);
13925        String componentName = isApp ? packageName : className;
13926        int packageUid = -1;
13927        ArrayList<String> components;
13928
13929        // writer
13930        synchronized (mPackages) {
13931            pkgSetting = mSettings.mPackages.get(packageName);
13932            if (pkgSetting == null) {
13933                if (className == null) {
13934                    throw new IllegalArgumentException(
13935                            "Unknown package: " + packageName);
13936                }
13937                throw new IllegalArgumentException(
13938                        "Unknown component: " + packageName
13939                        + "/" + className);
13940            }
13941            // Allow root and verify that userId is not being specified by a different user
13942            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13943                throw new SecurityException(
13944                        "Permission Denial: attempt to change component state from pid="
13945                        + Binder.getCallingPid()
13946                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13947            }
13948            if (className == null) {
13949                // We're dealing with an application/package level state change
13950                if (pkgSetting.getEnabled(userId) == newState) {
13951                    // Nothing to do
13952                    return;
13953                }
13954                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13955                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13956                    // Don't care about who enables an app.
13957                    callingPackage = null;
13958                }
13959                pkgSetting.setEnabled(newState, userId, callingPackage);
13960                // pkgSetting.pkg.mSetEnabled = newState;
13961            } else {
13962                // We're dealing with a component level state change
13963                // First, verify that this is a valid class name.
13964                PackageParser.Package pkg = pkgSetting.pkg;
13965                if (pkg == null || !pkg.hasComponentClassName(className)) {
13966                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13967                        throw new IllegalArgumentException("Component class " + className
13968                                + " does not exist in " + packageName);
13969                    } else {
13970                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13971                                + className + " does not exist in " + packageName);
13972                    }
13973                }
13974                switch (newState) {
13975                case COMPONENT_ENABLED_STATE_ENABLED:
13976                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13977                        return;
13978                    }
13979                    break;
13980                case COMPONENT_ENABLED_STATE_DISABLED:
13981                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13982                        return;
13983                    }
13984                    break;
13985                case COMPONENT_ENABLED_STATE_DEFAULT:
13986                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13987                        return;
13988                    }
13989                    break;
13990                default:
13991                    Slog.e(TAG, "Invalid new component state: " + newState);
13992                    return;
13993                }
13994            }
13995            scheduleWritePackageRestrictionsLocked(userId);
13996            components = mPendingBroadcasts.get(userId, packageName);
13997            final boolean newPackage = components == null;
13998            if (newPackage) {
13999                components = new ArrayList<String>();
14000            }
14001            if (!components.contains(componentName)) {
14002                components.add(componentName);
14003            }
14004            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14005                sendNow = true;
14006                // Purge entry from pending broadcast list if another one exists already
14007                // since we are sending one right away.
14008                mPendingBroadcasts.remove(userId, packageName);
14009            } else {
14010                if (newPackage) {
14011                    mPendingBroadcasts.put(userId, packageName, components);
14012                }
14013                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14014                    // Schedule a message
14015                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14016                }
14017            }
14018        }
14019
14020        long callingId = Binder.clearCallingIdentity();
14021        try {
14022            if (sendNow) {
14023                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14024                sendPackageChangedBroadcast(packageName,
14025                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14026            }
14027        } finally {
14028            Binder.restoreCallingIdentity(callingId);
14029        }
14030    }
14031
14032    private void sendPackageChangedBroadcast(String packageName,
14033            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14034        if (DEBUG_INSTALL)
14035            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14036                    + componentNames);
14037        Bundle extras = new Bundle(4);
14038        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14039        String nameList[] = new String[componentNames.size()];
14040        componentNames.toArray(nameList);
14041        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14042        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14043        extras.putInt(Intent.EXTRA_UID, packageUid);
14044        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14045                new int[] {UserHandle.getUserId(packageUid)});
14046    }
14047
14048    @Override
14049    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14050        if (!sUserManager.exists(userId)) return;
14051        final int uid = Binder.getCallingUid();
14052        final int permission = mContext.checkCallingOrSelfPermission(
14053                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14054        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14055        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14056        // writer
14057        synchronized (mPackages) {
14058            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14059                    allowedByPermission, uid, userId)) {
14060                scheduleWritePackageRestrictionsLocked(userId);
14061            }
14062        }
14063    }
14064
14065    @Override
14066    public String getInstallerPackageName(String packageName) {
14067        // reader
14068        synchronized (mPackages) {
14069            return mSettings.getInstallerPackageNameLPr(packageName);
14070        }
14071    }
14072
14073    @Override
14074    public int getApplicationEnabledSetting(String packageName, int userId) {
14075        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14076        int uid = Binder.getCallingUid();
14077        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14078        // reader
14079        synchronized (mPackages) {
14080            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14081        }
14082    }
14083
14084    @Override
14085    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14086        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14087        int uid = Binder.getCallingUid();
14088        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14089        // reader
14090        synchronized (mPackages) {
14091            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14092        }
14093    }
14094
14095    @Override
14096    public void enterSafeMode() {
14097        enforceSystemOrRoot("Only the system can request entering safe mode");
14098
14099        if (!mSystemReady) {
14100            mSafeMode = true;
14101        }
14102    }
14103
14104    @Override
14105    public void systemReady() {
14106        mSystemReady = true;
14107
14108        // Read the compatibilty setting when the system is ready.
14109        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14110                mContext.getContentResolver(),
14111                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14112        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14113        if (DEBUG_SETTINGS) {
14114            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14115        }
14116
14117        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14118
14119        synchronized (mPackages) {
14120            // Verify that all of the preferred activity components actually
14121            // exist.  It is possible for applications to be updated and at
14122            // that point remove a previously declared activity component that
14123            // had been set as a preferred activity.  We try to clean this up
14124            // the next time we encounter that preferred activity, but it is
14125            // possible for the user flow to never be able to return to that
14126            // situation so here we do a sanity check to make sure we haven't
14127            // left any junk around.
14128            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14129            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14130                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14131                removed.clear();
14132                for (PreferredActivity pa : pir.filterSet()) {
14133                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14134                        removed.add(pa);
14135                    }
14136                }
14137                if (removed.size() > 0) {
14138                    for (int r=0; r<removed.size(); r++) {
14139                        PreferredActivity pa = removed.get(r);
14140                        Slog.w(TAG, "Removing dangling preferred activity: "
14141                                + pa.mPref.mComponent);
14142                        pir.removeFilter(pa);
14143                    }
14144                    mSettings.writePackageRestrictionsLPr(
14145                            mSettings.mPreferredActivities.keyAt(i));
14146                }
14147            }
14148
14149            for (int userId : UserManagerService.getInstance().getUserIds()) {
14150                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14151                    grantPermissionsUserIds = ArrayUtils.appendInt(
14152                            grantPermissionsUserIds, userId);
14153                }
14154            }
14155        }
14156        sUserManager.systemReady();
14157
14158        // If we upgraded grant all default permissions before kicking off.
14159        for (int userId : grantPermissionsUserIds) {
14160            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14161        }
14162
14163        // Kick off any messages waiting for system ready
14164        if (mPostSystemReadyMessages != null) {
14165            for (Message msg : mPostSystemReadyMessages) {
14166                msg.sendToTarget();
14167            }
14168            mPostSystemReadyMessages = null;
14169        }
14170
14171        // Watch for external volumes that come and go over time
14172        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14173        storage.registerListener(mStorageListener);
14174
14175        mInstallerService.systemReady();
14176        mPackageDexOptimizer.systemReady();
14177    }
14178
14179    @Override
14180    public boolean isSafeMode() {
14181        return mSafeMode;
14182    }
14183
14184    @Override
14185    public boolean hasSystemUidErrors() {
14186        return mHasSystemUidErrors;
14187    }
14188
14189    static String arrayToString(int[] array) {
14190        StringBuffer buf = new StringBuffer(128);
14191        buf.append('[');
14192        if (array != null) {
14193            for (int i=0; i<array.length; i++) {
14194                if (i > 0) buf.append(", ");
14195                buf.append(array[i]);
14196            }
14197        }
14198        buf.append(']');
14199        return buf.toString();
14200    }
14201
14202    static class DumpState {
14203        public static final int DUMP_LIBS = 1 << 0;
14204        public static final int DUMP_FEATURES = 1 << 1;
14205        public static final int DUMP_RESOLVERS = 1 << 2;
14206        public static final int DUMP_PERMISSIONS = 1 << 3;
14207        public static final int DUMP_PACKAGES = 1 << 4;
14208        public static final int DUMP_SHARED_USERS = 1 << 5;
14209        public static final int DUMP_MESSAGES = 1 << 6;
14210        public static final int DUMP_PROVIDERS = 1 << 7;
14211        public static final int DUMP_VERIFIERS = 1 << 8;
14212        public static final int DUMP_PREFERRED = 1 << 9;
14213        public static final int DUMP_PREFERRED_XML = 1 << 10;
14214        public static final int DUMP_KEYSETS = 1 << 11;
14215        public static final int DUMP_VERSION = 1 << 12;
14216        public static final int DUMP_INSTALLS = 1 << 13;
14217        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14218        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14219
14220        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14221
14222        private int mTypes;
14223
14224        private int mOptions;
14225
14226        private boolean mTitlePrinted;
14227
14228        private SharedUserSetting mSharedUser;
14229
14230        public boolean isDumping(int type) {
14231            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14232                return true;
14233            }
14234
14235            return (mTypes & type) != 0;
14236        }
14237
14238        public void setDump(int type) {
14239            mTypes |= type;
14240        }
14241
14242        public boolean isOptionEnabled(int option) {
14243            return (mOptions & option) != 0;
14244        }
14245
14246        public void setOptionEnabled(int option) {
14247            mOptions |= option;
14248        }
14249
14250        public boolean onTitlePrinted() {
14251            final boolean printed = mTitlePrinted;
14252            mTitlePrinted = true;
14253            return printed;
14254        }
14255
14256        public boolean getTitlePrinted() {
14257            return mTitlePrinted;
14258        }
14259
14260        public void setTitlePrinted(boolean enabled) {
14261            mTitlePrinted = enabled;
14262        }
14263
14264        public SharedUserSetting getSharedUser() {
14265            return mSharedUser;
14266        }
14267
14268        public void setSharedUser(SharedUserSetting user) {
14269            mSharedUser = user;
14270        }
14271    }
14272
14273    @Override
14274    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14275        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14276                != PackageManager.PERMISSION_GRANTED) {
14277            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14278                    + Binder.getCallingPid()
14279                    + ", uid=" + Binder.getCallingUid()
14280                    + " without permission "
14281                    + android.Manifest.permission.DUMP);
14282            return;
14283        }
14284
14285        DumpState dumpState = new DumpState();
14286        boolean fullPreferred = false;
14287        boolean checkin = false;
14288
14289        String packageName = null;
14290        ArraySet<String> permissionNames = null;
14291
14292        int opti = 0;
14293        while (opti < args.length) {
14294            String opt = args[opti];
14295            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14296                break;
14297            }
14298            opti++;
14299
14300            if ("-a".equals(opt)) {
14301                // Right now we only know how to print all.
14302            } else if ("-h".equals(opt)) {
14303                pw.println("Package manager dump options:");
14304                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14305                pw.println("    --checkin: dump for a checkin");
14306                pw.println("    -f: print details of intent filters");
14307                pw.println("    -h: print this help");
14308                pw.println("  cmd may be one of:");
14309                pw.println("    l[ibraries]: list known shared libraries");
14310                pw.println("    f[ibraries]: list device features");
14311                pw.println("    k[eysets]: print known keysets");
14312                pw.println("    r[esolvers]: dump intent resolvers");
14313                pw.println("    perm[issions]: dump permissions");
14314                pw.println("    permission [name ...]: dump declaration and use of given permission");
14315                pw.println("    pref[erred]: print preferred package settings");
14316                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14317                pw.println("    prov[iders]: dump content providers");
14318                pw.println("    p[ackages]: dump installed packages");
14319                pw.println("    s[hared-users]: dump shared user IDs");
14320                pw.println("    m[essages]: print collected runtime messages");
14321                pw.println("    v[erifiers]: print package verifier info");
14322                pw.println("    version: print database version info");
14323                pw.println("    write: write current settings now");
14324                pw.println("    <package.name>: info about given package");
14325                pw.println("    installs: details about install sessions");
14326                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14327                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14328                return;
14329            } else if ("--checkin".equals(opt)) {
14330                checkin = true;
14331            } else if ("-f".equals(opt)) {
14332                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14333            } else {
14334                pw.println("Unknown argument: " + opt + "; use -h for help");
14335            }
14336        }
14337
14338        // Is the caller requesting to dump a particular piece of data?
14339        if (opti < args.length) {
14340            String cmd = args[opti];
14341            opti++;
14342            // Is this a package name?
14343            if ("android".equals(cmd) || cmd.contains(".")) {
14344                packageName = cmd;
14345                // When dumping a single package, we always dump all of its
14346                // filter information since the amount of data will be reasonable.
14347                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14348            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14349                dumpState.setDump(DumpState.DUMP_LIBS);
14350            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14351                dumpState.setDump(DumpState.DUMP_FEATURES);
14352            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14353                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14354            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14355                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14356            } else if ("permission".equals(cmd)) {
14357                if (opti >= args.length) {
14358                    pw.println("Error: permission requires permission name");
14359                    return;
14360                }
14361                permissionNames = new ArraySet<>();
14362                while (opti < args.length) {
14363                    permissionNames.add(args[opti]);
14364                    opti++;
14365                }
14366                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14367                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14368            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14369                dumpState.setDump(DumpState.DUMP_PREFERRED);
14370            } else if ("preferred-xml".equals(cmd)) {
14371                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14372                if (opti < args.length && "--full".equals(args[opti])) {
14373                    fullPreferred = true;
14374                    opti++;
14375                }
14376            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14377                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14378            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14379                dumpState.setDump(DumpState.DUMP_PACKAGES);
14380            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14381                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14382            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14383                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14384            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14385                dumpState.setDump(DumpState.DUMP_MESSAGES);
14386            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14387                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14388            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14389                    || "intent-filter-verifiers".equals(cmd)) {
14390                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14391            } else if ("version".equals(cmd)) {
14392                dumpState.setDump(DumpState.DUMP_VERSION);
14393            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14394                dumpState.setDump(DumpState.DUMP_KEYSETS);
14395            } else if ("installs".equals(cmd)) {
14396                dumpState.setDump(DumpState.DUMP_INSTALLS);
14397            } else if ("write".equals(cmd)) {
14398                synchronized (mPackages) {
14399                    mSettings.writeLPr();
14400                    pw.println("Settings written.");
14401                    return;
14402                }
14403            }
14404        }
14405
14406        if (checkin) {
14407            pw.println("vers,1");
14408        }
14409
14410        // reader
14411        synchronized (mPackages) {
14412            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14413                if (!checkin) {
14414                    if (dumpState.onTitlePrinted())
14415                        pw.println();
14416                    pw.println("Database versions:");
14417                    pw.print("  SDK Version:");
14418                    pw.print(" internal=");
14419                    pw.print(mSettings.mInternalSdkPlatform);
14420                    pw.print(" external=");
14421                    pw.println(mSettings.mExternalSdkPlatform);
14422                    pw.print("  DB Version:");
14423                    pw.print(" internal=");
14424                    pw.print(mSettings.mInternalDatabaseVersion);
14425                    pw.print(" external=");
14426                    pw.println(mSettings.mExternalDatabaseVersion);
14427                }
14428            }
14429
14430            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14431                if (!checkin) {
14432                    if (dumpState.onTitlePrinted())
14433                        pw.println();
14434                    pw.println("Verifiers:");
14435                    pw.print("  Required: ");
14436                    pw.print(mRequiredVerifierPackage);
14437                    pw.print(" (uid=");
14438                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14439                    pw.println(")");
14440                } else if (mRequiredVerifierPackage != null) {
14441                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14442                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14443                }
14444            }
14445
14446            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14447                    packageName == null) {
14448                if (mIntentFilterVerifierComponent != null) {
14449                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14450                    if (!checkin) {
14451                        if (dumpState.onTitlePrinted())
14452                            pw.println();
14453                        pw.println("Intent Filter Verifier:");
14454                        pw.print("  Using: ");
14455                        pw.print(verifierPackageName);
14456                        pw.print(" (uid=");
14457                        pw.print(getPackageUid(verifierPackageName, 0));
14458                        pw.println(")");
14459                    } else if (verifierPackageName != null) {
14460                        pw.print("ifv,"); pw.print(verifierPackageName);
14461                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14462                    }
14463                } else {
14464                    pw.println();
14465                    pw.println("No Intent Filter Verifier available!");
14466                }
14467            }
14468
14469            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14470                boolean printedHeader = false;
14471                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14472                while (it.hasNext()) {
14473                    String name = it.next();
14474                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14475                    if (!checkin) {
14476                        if (!printedHeader) {
14477                            if (dumpState.onTitlePrinted())
14478                                pw.println();
14479                            pw.println("Libraries:");
14480                            printedHeader = true;
14481                        }
14482                        pw.print("  ");
14483                    } else {
14484                        pw.print("lib,");
14485                    }
14486                    pw.print(name);
14487                    if (!checkin) {
14488                        pw.print(" -> ");
14489                    }
14490                    if (ent.path != null) {
14491                        if (!checkin) {
14492                            pw.print("(jar) ");
14493                            pw.print(ent.path);
14494                        } else {
14495                            pw.print(",jar,");
14496                            pw.print(ent.path);
14497                        }
14498                    } else {
14499                        if (!checkin) {
14500                            pw.print("(apk) ");
14501                            pw.print(ent.apk);
14502                        } else {
14503                            pw.print(",apk,");
14504                            pw.print(ent.apk);
14505                        }
14506                    }
14507                    pw.println();
14508                }
14509            }
14510
14511            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14512                if (dumpState.onTitlePrinted())
14513                    pw.println();
14514                if (!checkin) {
14515                    pw.println("Features:");
14516                }
14517                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14518                while (it.hasNext()) {
14519                    String name = it.next();
14520                    if (!checkin) {
14521                        pw.print("  ");
14522                    } else {
14523                        pw.print("feat,");
14524                    }
14525                    pw.println(name);
14526                }
14527            }
14528
14529            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14530                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14531                        : "Activity Resolver Table:", "  ", packageName,
14532                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14533                    dumpState.setTitlePrinted(true);
14534                }
14535                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14536                        : "Receiver Resolver Table:", "  ", packageName,
14537                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14538                    dumpState.setTitlePrinted(true);
14539                }
14540                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14541                        : "Service Resolver Table:", "  ", packageName,
14542                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14543                    dumpState.setTitlePrinted(true);
14544                }
14545                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14546                        : "Provider Resolver Table:", "  ", packageName,
14547                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14548                    dumpState.setTitlePrinted(true);
14549                }
14550            }
14551
14552            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14553                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14554                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14555                    int user = mSettings.mPreferredActivities.keyAt(i);
14556                    if (pir.dump(pw,
14557                            dumpState.getTitlePrinted()
14558                                ? "\nPreferred Activities User " + user + ":"
14559                                : "Preferred Activities User " + user + ":", "  ",
14560                            packageName, true, false)) {
14561                        dumpState.setTitlePrinted(true);
14562                    }
14563                }
14564            }
14565
14566            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14567                pw.flush();
14568                FileOutputStream fout = new FileOutputStream(fd);
14569                BufferedOutputStream str = new BufferedOutputStream(fout);
14570                XmlSerializer serializer = new FastXmlSerializer();
14571                try {
14572                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14573                    serializer.startDocument(null, true);
14574                    serializer.setFeature(
14575                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14576                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14577                    serializer.endDocument();
14578                    serializer.flush();
14579                } catch (IllegalArgumentException e) {
14580                    pw.println("Failed writing: " + e);
14581                } catch (IllegalStateException e) {
14582                    pw.println("Failed writing: " + e);
14583                } catch (IOException e) {
14584                    pw.println("Failed writing: " + e);
14585                }
14586            }
14587
14588            if (!checkin
14589                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14590                    && packageName == null) {
14591                pw.println();
14592                int count = mSettings.mPackages.size();
14593                if (count == 0) {
14594                    pw.println("No domain preferred apps!");
14595                    pw.println();
14596                } else {
14597                    final String prefix = "  ";
14598                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14599                    if (allPackageSettings.size() == 0) {
14600                        pw.println("No domain preferred apps!");
14601                        pw.println();
14602                    } else {
14603                        pw.println("Domain preferred apps status:");
14604                        pw.println();
14605                        count = 0;
14606                        for (PackageSetting ps : allPackageSettings) {
14607                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14608                            if (ivi == null || ivi.getPackageName() == null) continue;
14609                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14610                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14611                            pw.println(prefix + "Status: " + ivi.getStatusString());
14612                            pw.println();
14613                            count++;
14614                        }
14615                        if (count == 0) {
14616                            pw.println(prefix + "No domain preferred app status!");
14617                            pw.println();
14618                        }
14619                        for (int userId : sUserManager.getUserIds()) {
14620                            pw.println("Domain preferred apps for User " + userId + ":");
14621                            pw.println();
14622                            count = 0;
14623                            for (PackageSetting ps : allPackageSettings) {
14624                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14625                                if (ivi == null || ivi.getPackageName() == null) {
14626                                    continue;
14627                                }
14628                                final int status = ps.getDomainVerificationStatusForUser(userId);
14629                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14630                                    continue;
14631                                }
14632                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14633                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14634                                String statusStr = IntentFilterVerificationInfo.
14635                                        getStatusStringFromValue(status);
14636                                pw.println(prefix + "Status: " + statusStr);
14637                                pw.println();
14638                                count++;
14639                            }
14640                            if (count == 0) {
14641                                pw.println(prefix + "No domain preferred apps!");
14642                                pw.println();
14643                            }
14644                        }
14645                    }
14646                }
14647            }
14648
14649            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14650                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14651                if (packageName == null && permissionNames == null) {
14652                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14653                        if (iperm == 0) {
14654                            if (dumpState.onTitlePrinted())
14655                                pw.println();
14656                            pw.println("AppOp Permissions:");
14657                        }
14658                        pw.print("  AppOp Permission ");
14659                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14660                        pw.println(":");
14661                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14662                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14663                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14664                        }
14665                    }
14666                }
14667            }
14668
14669            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14670                boolean printedSomething = false;
14671                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14672                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14673                        continue;
14674                    }
14675                    if (!printedSomething) {
14676                        if (dumpState.onTitlePrinted())
14677                            pw.println();
14678                        pw.println("Registered ContentProviders:");
14679                        printedSomething = true;
14680                    }
14681                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14682                    pw.print("    "); pw.println(p.toString());
14683                }
14684                printedSomething = false;
14685                for (Map.Entry<String, PackageParser.Provider> entry :
14686                        mProvidersByAuthority.entrySet()) {
14687                    PackageParser.Provider p = entry.getValue();
14688                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14689                        continue;
14690                    }
14691                    if (!printedSomething) {
14692                        if (dumpState.onTitlePrinted())
14693                            pw.println();
14694                        pw.println("ContentProvider Authorities:");
14695                        printedSomething = true;
14696                    }
14697                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14698                    pw.print("    "); pw.println(p.toString());
14699                    if (p.info != null && p.info.applicationInfo != null) {
14700                        final String appInfo = p.info.applicationInfo.toString();
14701                        pw.print("      applicationInfo="); pw.println(appInfo);
14702                    }
14703                }
14704            }
14705
14706            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14707                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14708            }
14709
14710            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14711                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14712            }
14713
14714            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14715                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14716            }
14717
14718            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14719                // XXX should handle packageName != null by dumping only install data that
14720                // the given package is involved with.
14721                if (dumpState.onTitlePrinted()) pw.println();
14722                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14723            }
14724
14725            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14726                if (dumpState.onTitlePrinted()) pw.println();
14727                mSettings.dumpReadMessagesLPr(pw, dumpState);
14728
14729                pw.println();
14730                pw.println("Package warning messages:");
14731                BufferedReader in = null;
14732                String line = null;
14733                try {
14734                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14735                    while ((line = in.readLine()) != null) {
14736                        if (line.contains("ignored: updated version")) continue;
14737                        pw.println(line);
14738                    }
14739                } catch (IOException ignored) {
14740                } finally {
14741                    IoUtils.closeQuietly(in);
14742                }
14743            }
14744
14745            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14746                BufferedReader in = null;
14747                String line = null;
14748                try {
14749                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14750                    while ((line = in.readLine()) != null) {
14751                        if (line.contains("ignored: updated version")) continue;
14752                        pw.print("msg,");
14753                        pw.println(line);
14754                    }
14755                } catch (IOException ignored) {
14756                } finally {
14757                    IoUtils.closeQuietly(in);
14758                }
14759            }
14760        }
14761    }
14762
14763    // ------- apps on sdcard specific code -------
14764    static final boolean DEBUG_SD_INSTALL = false;
14765
14766    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14767
14768    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14769
14770    private boolean mMediaMounted = false;
14771
14772    static String getEncryptKey() {
14773        try {
14774            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14775                    SD_ENCRYPTION_KEYSTORE_NAME);
14776            if (sdEncKey == null) {
14777                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14778                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14779                if (sdEncKey == null) {
14780                    Slog.e(TAG, "Failed to create encryption keys");
14781                    return null;
14782                }
14783            }
14784            return sdEncKey;
14785        } catch (NoSuchAlgorithmException nsae) {
14786            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14787            return null;
14788        } catch (IOException ioe) {
14789            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14790            return null;
14791        }
14792    }
14793
14794    /*
14795     * Update media status on PackageManager.
14796     */
14797    @Override
14798    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14799        int callingUid = Binder.getCallingUid();
14800        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14801            throw new SecurityException("Media status can only be updated by the system");
14802        }
14803        // reader; this apparently protects mMediaMounted, but should probably
14804        // be a different lock in that case.
14805        synchronized (mPackages) {
14806            Log.i(TAG, "Updating external media status from "
14807                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14808                    + (mediaStatus ? "mounted" : "unmounted"));
14809            if (DEBUG_SD_INSTALL)
14810                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14811                        + ", mMediaMounted=" + mMediaMounted);
14812            if (mediaStatus == mMediaMounted) {
14813                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14814                        : 0, -1);
14815                mHandler.sendMessage(msg);
14816                return;
14817            }
14818            mMediaMounted = mediaStatus;
14819        }
14820        // Queue up an async operation since the package installation may take a
14821        // little while.
14822        mHandler.post(new Runnable() {
14823            public void run() {
14824                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14825            }
14826        });
14827    }
14828
14829    /**
14830     * Called by MountService when the initial ASECs to scan are available.
14831     * Should block until all the ASEC containers are finished being scanned.
14832     */
14833    public void scanAvailableAsecs() {
14834        updateExternalMediaStatusInner(true, false, false);
14835        if (mShouldRestoreconData) {
14836            SELinuxMMAC.setRestoreconDone();
14837            mShouldRestoreconData = false;
14838        }
14839    }
14840
14841    /*
14842     * Collect information of applications on external media, map them against
14843     * existing containers and update information based on current mount status.
14844     * Please note that we always have to report status if reportStatus has been
14845     * set to true especially when unloading packages.
14846     */
14847    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14848            boolean externalStorage) {
14849        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14850        int[] uidArr = EmptyArray.INT;
14851
14852        final String[] list = PackageHelper.getSecureContainerList();
14853        if (ArrayUtils.isEmpty(list)) {
14854            Log.i(TAG, "No secure containers found");
14855        } else {
14856            // Process list of secure containers and categorize them
14857            // as active or stale based on their package internal state.
14858
14859            // reader
14860            synchronized (mPackages) {
14861                for (String cid : list) {
14862                    // Leave stages untouched for now; installer service owns them
14863                    if (PackageInstallerService.isStageName(cid)) continue;
14864
14865                    if (DEBUG_SD_INSTALL)
14866                        Log.i(TAG, "Processing container " + cid);
14867                    String pkgName = getAsecPackageName(cid);
14868                    if (pkgName == null) {
14869                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14870                        continue;
14871                    }
14872                    if (DEBUG_SD_INSTALL)
14873                        Log.i(TAG, "Looking for pkg : " + pkgName);
14874
14875                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14876                    if (ps == null) {
14877                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14878                        continue;
14879                    }
14880
14881                    /*
14882                     * Skip packages that are not external if we're unmounting
14883                     * external storage.
14884                     */
14885                    if (externalStorage && !isMounted && !isExternal(ps)) {
14886                        continue;
14887                    }
14888
14889                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14890                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14891                    // The package status is changed only if the code path
14892                    // matches between settings and the container id.
14893                    if (ps.codePathString != null
14894                            && ps.codePathString.startsWith(args.getCodePath())) {
14895                        if (DEBUG_SD_INSTALL) {
14896                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14897                                    + " at code path: " + ps.codePathString);
14898                        }
14899
14900                        // We do have a valid package installed on sdcard
14901                        processCids.put(args, ps.codePathString);
14902                        final int uid = ps.appId;
14903                        if (uid != -1) {
14904                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14905                        }
14906                    } else {
14907                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14908                                + ps.codePathString);
14909                    }
14910                }
14911            }
14912
14913            Arrays.sort(uidArr);
14914        }
14915
14916        // Process packages with valid entries.
14917        if (isMounted) {
14918            if (DEBUG_SD_INSTALL)
14919                Log.i(TAG, "Loading packages");
14920            loadMediaPackages(processCids, uidArr);
14921            startCleaningPackages();
14922            mInstallerService.onSecureContainersAvailable();
14923        } else {
14924            if (DEBUG_SD_INSTALL)
14925                Log.i(TAG, "Unloading packages");
14926            unloadMediaPackages(processCids, uidArr, reportStatus);
14927        }
14928    }
14929
14930    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14931            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14932        final int size = infos.size();
14933        final String[] packageNames = new String[size];
14934        final int[] packageUids = new int[size];
14935        for (int i = 0; i < size; i++) {
14936            final ApplicationInfo info = infos.get(i);
14937            packageNames[i] = info.packageName;
14938            packageUids[i] = info.uid;
14939        }
14940        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14941                finishedReceiver);
14942    }
14943
14944    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14945            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14946        sendResourcesChangedBroadcast(mediaStatus, replacing,
14947                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14948    }
14949
14950    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14951            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14952        int size = pkgList.length;
14953        if (size > 0) {
14954            // Send broadcasts here
14955            Bundle extras = new Bundle();
14956            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14957            if (uidArr != null) {
14958                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14959            }
14960            if (replacing) {
14961                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14962            }
14963            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14964                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14965            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14966        }
14967    }
14968
14969   /*
14970     * Look at potentially valid container ids from processCids If package
14971     * information doesn't match the one on record or package scanning fails,
14972     * the cid is added to list of removeCids. We currently don't delete stale
14973     * containers.
14974     */
14975    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14976        ArrayList<String> pkgList = new ArrayList<String>();
14977        Set<AsecInstallArgs> keys = processCids.keySet();
14978
14979        for (AsecInstallArgs args : keys) {
14980            String codePath = processCids.get(args);
14981            if (DEBUG_SD_INSTALL)
14982                Log.i(TAG, "Loading container : " + args.cid);
14983            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14984            try {
14985                // Make sure there are no container errors first.
14986                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14987                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14988                            + " when installing from sdcard");
14989                    continue;
14990                }
14991                // Check code path here.
14992                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14993                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14994                            + " does not match one in settings " + codePath);
14995                    continue;
14996                }
14997                // Parse package
14998                int parseFlags = mDefParseFlags;
14999                if (args.isExternalAsec()) {
15000                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15001                }
15002                if (args.isFwdLocked()) {
15003                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15004                }
15005
15006                synchronized (mInstallLock) {
15007                    PackageParser.Package pkg = null;
15008                    try {
15009                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15010                    } catch (PackageManagerException e) {
15011                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15012                    }
15013                    // Scan the package
15014                    if (pkg != null) {
15015                        /*
15016                         * TODO why is the lock being held? doPostInstall is
15017                         * called in other places without the lock. This needs
15018                         * to be straightened out.
15019                         */
15020                        // writer
15021                        synchronized (mPackages) {
15022                            retCode = PackageManager.INSTALL_SUCCEEDED;
15023                            pkgList.add(pkg.packageName);
15024                            // Post process args
15025                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15026                                    pkg.applicationInfo.uid);
15027                        }
15028                    } else {
15029                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15030                    }
15031                }
15032
15033            } finally {
15034                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15035                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15036                }
15037            }
15038        }
15039        // writer
15040        synchronized (mPackages) {
15041            // If the platform SDK has changed since the last time we booted,
15042            // we need to re-grant app permission to catch any new ones that
15043            // appear. This is really a hack, and means that apps can in some
15044            // cases get permissions that the user didn't initially explicitly
15045            // allow... it would be nice to have some better way to handle
15046            // this situation.
15047            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15048            if (regrantPermissions)
15049                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15050                        + mSdkVersion + "; regranting permissions for external storage");
15051            mSettings.mExternalSdkPlatform = mSdkVersion;
15052
15053            // Make sure group IDs have been assigned, and any permission
15054            // changes in other apps are accounted for
15055            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15056                    | (regrantPermissions
15057                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15058                            : 0));
15059
15060            mSettings.updateExternalDatabaseVersion();
15061
15062            // can downgrade to reader
15063            // Persist settings
15064            mSettings.writeLPr();
15065        }
15066        // Send a broadcast to let everyone know we are done processing
15067        if (pkgList.size() > 0) {
15068            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15069        }
15070    }
15071
15072   /*
15073     * Utility method to unload a list of specified containers
15074     */
15075    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15076        // Just unmount all valid containers.
15077        for (AsecInstallArgs arg : cidArgs) {
15078            synchronized (mInstallLock) {
15079                arg.doPostDeleteLI(false);
15080           }
15081       }
15082   }
15083
15084    /*
15085     * Unload packages mounted on external media. This involves deleting package
15086     * data from internal structures, sending broadcasts about diabled packages,
15087     * gc'ing to free up references, unmounting all secure containers
15088     * corresponding to packages on external media, and posting a
15089     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15090     * that we always have to post this message if status has been requested no
15091     * matter what.
15092     */
15093    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15094            final boolean reportStatus) {
15095        if (DEBUG_SD_INSTALL)
15096            Log.i(TAG, "unloading media packages");
15097        ArrayList<String> pkgList = new ArrayList<String>();
15098        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15099        final Set<AsecInstallArgs> keys = processCids.keySet();
15100        for (AsecInstallArgs args : keys) {
15101            String pkgName = args.getPackageName();
15102            if (DEBUG_SD_INSTALL)
15103                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15104            // Delete package internally
15105            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15106            synchronized (mInstallLock) {
15107                boolean res = deletePackageLI(pkgName, null, false, null, null,
15108                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15109                if (res) {
15110                    pkgList.add(pkgName);
15111                } else {
15112                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15113                    failedList.add(args);
15114                }
15115            }
15116        }
15117
15118        // reader
15119        synchronized (mPackages) {
15120            // We didn't update the settings after removing each package;
15121            // write them now for all packages.
15122            mSettings.writeLPr();
15123        }
15124
15125        // We have to absolutely send UPDATED_MEDIA_STATUS only
15126        // after confirming that all the receivers processed the ordered
15127        // broadcast when packages get disabled, force a gc to clean things up.
15128        // and unload all the containers.
15129        if (pkgList.size() > 0) {
15130            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15131                    new IIntentReceiver.Stub() {
15132                public void performReceive(Intent intent, int resultCode, String data,
15133                        Bundle extras, boolean ordered, boolean sticky,
15134                        int sendingUser) throws RemoteException {
15135                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15136                            reportStatus ? 1 : 0, 1, keys);
15137                    mHandler.sendMessage(msg);
15138                }
15139            });
15140        } else {
15141            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15142                    keys);
15143            mHandler.sendMessage(msg);
15144        }
15145    }
15146
15147    private void loadPrivatePackages(VolumeInfo vol) {
15148        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15149        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15150        synchronized (mInstallLock) {
15151        synchronized (mPackages) {
15152            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15153            for (PackageSetting ps : packages) {
15154                final PackageParser.Package pkg;
15155                try {
15156                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15157                    loaded.add(pkg.applicationInfo);
15158                } catch (PackageManagerException e) {
15159                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15160                }
15161            }
15162
15163            // TODO: regrant any permissions that changed based since original install
15164
15165            mSettings.writeLPr();
15166        }
15167        }
15168
15169        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15170        sendResourcesChangedBroadcast(true, false, loaded, null);
15171    }
15172
15173    private void unloadPrivatePackages(VolumeInfo vol) {
15174        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15175        synchronized (mInstallLock) {
15176        synchronized (mPackages) {
15177            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15178            for (PackageSetting ps : packages) {
15179                if (ps.pkg == null) continue;
15180
15181                final ApplicationInfo info = ps.pkg.applicationInfo;
15182                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15183                if (deletePackageLI(ps.name, null, false, null, null,
15184                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15185                    unloaded.add(info);
15186                } else {
15187                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15188                }
15189            }
15190
15191            mSettings.writeLPr();
15192        }
15193        }
15194
15195        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15196        sendResourcesChangedBroadcast(false, false, unloaded, null);
15197    }
15198
15199    private void unfreezePackage(String packageName) {
15200        synchronized (mPackages) {
15201            final PackageSetting ps = mSettings.mPackages.get(packageName);
15202            if (ps != null) {
15203                ps.frozen = false;
15204            }
15205        }
15206    }
15207
15208    @Override
15209    public int movePackage(final String packageName, final String volumeUuid) {
15210        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15211
15212        final int moveId = mNextMoveId.getAndIncrement();
15213        try {
15214            movePackageInternal(packageName, volumeUuid, moveId);
15215        } catch (PackageManagerException e) {
15216            Slog.w(TAG, "Failed to move " + packageName, e);
15217            mMoveCallbacks.notifyStatusChanged(moveId,
15218                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15219        }
15220        return moveId;
15221    }
15222
15223    private void movePackageInternal(final String packageName, final String volumeUuid,
15224            final int moveId) throws PackageManagerException {
15225        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15226        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15227        final PackageManager pm = mContext.getPackageManager();
15228
15229        final boolean currentAsec;
15230        final String currentVolumeUuid;
15231        final File codeFile;
15232        final String installerPackageName;
15233        final String packageAbiOverride;
15234        final int appId;
15235        final String seinfo;
15236        final String label;
15237
15238        // reader
15239        synchronized (mPackages) {
15240            final PackageParser.Package pkg = mPackages.get(packageName);
15241            final PackageSetting ps = mSettings.mPackages.get(packageName);
15242            if (pkg == null || ps == null) {
15243                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15244            }
15245
15246            if (pkg.applicationInfo.isSystemApp()) {
15247                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15248                        "Cannot move system application");
15249            }
15250
15251            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15252                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15253                        "Package already moved to " + volumeUuid);
15254            }
15255
15256            final File probe = new File(pkg.codePath);
15257            final File probeOat = new File(probe, "oat");
15258            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15259                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15260                        "Move only supported for modern cluster style installs");
15261            }
15262
15263            if (ps.frozen) {
15264                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15265                        "Failed to move already frozen package");
15266            }
15267            ps.frozen = true;
15268
15269            currentAsec = pkg.applicationInfo.isForwardLocked()
15270                    || pkg.applicationInfo.isExternalAsec();
15271            currentVolumeUuid = ps.volumeUuid;
15272            codeFile = new File(pkg.codePath);
15273            installerPackageName = ps.installerPackageName;
15274            packageAbiOverride = ps.cpuAbiOverrideString;
15275            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15276            seinfo = pkg.applicationInfo.seinfo;
15277            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15278        }
15279
15280        // Now that we're guarded by frozen state, kill app during move
15281        killApplication(packageName, appId, "move pkg");
15282
15283        final Bundle extras = new Bundle();
15284        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15285        extras.putString(Intent.EXTRA_TITLE, label);
15286        mMoveCallbacks.notifyCreated(moveId, extras);
15287
15288        int installFlags;
15289        final boolean moveCompleteApp;
15290        final File measurePath;
15291
15292        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15293            installFlags = INSTALL_INTERNAL;
15294            moveCompleteApp = !currentAsec;
15295            measurePath = Environment.getDataAppDirectory(volumeUuid);
15296        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15297            installFlags = INSTALL_EXTERNAL;
15298            moveCompleteApp = false;
15299            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15300        } else {
15301            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15302            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15303                    || !volume.isMountedWritable()) {
15304                unfreezePackage(packageName);
15305                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15306                        "Move location not mounted private volume");
15307            }
15308
15309            Preconditions.checkState(!currentAsec);
15310
15311            installFlags = INSTALL_INTERNAL;
15312            moveCompleteApp = true;
15313            measurePath = Environment.getDataAppDirectory(volumeUuid);
15314        }
15315
15316        final PackageStats stats = new PackageStats(null, -1);
15317        synchronized (mInstaller) {
15318            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15319                unfreezePackage(packageName);
15320                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15321                        "Failed to measure package size");
15322            }
15323        }
15324
15325        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15326                + stats.dataSize);
15327
15328        final long startFreeBytes = measurePath.getFreeSpace();
15329        final long sizeBytes;
15330        if (moveCompleteApp) {
15331            sizeBytes = stats.codeSize + stats.dataSize;
15332        } else {
15333            sizeBytes = stats.codeSize;
15334        }
15335
15336        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15337            unfreezePackage(packageName);
15338            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15339                    "Not enough free space to move");
15340        }
15341
15342        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15343
15344        final CountDownLatch installedLatch = new CountDownLatch(1);
15345        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15346            @Override
15347            public void onUserActionRequired(Intent intent) throws RemoteException {
15348                throw new IllegalStateException();
15349            }
15350
15351            @Override
15352            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15353                    Bundle extras) throws RemoteException {
15354                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15355                        + PackageManager.installStatusToString(returnCode, msg));
15356
15357                installedLatch.countDown();
15358
15359                // Regardless of success or failure of the move operation,
15360                // always unfreeze the package
15361                unfreezePackage(packageName);
15362
15363                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15364                switch (status) {
15365                    case PackageInstaller.STATUS_SUCCESS:
15366                        mMoveCallbacks.notifyStatusChanged(moveId,
15367                                PackageManager.MOVE_SUCCEEDED);
15368                        break;
15369                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15370                        mMoveCallbacks.notifyStatusChanged(moveId,
15371                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15372                        break;
15373                    default:
15374                        mMoveCallbacks.notifyStatusChanged(moveId,
15375                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15376                        break;
15377                }
15378            }
15379        };
15380
15381        final MoveInfo move;
15382        if (moveCompleteApp) {
15383            // Kick off a thread to report progress estimates
15384            new Thread() {
15385                @Override
15386                public void run() {
15387                    while (true) {
15388                        try {
15389                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15390                                break;
15391                            }
15392                        } catch (InterruptedException ignored) {
15393                        }
15394
15395                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15396                        final int progress = 10 + (int) MathUtils.constrain(
15397                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15398                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15399                    }
15400                }
15401            }.start();
15402
15403            final String dataAppName = codeFile.getName();
15404            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15405                    dataAppName, appId, seinfo);
15406        } else {
15407            move = null;
15408        }
15409
15410        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15411
15412        final Message msg = mHandler.obtainMessage(INIT_COPY);
15413        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15414        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15415                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15416        mHandler.sendMessage(msg);
15417    }
15418
15419    @Override
15420    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15421        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15422
15423        final int realMoveId = mNextMoveId.getAndIncrement();
15424        final Bundle extras = new Bundle();
15425        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15426        mMoveCallbacks.notifyCreated(realMoveId, extras);
15427
15428        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15429            @Override
15430            public void onCreated(int moveId, Bundle extras) {
15431                // Ignored
15432            }
15433
15434            @Override
15435            public void onStatusChanged(int moveId, int status, long estMillis) {
15436                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15437            }
15438        };
15439
15440        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15441        storage.setPrimaryStorageUuid(volumeUuid, callback);
15442        return realMoveId;
15443    }
15444
15445    @Override
15446    public int getMoveStatus(int moveId) {
15447        mContext.enforceCallingOrSelfPermission(
15448                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15449        return mMoveCallbacks.mLastStatus.get(moveId);
15450    }
15451
15452    @Override
15453    public void registerMoveCallback(IPackageMoveObserver callback) {
15454        mContext.enforceCallingOrSelfPermission(
15455                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15456        mMoveCallbacks.register(callback);
15457    }
15458
15459    @Override
15460    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15461        mContext.enforceCallingOrSelfPermission(
15462                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15463        mMoveCallbacks.unregister(callback);
15464    }
15465
15466    @Override
15467    public boolean setInstallLocation(int loc) {
15468        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15469                null);
15470        if (getInstallLocation() == loc) {
15471            return true;
15472        }
15473        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15474                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15475            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15476                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15477            return true;
15478        }
15479        return false;
15480   }
15481
15482    @Override
15483    public int getInstallLocation() {
15484        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15485                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15486                PackageHelper.APP_INSTALL_AUTO);
15487    }
15488
15489    /** Called by UserManagerService */
15490    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15491        mDirtyUsers.remove(userHandle);
15492        mSettings.removeUserLPw(userHandle);
15493        mPendingBroadcasts.remove(userHandle);
15494        if (mInstaller != null) {
15495            // Technically, we shouldn't be doing this with the package lock
15496            // held.  However, this is very rare, and there is already so much
15497            // other disk I/O going on, that we'll let it slide for now.
15498            final StorageManager storage = StorageManager.from(mContext);
15499            final List<VolumeInfo> vols = storage.getVolumes();
15500            for (VolumeInfo vol : vols) {
15501                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15502                    final String volumeUuid = vol.getFsUuid();
15503                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15504                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15505                }
15506            }
15507        }
15508        mUserNeedsBadging.delete(userHandle);
15509        removeUnusedPackagesLILPw(userManager, userHandle);
15510    }
15511
15512    /**
15513     * We're removing userHandle and would like to remove any downloaded packages
15514     * that are no longer in use by any other user.
15515     * @param userHandle the user being removed
15516     */
15517    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15518        final boolean DEBUG_CLEAN_APKS = false;
15519        int [] users = userManager.getUserIdsLPr();
15520        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15521        while (psit.hasNext()) {
15522            PackageSetting ps = psit.next();
15523            if (ps.pkg == null) {
15524                continue;
15525            }
15526            final String packageName = ps.pkg.packageName;
15527            // Skip over if system app
15528            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15529                continue;
15530            }
15531            if (DEBUG_CLEAN_APKS) {
15532                Slog.i(TAG, "Checking package " + packageName);
15533            }
15534            boolean keep = false;
15535            for (int i = 0; i < users.length; i++) {
15536                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15537                    keep = true;
15538                    if (DEBUG_CLEAN_APKS) {
15539                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15540                                + users[i]);
15541                    }
15542                    break;
15543                }
15544            }
15545            if (!keep) {
15546                if (DEBUG_CLEAN_APKS) {
15547                    Slog.i(TAG, "  Removing package " + packageName);
15548                }
15549                mHandler.post(new Runnable() {
15550                    public void run() {
15551                        deletePackageX(packageName, userHandle, 0);
15552                    } //end run
15553                });
15554            }
15555        }
15556    }
15557
15558    /** Called by UserManagerService */
15559    void createNewUserLILPw(int userHandle, File path) {
15560        if (mInstaller != null) {
15561            mInstaller.createUserConfig(userHandle);
15562            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15563            applyFactoryDefaultBrowserLPw(userHandle);
15564        }
15565    }
15566
15567    void newUserCreatedLILPw(final int userHandle) {
15568        // We cannot grant the default permissions with a lock held as
15569        // we query providers from other components for default handlers
15570        // such as enabled IMEs, etc.
15571        mHandler.post(new Runnable() {
15572            @Override
15573            public void run() {
15574                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15575            }
15576        });
15577    }
15578
15579    @Override
15580    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15581        mContext.enforceCallingOrSelfPermission(
15582                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15583                "Only package verification agents can read the verifier device identity");
15584
15585        synchronized (mPackages) {
15586            return mSettings.getVerifierDeviceIdentityLPw();
15587        }
15588    }
15589
15590    @Override
15591    public void setPermissionEnforced(String permission, boolean enforced) {
15592        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15593        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15594            synchronized (mPackages) {
15595                if (mSettings.mReadExternalStorageEnforced == null
15596                        || mSettings.mReadExternalStorageEnforced != enforced) {
15597                    mSettings.mReadExternalStorageEnforced = enforced;
15598                    mSettings.writeLPr();
15599                }
15600            }
15601            // kill any non-foreground processes so we restart them and
15602            // grant/revoke the GID.
15603            final IActivityManager am = ActivityManagerNative.getDefault();
15604            if (am != null) {
15605                final long token = Binder.clearCallingIdentity();
15606                try {
15607                    am.killProcessesBelowForeground("setPermissionEnforcement");
15608                } catch (RemoteException e) {
15609                } finally {
15610                    Binder.restoreCallingIdentity(token);
15611                }
15612            }
15613        } else {
15614            throw new IllegalArgumentException("No selective enforcement for " + permission);
15615        }
15616    }
15617
15618    @Override
15619    @Deprecated
15620    public boolean isPermissionEnforced(String permission) {
15621        return true;
15622    }
15623
15624    @Override
15625    public boolean isStorageLow() {
15626        final long token = Binder.clearCallingIdentity();
15627        try {
15628            final DeviceStorageMonitorInternal
15629                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15630            if (dsm != null) {
15631                return dsm.isMemoryLow();
15632            } else {
15633                return false;
15634            }
15635        } finally {
15636            Binder.restoreCallingIdentity(token);
15637        }
15638    }
15639
15640    @Override
15641    public IPackageInstaller getPackageInstaller() {
15642        return mInstallerService;
15643    }
15644
15645    private boolean userNeedsBadging(int userId) {
15646        int index = mUserNeedsBadging.indexOfKey(userId);
15647        if (index < 0) {
15648            final UserInfo userInfo;
15649            final long token = Binder.clearCallingIdentity();
15650            try {
15651                userInfo = sUserManager.getUserInfo(userId);
15652            } finally {
15653                Binder.restoreCallingIdentity(token);
15654            }
15655            final boolean b;
15656            if (userInfo != null && userInfo.isManagedProfile()) {
15657                b = true;
15658            } else {
15659                b = false;
15660            }
15661            mUserNeedsBadging.put(userId, b);
15662            return b;
15663        }
15664        return mUserNeedsBadging.valueAt(index);
15665    }
15666
15667    @Override
15668    public KeySet getKeySetByAlias(String packageName, String alias) {
15669        if (packageName == null || alias == null) {
15670            return null;
15671        }
15672        synchronized(mPackages) {
15673            final PackageParser.Package pkg = mPackages.get(packageName);
15674            if (pkg == null) {
15675                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15676                throw new IllegalArgumentException("Unknown package: " + packageName);
15677            }
15678            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15679            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15680        }
15681    }
15682
15683    @Override
15684    public KeySet getSigningKeySet(String packageName) {
15685        if (packageName == null) {
15686            return null;
15687        }
15688        synchronized(mPackages) {
15689            final PackageParser.Package pkg = mPackages.get(packageName);
15690            if (pkg == null) {
15691                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15692                throw new IllegalArgumentException("Unknown package: " + packageName);
15693            }
15694            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15695                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15696                throw new SecurityException("May not access signing KeySet of other apps.");
15697            }
15698            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15699            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15700        }
15701    }
15702
15703    @Override
15704    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15705        if (packageName == null || ks == null) {
15706            return false;
15707        }
15708        synchronized(mPackages) {
15709            final PackageParser.Package pkg = mPackages.get(packageName);
15710            if (pkg == null) {
15711                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15712                throw new IllegalArgumentException("Unknown package: " + packageName);
15713            }
15714            IBinder ksh = ks.getToken();
15715            if (ksh instanceof KeySetHandle) {
15716                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15717                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15718            }
15719            return false;
15720        }
15721    }
15722
15723    @Override
15724    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15725        if (packageName == null || ks == null) {
15726            return false;
15727        }
15728        synchronized(mPackages) {
15729            final PackageParser.Package pkg = mPackages.get(packageName);
15730            if (pkg == null) {
15731                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15732                throw new IllegalArgumentException("Unknown package: " + packageName);
15733            }
15734            IBinder ksh = ks.getToken();
15735            if (ksh instanceof KeySetHandle) {
15736                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15737                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15738            }
15739            return false;
15740        }
15741    }
15742
15743    public void getUsageStatsIfNoPackageUsageInfo() {
15744        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15745            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15746            if (usm == null) {
15747                throw new IllegalStateException("UsageStatsManager must be initialized");
15748            }
15749            long now = System.currentTimeMillis();
15750            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15751            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15752                String packageName = entry.getKey();
15753                PackageParser.Package pkg = mPackages.get(packageName);
15754                if (pkg == null) {
15755                    continue;
15756                }
15757                UsageStats usage = entry.getValue();
15758                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15759                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15760            }
15761        }
15762    }
15763
15764    /**
15765     * Check and throw if the given before/after packages would be considered a
15766     * downgrade.
15767     */
15768    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15769            throws PackageManagerException {
15770        if (after.versionCode < before.mVersionCode) {
15771            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15772                    "Update version code " + after.versionCode + " is older than current "
15773                    + before.mVersionCode);
15774        } else if (after.versionCode == before.mVersionCode) {
15775            if (after.baseRevisionCode < before.baseRevisionCode) {
15776                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15777                        "Update base revision code " + after.baseRevisionCode
15778                        + " is older than current " + before.baseRevisionCode);
15779            }
15780
15781            if (!ArrayUtils.isEmpty(after.splitNames)) {
15782                for (int i = 0; i < after.splitNames.length; i++) {
15783                    final String splitName = after.splitNames[i];
15784                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15785                    if (j != -1) {
15786                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15787                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15788                                    "Update split " + splitName + " revision code "
15789                                    + after.splitRevisionCodes[i] + " is older than current "
15790                                    + before.splitRevisionCodes[j]);
15791                        }
15792                    }
15793                }
15794            }
15795        }
15796    }
15797
15798    private static class MoveCallbacks extends Handler {
15799        private static final int MSG_CREATED = 1;
15800        private static final int MSG_STATUS_CHANGED = 2;
15801
15802        private final RemoteCallbackList<IPackageMoveObserver>
15803                mCallbacks = new RemoteCallbackList<>();
15804
15805        private final SparseIntArray mLastStatus = new SparseIntArray();
15806
15807        public MoveCallbacks(Looper looper) {
15808            super(looper);
15809        }
15810
15811        public void register(IPackageMoveObserver callback) {
15812            mCallbacks.register(callback);
15813        }
15814
15815        public void unregister(IPackageMoveObserver callback) {
15816            mCallbacks.unregister(callback);
15817        }
15818
15819        @Override
15820        public void handleMessage(Message msg) {
15821            final SomeArgs args = (SomeArgs) msg.obj;
15822            final int n = mCallbacks.beginBroadcast();
15823            for (int i = 0; i < n; i++) {
15824                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15825                try {
15826                    invokeCallback(callback, msg.what, args);
15827                } catch (RemoteException ignored) {
15828                }
15829            }
15830            mCallbacks.finishBroadcast();
15831            args.recycle();
15832        }
15833
15834        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15835                throws RemoteException {
15836            switch (what) {
15837                case MSG_CREATED: {
15838                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15839                    break;
15840                }
15841                case MSG_STATUS_CHANGED: {
15842                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15843                    break;
15844                }
15845            }
15846        }
15847
15848        private void notifyCreated(int moveId, Bundle extras) {
15849            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15850
15851            final SomeArgs args = SomeArgs.obtain();
15852            args.argi1 = moveId;
15853            args.arg2 = extras;
15854            obtainMessage(MSG_CREATED, args).sendToTarget();
15855        }
15856
15857        private void notifyStatusChanged(int moveId, int status) {
15858            notifyStatusChanged(moveId, status, -1);
15859        }
15860
15861        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15862            Slog.v(TAG, "Move " + moveId + " status " + status);
15863
15864            final SomeArgs args = SomeArgs.obtain();
15865            args.argi1 = moveId;
15866            args.argi2 = status;
15867            args.arg3 = estMillis;
15868            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15869
15870            synchronized (mLastStatus) {
15871                mLastStatus.put(moveId, status);
15872            }
15873        }
15874    }
15875
15876    private final class OnPermissionChangeListeners extends Handler {
15877        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15878
15879        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15880                new RemoteCallbackList<>();
15881
15882        public OnPermissionChangeListeners(Looper looper) {
15883            super(looper);
15884        }
15885
15886        @Override
15887        public void handleMessage(Message msg) {
15888            switch (msg.what) {
15889                case MSG_ON_PERMISSIONS_CHANGED: {
15890                    final int uid = msg.arg1;
15891                    handleOnPermissionsChanged(uid);
15892                } break;
15893            }
15894        }
15895
15896        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15897            mPermissionListeners.register(listener);
15898
15899        }
15900
15901        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15902            mPermissionListeners.unregister(listener);
15903        }
15904
15905        public void onPermissionsChanged(int uid) {
15906            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15907                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15908            }
15909        }
15910
15911        private void handleOnPermissionsChanged(int uid) {
15912            final int count = mPermissionListeners.beginBroadcast();
15913            try {
15914                for (int i = 0; i < count; i++) {
15915                    IOnPermissionsChangeListener callback = mPermissionListeners
15916                            .getBroadcastItem(i);
15917                    try {
15918                        callback.onPermissionsChanged(uid);
15919                    } catch (RemoteException e) {
15920                        Log.e(TAG, "Permission listener is dead", e);
15921                    }
15922                }
15923            } finally {
15924                mPermissionListeners.finishBroadcast();
15925            }
15926        }
15927    }
15928
15929    private class PackageManagerInternalImpl extends PackageManagerInternal {
15930        @Override
15931        public void setLocationPackagesProvider(PackagesProvider provider) {
15932            synchronized (mPackages) {
15933                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15934            }
15935        }
15936
15937        @Override
15938        public void setImePackagesProvider(PackagesProvider provider) {
15939            synchronized (mPackages) {
15940                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15941            }
15942        }
15943
15944        @Override
15945        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15946            synchronized (mPackages) {
15947                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15948            }
15949        }
15950
15951        @Override
15952        public void setSmsAppPackagesProvider(PackagesProvider provider) {
15953            synchronized (mPackages) {
15954                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
15955            }
15956        }
15957
15958        @Override
15959        public void setDialerAppPackagesProvider(PackagesProvider provider) {
15960            synchronized (mPackages) {
15961                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
15962            }
15963        }
15964
15965        @Override
15966        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
15967            synchronized (mPackages) {
15968                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
15969                        packageName, userId);
15970            }
15971        }
15972
15973        @Override
15974        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
15975            synchronized (mPackages) {
15976                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
15977                        packageName, userId);
15978            }
15979        }
15980    }
15981
15982    @Override
15983    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
15984        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
15985        synchronized (mPackages) {
15986            mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
15987                    packageNames, userId);
15988        }
15989    }
15990
15991    private static void enforceSystemOrPhoneCaller(String tag) {
15992        int callingUid = Binder.getCallingUid();
15993        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
15994            throw new SecurityException(
15995                    "Cannot call " + tag + " from UID " + callingUid);
15996        }
15997    }
15998}
15999