PackageManagerService.java revision e35360d806d0858229ec8dde4929da0bdb93e7d3
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
29import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
30import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
37import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
38import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
39import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
40import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
47import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
48import static android.content.pm.PackageManager.INSTALL_INTERNAL;
49import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
53import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
54import static android.content.pm.PackageManager.MATCH_ALL;
55import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
56import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
57import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
58import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
59import static android.content.pm.PackageManager.PERMISSION_GRANTED;
60import static android.content.pm.PackageParser.isApkFile;
61import static android.os.Process.PACKAGE_INFO_GID;
62import static android.os.Process.SYSTEM_UID;
63import static android.system.OsConstants.O_CREAT;
64import static android.system.OsConstants.O_RDWR;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
66import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
67import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
68import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
69import static com.android.internal.util.ArrayUtils.appendInt;
70import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
72import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
73import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
74import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
75
76import android.Manifest;
77import android.app.ActivityManager;
78import android.app.ActivityManagerNative;
79import android.app.AppGlobals;
80import android.app.IActivityManager;
81import android.app.admin.IDevicePolicyManager;
82import android.app.backup.IBackupManager;
83import android.app.usage.UsageStats;
84import android.app.usage.UsageStatsManager;
85import android.content.BroadcastReceiver;
86import android.content.ComponentName;
87import android.content.Context;
88import android.content.IIntentReceiver;
89import android.content.Intent;
90import android.content.IntentFilter;
91import android.content.IntentSender;
92import android.content.IntentSender.SendIntentException;
93import android.content.ServiceConnection;
94import android.content.pm.ActivityInfo;
95import android.content.pm.ApplicationInfo;
96import android.content.pm.FeatureInfo;
97import android.content.pm.IOnPermissionsChangeListener;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.IntentFilterVerificationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageManagerInternal;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Debug;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteCallbackList;
152import android.os.RemoteException;
153import android.os.SELinux;
154import android.os.ServiceManager;
155import android.os.SystemClock;
156import android.os.SystemProperties;
157import android.os.UserHandle;
158import android.os.UserManager;
159import android.os.storage.IMountService;
160import android.os.storage.StorageEventListener;
161import android.os.storage.StorageManager;
162import android.os.storage.VolumeInfo;
163import android.os.storage.VolumeRecord;
164import android.security.KeyStore;
165import android.security.SystemKeyStore;
166import android.system.ErrnoException;
167import android.system.Os;
168import android.system.StructStat;
169import android.text.TextUtils;
170import android.text.format.DateUtils;
171import android.util.ArrayMap;
172import android.util.ArraySet;
173import android.util.AtomicFile;
174import android.util.DisplayMetrics;
175import android.util.EventLog;
176import android.util.ExceptionUtils;
177import android.util.Log;
178import android.util.LogPrinter;
179import android.util.MathUtils;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.util.SparseIntArray;
185import android.util.Xml;
186import android.view.Display;
187
188import dalvik.system.DexFile;
189import dalvik.system.VMRuntime;
190
191import libcore.io.IoUtils;
192import libcore.util.EmptyArray;
193
194import com.android.internal.R;
195import com.android.internal.annotations.GuardedBy;
196import com.android.internal.app.IMediaContainerService;
197import com.android.internal.app.ResolverActivity;
198import com.android.internal.content.NativeLibraryHelper;
199import com.android.internal.content.PackageHelper;
200import com.android.internal.os.IParcelFileDescriptorFactory;
201import com.android.internal.os.SomeArgs;
202import com.android.internal.os.Zygote;
203import com.android.internal.util.ArrayUtils;
204import com.android.internal.util.FastPrintWriter;
205import com.android.internal.util.FastXmlSerializer;
206import com.android.internal.util.IndentingPrintWriter;
207import com.android.internal.util.Preconditions;
208import com.android.server.EventLogTags;
209import com.android.server.FgThread;
210import com.android.server.IntentResolver;
211import com.android.server.LocalServices;
212import com.android.server.ServiceThread;
213import com.android.server.SystemConfig;
214import com.android.server.Watchdog;
215import com.android.server.pm.PermissionsState.PermissionState;
216import com.android.server.pm.Settings.DatabaseVersion;
217import com.android.server.storage.DeviceStorageMonitorInternal;
218
219import org.xmlpull.v1.XmlPullParser;
220import org.xmlpull.v1.XmlPullParserException;
221import org.xmlpull.v1.XmlSerializer;
222
223import java.io.BufferedInputStream;
224import java.io.BufferedOutputStream;
225import java.io.BufferedReader;
226import java.io.ByteArrayInputStream;
227import java.io.ByteArrayOutputStream;
228import java.io.File;
229import java.io.FileDescriptor;
230import java.io.FileNotFoundException;
231import java.io.FileOutputStream;
232import java.io.FileReader;
233import java.io.FilenameFilter;
234import java.io.IOException;
235import java.io.InputStream;
236import java.io.PrintWriter;
237import java.nio.charset.StandardCharsets;
238import java.security.NoSuchAlgorithmException;
239import java.security.PublicKey;
240import java.security.cert.CertificateEncodingException;
241import java.security.cert.CertificateException;
242import java.text.SimpleDateFormat;
243import java.util.ArrayList;
244import java.util.Arrays;
245import java.util.Collection;
246import java.util.Collections;
247import java.util.Comparator;
248import java.util.Date;
249import java.util.Iterator;
250import java.util.List;
251import java.util.Map;
252import java.util.Objects;
253import java.util.Set;
254import java.util.concurrent.CountDownLatch;
255import java.util.concurrent.TimeUnit;
256import java.util.concurrent.atomic.AtomicBoolean;
257import java.util.concurrent.atomic.AtomicInteger;
258import java.util.concurrent.atomic.AtomicLong;
259
260/**
261 * Keep track of all those .apks everywhere.
262 *
263 * This is very central to the platform's security; please run the unit
264 * tests whenever making modifications here:
265 *
266runtest -c android.content.pm.PackageManagerTests frameworks-core
267 *
268 * {@hide}
269 */
270public class PackageManagerService extends IPackageManager.Stub {
271    static final String TAG = "PackageManager";
272    static final boolean DEBUG_SETTINGS = false;
273    static final boolean DEBUG_PREFERRED = false;
274    static final boolean DEBUG_UPGRADE = false;
275    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
276    private static final boolean DEBUG_BACKUP = true;
277    private static final boolean DEBUG_INSTALL = false;
278    private static final boolean DEBUG_REMOVE = false;
279    private static final boolean DEBUG_BROADCASTS = false;
280    private static final boolean DEBUG_SHOW_INFO = false;
281    private static final boolean DEBUG_PACKAGE_INFO = false;
282    private static final boolean DEBUG_INTENT_MATCHING = false;
283    private static final boolean DEBUG_PACKAGE_SCANNING = false;
284    private static final boolean DEBUG_VERIFY = false;
285    private static final boolean DEBUG_DEXOPT = false;
286    private static final boolean DEBUG_ABI_SELECTION = false;
287
288    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
289
290    private static final int RADIO_UID = Process.PHONE_UID;
291    private static final int LOG_UID = Process.LOG_UID;
292    private static final int NFC_UID = Process.NFC_UID;
293    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
294    private static final int SHELL_UID = Process.SHELL_UID;
295
296    // Cap the size of permission trees that 3rd party apps can define
297    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
298
299    // Suffix used during package installation when copying/moving
300    // package apks to install directory.
301    private static final String INSTALL_PACKAGE_SUFFIX = "-";
302
303    static final int SCAN_NO_DEX = 1<<1;
304    static final int SCAN_FORCE_DEX = 1<<2;
305    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
306    static final int SCAN_NEW_INSTALL = 1<<4;
307    static final int SCAN_NO_PATHS = 1<<5;
308    static final int SCAN_UPDATE_TIME = 1<<6;
309    static final int SCAN_DEFER_DEX = 1<<7;
310    static final int SCAN_BOOTING = 1<<8;
311    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
312    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
313    static final int SCAN_REQUIRE_KNOWN = 1<<12;
314    static final int SCAN_MOVE = 1<<13;
315    static final int SCAN_INITIAL = 1<<14;
316
317    static final int REMOVE_CHATTY = 1<<16;
318
319    private static final int[] EMPTY_INT_ARRAY = new int[0];
320
321    /**
322     * Timeout (in milliseconds) after which the watchdog should declare that
323     * our handler thread is wedged.  The usual default for such things is one
324     * minute but we sometimes do very lengthy I/O operations on this thread,
325     * such as installing multi-gigabyte applications, so ours needs to be longer.
326     */
327    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
328
329    /**
330     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
331     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
332     * settings entry if available, otherwise we use the hardcoded default.  If it's been
333     * more than this long since the last fstrim, we force one during the boot sequence.
334     *
335     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
336     * one gets run at the next available charging+idle time.  This final mandatory
337     * no-fstrim check kicks in only of the other scheduling criteria is never met.
338     */
339    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
340
341    /**
342     * Whether verification is enabled by default.
343     */
344    private static final boolean DEFAULT_VERIFY_ENABLE = true;
345
346    /**
347     * The default maximum time to wait for the verification agent to return in
348     * milliseconds.
349     */
350    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
351
352    /**
353     * The default response for package verification timeout.
354     *
355     * This can be either PackageManager.VERIFICATION_ALLOW or
356     * PackageManager.VERIFICATION_REJECT.
357     */
358    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
359
360    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
361
362    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
363            DEFAULT_CONTAINER_PACKAGE,
364            "com.android.defcontainer.DefaultContainerService");
365
366    private static final String KILL_APP_REASON_GIDS_CHANGED =
367            "permission grant or revoke changed gids";
368
369    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
370            "permissions revoked";
371
372    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
373
374    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
375
376    /** Permission grant: not grant the permission. */
377    private static final int GRANT_DENIED = 1;
378
379    /** Permission grant: grant the permission as an install permission. */
380    private static final int GRANT_INSTALL = 2;
381
382    /** Permission grant: grant the permission as an install permission for a legacy app. */
383    private static final int GRANT_INSTALL_LEGACY = 3;
384
385    /** Permission grant: grant the permission as a runtime one. */
386    private static final int GRANT_RUNTIME = 4;
387
388    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
389    private static final int GRANT_UPGRADE = 5;
390
391    /** Canonical intent used to identify what counts as a "web browser" app */
392    private static final Intent sBrowserIntent;
393    static {
394        sBrowserIntent = new Intent();
395        sBrowserIntent.setAction(Intent.ACTION_VIEW);
396        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
397        sBrowserIntent.setData(Uri.parse("http:"));
398    }
399
400    final ServiceThread mHandlerThread;
401
402    final PackageHandler mHandler;
403
404    /**
405     * Messages for {@link #mHandler} that need to wait for system ready before
406     * being dispatched.
407     */
408    private ArrayList<Message> mPostSystemReadyMessages;
409
410    final int mSdkVersion = Build.VERSION.SDK_INT;
411
412    final Context mContext;
413    final boolean mFactoryTest;
414    final boolean mOnlyCore;
415    final boolean mLazyDexOpt;
416    final long mDexOptLRUThresholdInMills;
417    final DisplayMetrics mMetrics;
418    final int mDefParseFlags;
419    final String[] mSeparateProcesses;
420    final boolean mIsUpgrade;
421
422    // This is where all application persistent data goes.
423    final File mAppDataDir;
424
425    // This is where all application persistent data goes for secondary users.
426    final File mUserAppDataDir;
427
428    /** The location for ASEC container files on internal storage. */
429    final String mAsecInternalPath;
430
431    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
432    // LOCK HELD.  Can be called with mInstallLock held.
433    @GuardedBy("mInstallLock")
434    final Installer mInstaller;
435
436    /** Directory where installed third-party apps stored */
437    final File mAppInstallDir;
438
439    /**
440     * Directory to which applications installed internally have their
441     * 32 bit native libraries copied.
442     */
443    private File mAppLib32InstallDir;
444
445    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
446    // apps.
447    final File mDrmAppPrivateInstallDir;
448
449    // ----------------------------------------------------------------
450
451    // Lock for state used when installing and doing other long running
452    // operations.  Methods that must be called with this lock held have
453    // the suffix "LI".
454    final Object mInstallLock = new Object();
455
456    // ----------------------------------------------------------------
457
458    // Keys are String (package name), values are Package.  This also serves
459    // as the lock for the global state.  Methods that must be called with
460    // this lock held have the prefix "LP".
461    @GuardedBy("mPackages")
462    final ArrayMap<String, PackageParser.Package> mPackages =
463            new ArrayMap<String, PackageParser.Package>();
464
465    // Tracks available target package names -> overlay package paths.
466    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
467        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
468
469    final Settings mSettings;
470    boolean mRestoredSettings;
471
472    // System configuration read by SystemConfig.
473    final int[] mGlobalGids;
474    final SparseArray<ArraySet<String>> mSystemPermissions;
475    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
476
477    // If mac_permissions.xml was found for seinfo labeling.
478    boolean mFoundPolicyFile;
479
480    // If a recursive restorecon of /data/data/<pkg> is needed.
481    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
482
483    public static final class SharedLibraryEntry {
484        public final String path;
485        public final String apk;
486
487        SharedLibraryEntry(String _path, String _apk) {
488            path = _path;
489            apk = _apk;
490        }
491    }
492
493    // Currently known shared libraries.
494    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
495            new ArrayMap<String, SharedLibraryEntry>();
496
497    // All available activities, for your resolving pleasure.
498    final ActivityIntentResolver mActivities =
499            new ActivityIntentResolver();
500
501    // All available receivers, for your resolving pleasure.
502    final ActivityIntentResolver mReceivers =
503            new ActivityIntentResolver();
504
505    // All available services, for your resolving pleasure.
506    final ServiceIntentResolver mServices = new ServiceIntentResolver();
507
508    // All available providers, for your resolving pleasure.
509    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
510
511    // Mapping from provider base names (first directory in content URI codePath)
512    // to the provider information.
513    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
514            new ArrayMap<String, PackageParser.Provider>();
515
516    // Mapping from instrumentation class names to info about them.
517    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
518            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
519
520    // Mapping from permission names to info about them.
521    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
522            new ArrayMap<String, PackageParser.PermissionGroup>();
523
524    // Packages whose data we have transfered into another package, thus
525    // should no longer exist.
526    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
527
528    // Broadcast actions that are only available to the system.
529    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
530
531    /** List of packages waiting for verification. */
532    final SparseArray<PackageVerificationState> mPendingVerification
533            = new SparseArray<PackageVerificationState>();
534
535    /** Set of packages associated with each app op permission. */
536    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
537
538    final PackageInstallerService mInstallerService;
539
540    private final PackageDexOptimizer mPackageDexOptimizer;
541
542    private AtomicInteger mNextMoveId = new AtomicInteger();
543    private final MoveCallbacks mMoveCallbacks;
544
545    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
546
547    // Cache of users who need badging.
548    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
549
550    /** Token for keys in mPendingVerification. */
551    private int mPendingVerificationToken = 0;
552
553    volatile boolean mSystemReady;
554    volatile boolean mSafeMode;
555    volatile boolean mHasSystemUidErrors;
556
557    ApplicationInfo mAndroidApplication;
558    final ActivityInfo mResolveActivity = new ActivityInfo();
559    final ResolveInfo mResolveInfo = new ResolveInfo();
560    ComponentName mResolveComponentName;
561    PackageParser.Package mPlatformPackage;
562    ComponentName mCustomResolverComponentName;
563
564    boolean mResolverReplaced = false;
565
566    private final ComponentName mIntentFilterVerifierComponent;
567    private int mIntentFilterVerificationToken = 0;
568
569    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
570            = new SparseArray<IntentFilterVerificationState>();
571
572    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
573            new DefaultPermissionGrantPolicy(this);
574
575    private static class IFVerificationParams {
576        PackageParser.Package pkg;
577        boolean replacing;
578        int userId;
579        int verifierUid;
580
581        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
582                int _userId, int _verifierUid) {
583            pkg = _pkg;
584            replacing = _replacing;
585            userId = _userId;
586            replacing = _replacing;
587            verifierUid = _verifierUid;
588        }
589    }
590
591    private interface IntentFilterVerifier<T extends IntentFilter> {
592        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
593                                               T filter, String packageName);
594        void startVerifications(int userId);
595        void receiveVerificationResponse(int verificationId);
596    }
597
598    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
599        private Context mContext;
600        private ComponentName mIntentFilterVerifierComponent;
601        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
602
603        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
604            mContext = context;
605            mIntentFilterVerifierComponent = verifierComponent;
606        }
607
608        private String getDefaultScheme() {
609            return IntentFilter.SCHEME_HTTPS;
610        }
611
612        @Override
613        public void startVerifications(int userId) {
614            // Launch verifications requests
615            int count = mCurrentIntentFilterVerifications.size();
616            for (int n=0; n<count; n++) {
617                int verificationId = mCurrentIntentFilterVerifications.get(n);
618                final IntentFilterVerificationState ivs =
619                        mIntentFilterVerificationStates.get(verificationId);
620
621                String packageName = ivs.getPackageName();
622
623                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
624                final int filterCount = filters.size();
625                ArraySet<String> domainsSet = new ArraySet<>();
626                for (int m=0; m<filterCount; m++) {
627                    PackageParser.ActivityIntentInfo filter = filters.get(m);
628                    domainsSet.addAll(filter.getHostsList());
629                }
630                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
631                synchronized (mPackages) {
632                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
633                            packageName, domainsList) != null) {
634                        scheduleWriteSettingsLocked();
635                    }
636                }
637                sendVerificationRequest(userId, verificationId, ivs);
638            }
639            mCurrentIntentFilterVerifications.clear();
640        }
641
642        private void sendVerificationRequest(int userId, int verificationId,
643                IntentFilterVerificationState ivs) {
644
645            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
646            verificationIntent.putExtra(
647                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
648                    verificationId);
649            verificationIntent.putExtra(
650                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
651                    getDefaultScheme());
652            verificationIntent.putExtra(
653                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
654                    ivs.getHostsString());
655            verificationIntent.putExtra(
656                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
657                    ivs.getPackageName());
658            verificationIntent.setComponent(mIntentFilterVerifierComponent);
659            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
660
661            UserHandle user = new UserHandle(userId);
662            mContext.sendBroadcastAsUser(verificationIntent, user);
663            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
664                    "Sending IntentFilter verification broadcast");
665        }
666
667        public void receiveVerificationResponse(int verificationId) {
668            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
669
670            final boolean verified = ivs.isVerified();
671
672            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
673            final int count = filters.size();
674            if (DEBUG_DOMAIN_VERIFICATION) {
675                Slog.i(TAG, "Received verification response " + verificationId
676                        + " for " + count + " filters, verified=" + verified);
677            }
678            for (int n=0; n<count; n++) {
679                PackageParser.ActivityIntentInfo filter = filters.get(n);
680                filter.setVerified(verified);
681
682                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
683                        + " verified with result:" + verified + " and hosts:"
684                        + ivs.getHostsString());
685            }
686
687            mIntentFilterVerificationStates.remove(verificationId);
688
689            final String packageName = ivs.getPackageName();
690            IntentFilterVerificationInfo ivi = null;
691
692            synchronized (mPackages) {
693                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
694            }
695            if (ivi == null) {
696                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
697                        + verificationId + " packageName:" + packageName);
698                return;
699            }
700            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
701                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
702
703            synchronized (mPackages) {
704                if (verified) {
705                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
706                } else {
707                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
708                }
709                scheduleWriteSettingsLocked();
710
711                final int userId = ivs.getUserId();
712                if (userId != UserHandle.USER_ALL) {
713                    final int userStatus =
714                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
715
716                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
717                    boolean needUpdate = false;
718
719                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
720                    // already been set by the User thru the Disambiguation dialog
721                    switch (userStatus) {
722                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
723                            if (verified) {
724                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
725                            } else {
726                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
727                            }
728                            needUpdate = true;
729                            break;
730
731                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
732                            if (verified) {
733                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
734                                needUpdate = true;
735                            }
736                            break;
737
738                        default:
739                            // Nothing to do
740                    }
741
742                    if (needUpdate) {
743                        mSettings.updateIntentFilterVerificationStatusLPw(
744                                packageName, updatedStatus, userId);
745                        scheduleWritePackageRestrictionsLocked(userId);
746                    }
747                }
748            }
749        }
750
751        @Override
752        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
753                    ActivityIntentInfo filter, String packageName) {
754            if (!hasValidDomains(filter)) {
755                return false;
756            }
757            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
758            if (ivs == null) {
759                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
760                        packageName);
761            }
762            if (DEBUG_DOMAIN_VERIFICATION) {
763                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
764            }
765            ivs.addFilter(filter);
766            return true;
767        }
768
769        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
770                int userId, int verificationId, String packageName) {
771            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
772                    verifierUid, userId, packageName);
773            ivs.setPendingState();
774            synchronized (mPackages) {
775                mIntentFilterVerificationStates.append(verificationId, ivs);
776                mCurrentIntentFilterVerifications.add(verificationId);
777            }
778            return ivs;
779        }
780    }
781
782    private static boolean hasValidDomains(ActivityIntentInfo filter) {
783        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
784                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
785        if (!hasHTTPorHTTPS) {
786            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
787                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
788            return false;
789        }
790        return true;
791    }
792
793    private IntentFilterVerifier mIntentFilterVerifier;
794
795    // Set of pending broadcasts for aggregating enable/disable of components.
796    static class PendingPackageBroadcasts {
797        // for each user id, a map of <package name -> components within that package>
798        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
799
800        public PendingPackageBroadcasts() {
801            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
802        }
803
804        public ArrayList<String> get(int userId, String packageName) {
805            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
806            return packages.get(packageName);
807        }
808
809        public void put(int userId, String packageName, ArrayList<String> components) {
810            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
811            packages.put(packageName, components);
812        }
813
814        public void remove(int userId, String packageName) {
815            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
816            if (packages != null) {
817                packages.remove(packageName);
818            }
819        }
820
821        public void remove(int userId) {
822            mUidMap.remove(userId);
823        }
824
825        public int userIdCount() {
826            return mUidMap.size();
827        }
828
829        public int userIdAt(int n) {
830            return mUidMap.keyAt(n);
831        }
832
833        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
834            return mUidMap.get(userId);
835        }
836
837        public int size() {
838            // total number of pending broadcast entries across all userIds
839            int num = 0;
840            for (int i = 0; i< mUidMap.size(); i++) {
841                num += mUidMap.valueAt(i).size();
842            }
843            return num;
844        }
845
846        public void clear() {
847            mUidMap.clear();
848        }
849
850        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
851            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
852            if (map == null) {
853                map = new ArrayMap<String, ArrayList<String>>();
854                mUidMap.put(userId, map);
855            }
856            return map;
857        }
858    }
859    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
860
861    // Service Connection to remote media container service to copy
862    // package uri's from external media onto secure containers
863    // or internal storage.
864    private IMediaContainerService mContainerService = null;
865
866    static final int SEND_PENDING_BROADCAST = 1;
867    static final int MCS_BOUND = 3;
868    static final int END_COPY = 4;
869    static final int INIT_COPY = 5;
870    static final int MCS_UNBIND = 6;
871    static final int START_CLEANING_PACKAGE = 7;
872    static final int FIND_INSTALL_LOC = 8;
873    static final int POST_INSTALL = 9;
874    static final int MCS_RECONNECT = 10;
875    static final int MCS_GIVE_UP = 11;
876    static final int UPDATED_MEDIA_STATUS = 12;
877    static final int WRITE_SETTINGS = 13;
878    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
879    static final int PACKAGE_VERIFIED = 15;
880    static final int CHECK_PENDING_VERIFICATION = 16;
881    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
882    static final int INTENT_FILTER_VERIFIED = 18;
883
884    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
885
886    // Delay time in millisecs
887    static final int BROADCAST_DELAY = 10 * 1000;
888
889    static UserManagerService sUserManager;
890
891    // Stores a list of users whose package restrictions file needs to be updated
892    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
893
894    final private DefaultContainerConnection mDefContainerConn =
895            new DefaultContainerConnection();
896    class DefaultContainerConnection implements ServiceConnection {
897        public void onServiceConnected(ComponentName name, IBinder service) {
898            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
899            IMediaContainerService imcs =
900                IMediaContainerService.Stub.asInterface(service);
901            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
902        }
903
904        public void onServiceDisconnected(ComponentName name) {
905            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
906        }
907    }
908
909    // Recordkeeping of restore-after-install operations that are currently in flight
910    // between the Package Manager and the Backup Manager
911    class PostInstallData {
912        public InstallArgs args;
913        public PackageInstalledInfo res;
914
915        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
916            args = _a;
917            res = _r;
918        }
919    }
920
921    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
922    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
923
924    // XML tags for backup/restore of various bits of state
925    private static final String TAG_PREFERRED_BACKUP = "pa";
926    private static final String TAG_DEFAULT_APPS = "da";
927    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
928
929    private final String mRequiredVerifierPackage;
930
931    private final PackageUsage mPackageUsage = new PackageUsage();
932
933    private class PackageUsage {
934        private static final int WRITE_INTERVAL
935            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
936
937        private final Object mFileLock = new Object();
938        private final AtomicLong mLastWritten = new AtomicLong(0);
939        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
940
941        private boolean mIsHistoricalPackageUsageAvailable = true;
942
943        boolean isHistoricalPackageUsageAvailable() {
944            return mIsHistoricalPackageUsageAvailable;
945        }
946
947        void write(boolean force) {
948            if (force) {
949                writeInternal();
950                return;
951            }
952            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
953                && !DEBUG_DEXOPT) {
954                return;
955            }
956            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
957                new Thread("PackageUsage_DiskWriter") {
958                    @Override
959                    public void run() {
960                        try {
961                            writeInternal();
962                        } finally {
963                            mBackgroundWriteRunning.set(false);
964                        }
965                    }
966                }.start();
967            }
968        }
969
970        private void writeInternal() {
971            synchronized (mPackages) {
972                synchronized (mFileLock) {
973                    AtomicFile file = getFile();
974                    FileOutputStream f = null;
975                    try {
976                        f = file.startWrite();
977                        BufferedOutputStream out = new BufferedOutputStream(f);
978                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
979                        StringBuilder sb = new StringBuilder();
980                        for (PackageParser.Package pkg : mPackages.values()) {
981                            if (pkg.mLastPackageUsageTimeInMills == 0) {
982                                continue;
983                            }
984                            sb.setLength(0);
985                            sb.append(pkg.packageName);
986                            sb.append(' ');
987                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
988                            sb.append('\n');
989                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
990                        }
991                        out.flush();
992                        file.finishWrite(f);
993                    } catch (IOException e) {
994                        if (f != null) {
995                            file.failWrite(f);
996                        }
997                        Log.e(TAG, "Failed to write package usage times", e);
998                    }
999                }
1000            }
1001            mLastWritten.set(SystemClock.elapsedRealtime());
1002        }
1003
1004        void readLP() {
1005            synchronized (mFileLock) {
1006                AtomicFile file = getFile();
1007                BufferedInputStream in = null;
1008                try {
1009                    in = new BufferedInputStream(file.openRead());
1010                    StringBuffer sb = new StringBuffer();
1011                    while (true) {
1012                        String packageName = readToken(in, sb, ' ');
1013                        if (packageName == null) {
1014                            break;
1015                        }
1016                        String timeInMillisString = readToken(in, sb, '\n');
1017                        if (timeInMillisString == null) {
1018                            throw new IOException("Failed to find last usage time for package "
1019                                                  + packageName);
1020                        }
1021                        PackageParser.Package pkg = mPackages.get(packageName);
1022                        if (pkg == null) {
1023                            continue;
1024                        }
1025                        long timeInMillis;
1026                        try {
1027                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1028                        } catch (NumberFormatException e) {
1029                            throw new IOException("Failed to parse " + timeInMillisString
1030                                                  + " as a long.", e);
1031                        }
1032                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1033                    }
1034                } catch (FileNotFoundException expected) {
1035                    mIsHistoricalPackageUsageAvailable = false;
1036                } catch (IOException e) {
1037                    Log.w(TAG, "Failed to read package usage times", e);
1038                } finally {
1039                    IoUtils.closeQuietly(in);
1040                }
1041            }
1042            mLastWritten.set(SystemClock.elapsedRealtime());
1043        }
1044
1045        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1046                throws IOException {
1047            sb.setLength(0);
1048            while (true) {
1049                int ch = in.read();
1050                if (ch == -1) {
1051                    if (sb.length() == 0) {
1052                        return null;
1053                    }
1054                    throw new IOException("Unexpected EOF");
1055                }
1056                if (ch == endOfToken) {
1057                    return sb.toString();
1058                }
1059                sb.append((char)ch);
1060            }
1061        }
1062
1063        private AtomicFile getFile() {
1064            File dataDir = Environment.getDataDirectory();
1065            File systemDir = new File(dataDir, "system");
1066            File fname = new File(systemDir, "package-usage.list");
1067            return new AtomicFile(fname);
1068        }
1069    }
1070
1071    class PackageHandler extends Handler {
1072        private boolean mBound = false;
1073        final ArrayList<HandlerParams> mPendingInstalls =
1074            new ArrayList<HandlerParams>();
1075
1076        private boolean connectToService() {
1077            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1078                    " DefaultContainerService");
1079            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1080            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1081            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1082                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1083                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1084                mBound = true;
1085                return true;
1086            }
1087            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1088            return false;
1089        }
1090
1091        private void disconnectService() {
1092            mContainerService = null;
1093            mBound = false;
1094            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1095            mContext.unbindService(mDefContainerConn);
1096            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1097        }
1098
1099        PackageHandler(Looper looper) {
1100            super(looper);
1101        }
1102
1103        public void handleMessage(Message msg) {
1104            try {
1105                doHandleMessage(msg);
1106            } finally {
1107                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1108            }
1109        }
1110
1111        void doHandleMessage(Message msg) {
1112            switch (msg.what) {
1113                case INIT_COPY: {
1114                    HandlerParams params = (HandlerParams) msg.obj;
1115                    int idx = mPendingInstalls.size();
1116                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1117                    // If a bind was already initiated we dont really
1118                    // need to do anything. The pending install
1119                    // will be processed later on.
1120                    if (!mBound) {
1121                        // If this is the only one pending we might
1122                        // have to bind to the service again.
1123                        if (!connectToService()) {
1124                            Slog.e(TAG, "Failed to bind to media container service");
1125                            params.serviceError();
1126                            return;
1127                        } else {
1128                            // Once we bind to the service, the first
1129                            // pending request will be processed.
1130                            mPendingInstalls.add(idx, params);
1131                        }
1132                    } else {
1133                        mPendingInstalls.add(idx, params);
1134                        // Already bound to the service. Just make
1135                        // sure we trigger off processing the first request.
1136                        if (idx == 0) {
1137                            mHandler.sendEmptyMessage(MCS_BOUND);
1138                        }
1139                    }
1140                    break;
1141                }
1142                case MCS_BOUND: {
1143                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1144                    if (msg.obj != null) {
1145                        mContainerService = (IMediaContainerService) msg.obj;
1146                    }
1147                    if (mContainerService == null) {
1148                        if (!mBound) {
1149                            // Something seriously wrong since we are not bound and we are not
1150                            // waiting for connection. Bail out.
1151                            Slog.e(TAG, "Cannot bind to media container service");
1152                            for (HandlerParams params : mPendingInstalls) {
1153                                // Indicate service bind error
1154                                params.serviceError();
1155                            }
1156                            mPendingInstalls.clear();
1157                        } else {
1158                            Slog.w(TAG, "Waiting to connect to media container service");
1159                        }
1160                    } else if (mPendingInstalls.size() > 0) {
1161                        HandlerParams params = mPendingInstalls.get(0);
1162                        if (params != null) {
1163                            if (params.startCopy()) {
1164                                // We are done...  look for more work or to
1165                                // go idle.
1166                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1167                                        "Checking for more work or unbind...");
1168                                // Delete pending install
1169                                if (mPendingInstalls.size() > 0) {
1170                                    mPendingInstalls.remove(0);
1171                                }
1172                                if (mPendingInstalls.size() == 0) {
1173                                    if (mBound) {
1174                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1175                                                "Posting delayed MCS_UNBIND");
1176                                        removeMessages(MCS_UNBIND);
1177                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1178                                        // Unbind after a little delay, to avoid
1179                                        // continual thrashing.
1180                                        sendMessageDelayed(ubmsg, 10000);
1181                                    }
1182                                } else {
1183                                    // There are more pending requests in queue.
1184                                    // Just post MCS_BOUND message to trigger processing
1185                                    // of next pending install.
1186                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1187                                            "Posting MCS_BOUND for next work");
1188                                    mHandler.sendEmptyMessage(MCS_BOUND);
1189                                }
1190                            }
1191                        }
1192                    } else {
1193                        // Should never happen ideally.
1194                        Slog.w(TAG, "Empty queue");
1195                    }
1196                    break;
1197                }
1198                case MCS_RECONNECT: {
1199                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1200                    if (mPendingInstalls.size() > 0) {
1201                        if (mBound) {
1202                            disconnectService();
1203                        }
1204                        if (!connectToService()) {
1205                            Slog.e(TAG, "Failed to bind to media container service");
1206                            for (HandlerParams params : mPendingInstalls) {
1207                                // Indicate service bind error
1208                                params.serviceError();
1209                            }
1210                            mPendingInstalls.clear();
1211                        }
1212                    }
1213                    break;
1214                }
1215                case MCS_UNBIND: {
1216                    // If there is no actual work left, then time to unbind.
1217                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1218
1219                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1220                        if (mBound) {
1221                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1222
1223                            disconnectService();
1224                        }
1225                    } else if (mPendingInstalls.size() > 0) {
1226                        // There are more pending requests in queue.
1227                        // Just post MCS_BOUND message to trigger processing
1228                        // of next pending install.
1229                        mHandler.sendEmptyMessage(MCS_BOUND);
1230                    }
1231
1232                    break;
1233                }
1234                case MCS_GIVE_UP: {
1235                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1236                    mPendingInstalls.remove(0);
1237                    break;
1238                }
1239                case SEND_PENDING_BROADCAST: {
1240                    String packages[];
1241                    ArrayList<String> components[];
1242                    int size = 0;
1243                    int uids[];
1244                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1245                    synchronized (mPackages) {
1246                        if (mPendingBroadcasts == null) {
1247                            return;
1248                        }
1249                        size = mPendingBroadcasts.size();
1250                        if (size <= 0) {
1251                            // Nothing to be done. Just return
1252                            return;
1253                        }
1254                        packages = new String[size];
1255                        components = new ArrayList[size];
1256                        uids = new int[size];
1257                        int i = 0;  // filling out the above arrays
1258
1259                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1260                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1261                            Iterator<Map.Entry<String, ArrayList<String>>> it
1262                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1263                                            .entrySet().iterator();
1264                            while (it.hasNext() && i < size) {
1265                                Map.Entry<String, ArrayList<String>> ent = it.next();
1266                                packages[i] = ent.getKey();
1267                                components[i] = ent.getValue();
1268                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1269                                uids[i] = (ps != null)
1270                                        ? UserHandle.getUid(packageUserId, ps.appId)
1271                                        : -1;
1272                                i++;
1273                            }
1274                        }
1275                        size = i;
1276                        mPendingBroadcasts.clear();
1277                    }
1278                    // Send broadcasts
1279                    for (int i = 0; i < size; i++) {
1280                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1281                    }
1282                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1283                    break;
1284                }
1285                case START_CLEANING_PACKAGE: {
1286                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1287                    final String packageName = (String)msg.obj;
1288                    final int userId = msg.arg1;
1289                    final boolean andCode = msg.arg2 != 0;
1290                    synchronized (mPackages) {
1291                        if (userId == UserHandle.USER_ALL) {
1292                            int[] users = sUserManager.getUserIds();
1293                            for (int user : users) {
1294                                mSettings.addPackageToCleanLPw(
1295                                        new PackageCleanItem(user, packageName, andCode));
1296                            }
1297                        } else {
1298                            mSettings.addPackageToCleanLPw(
1299                                    new PackageCleanItem(userId, packageName, andCode));
1300                        }
1301                    }
1302                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1303                    startCleaningPackages();
1304                } break;
1305                case POST_INSTALL: {
1306                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1307                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1308                    mRunningInstalls.delete(msg.arg1);
1309                    boolean deleteOld = false;
1310
1311                    if (data != null) {
1312                        InstallArgs args = data.args;
1313                        PackageInstalledInfo res = data.res;
1314
1315                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1316                            final String packageName = res.pkg.applicationInfo.packageName;
1317                            res.removedInfo.sendBroadcast(false, true, false);
1318                            Bundle extras = new Bundle(1);
1319                            extras.putInt(Intent.EXTRA_UID, res.uid);
1320
1321                            // Now that we successfully installed the package, grant runtime
1322                            // permissions if requested before broadcasting the install.
1323                            if ((args.installFlags
1324                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1325                                grantRequestedRuntimePermissions(res.pkg,
1326                                        args.user.getIdentifier());
1327                            }
1328
1329                            // Determine the set of users who are adding this
1330                            // package for the first time vs. those who are seeing
1331                            // an update.
1332                            int[] firstUsers;
1333                            int[] updateUsers = new int[0];
1334                            if (res.origUsers == null || res.origUsers.length == 0) {
1335                                firstUsers = res.newUsers;
1336                            } else {
1337                                firstUsers = new int[0];
1338                                for (int i=0; i<res.newUsers.length; i++) {
1339                                    int user = res.newUsers[i];
1340                                    boolean isNew = true;
1341                                    for (int j=0; j<res.origUsers.length; j++) {
1342                                        if (res.origUsers[j] == user) {
1343                                            isNew = false;
1344                                            break;
1345                                        }
1346                                    }
1347                                    if (isNew) {
1348                                        int[] newFirst = new int[firstUsers.length+1];
1349                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1350                                                firstUsers.length);
1351                                        newFirst[firstUsers.length] = user;
1352                                        firstUsers = newFirst;
1353                                    } else {
1354                                        int[] newUpdate = new int[updateUsers.length+1];
1355                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1356                                                updateUsers.length);
1357                                        newUpdate[updateUsers.length] = user;
1358                                        updateUsers = newUpdate;
1359                                    }
1360                                }
1361                            }
1362                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1363                                    packageName, extras, null, null, firstUsers);
1364                            final boolean update = res.removedInfo.removedPackage != null;
1365                            if (update) {
1366                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1367                            }
1368                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1369                                    packageName, extras, null, null, updateUsers);
1370                            if (update) {
1371                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1372                                        packageName, extras, null, null, updateUsers);
1373                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1374                                        null, null, packageName, null, updateUsers);
1375
1376                                // treat asec-hosted packages like removable media on upgrade
1377                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1378                                    if (DEBUG_INSTALL) {
1379                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1380                                                + " is ASEC-hosted -> AVAILABLE");
1381                                    }
1382                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1383                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1384                                    pkgList.add(packageName);
1385                                    sendResourcesChangedBroadcast(true, true,
1386                                            pkgList,uidArray, null);
1387                                }
1388                            }
1389                            if (res.removedInfo.args != null) {
1390                                // Remove the replaced package's older resources safely now
1391                                deleteOld = true;
1392                            }
1393
1394                            // If this app is a browser and it's newly-installed for some
1395                            // users, clear any default-browser state in those users
1396                            if (firstUsers.length > 0) {
1397                                // the app's nature doesn't depend on the user, so we can just
1398                                // check its browser nature in any user and generalize.
1399                                if (packageIsBrowser(packageName, firstUsers[0])) {
1400                                    synchronized (mPackages) {
1401                                        for (int userId : firstUsers) {
1402                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1403                                        }
1404                                    }
1405                                }
1406                            }
1407                            // Log current value of "unknown sources" setting
1408                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1409                                getUnknownSourcesSettings());
1410                        }
1411                        // Force a gc to clear up things
1412                        Runtime.getRuntime().gc();
1413                        // We delete after a gc for applications  on sdcard.
1414                        if (deleteOld) {
1415                            synchronized (mInstallLock) {
1416                                res.removedInfo.args.doPostDeleteLI(true);
1417                            }
1418                        }
1419                        if (args.observer != null) {
1420                            try {
1421                                Bundle extras = extrasForInstallResult(res);
1422                                args.observer.onPackageInstalled(res.name, res.returnCode,
1423                                        res.returnMsg, extras);
1424                            } catch (RemoteException e) {
1425                                Slog.i(TAG, "Observer no longer exists.");
1426                            }
1427                        }
1428                    } else {
1429                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1430                    }
1431                } break;
1432                case UPDATED_MEDIA_STATUS: {
1433                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1434                    boolean reportStatus = msg.arg1 == 1;
1435                    boolean doGc = msg.arg2 == 1;
1436                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1437                    if (doGc) {
1438                        // Force a gc to clear up stale containers.
1439                        Runtime.getRuntime().gc();
1440                    }
1441                    if (msg.obj != null) {
1442                        @SuppressWarnings("unchecked")
1443                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1444                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1445                        // Unload containers
1446                        unloadAllContainers(args);
1447                    }
1448                    if (reportStatus) {
1449                        try {
1450                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1451                            PackageHelper.getMountService().finishMediaUpdate();
1452                        } catch (RemoteException e) {
1453                            Log.e(TAG, "MountService not running?");
1454                        }
1455                    }
1456                } break;
1457                case WRITE_SETTINGS: {
1458                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1459                    synchronized (mPackages) {
1460                        removeMessages(WRITE_SETTINGS);
1461                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1462                        mSettings.writeLPr();
1463                        mDirtyUsers.clear();
1464                    }
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1466                } break;
1467                case WRITE_PACKAGE_RESTRICTIONS: {
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1469                    synchronized (mPackages) {
1470                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1471                        for (int userId : mDirtyUsers) {
1472                            mSettings.writePackageRestrictionsLPr(userId);
1473                        }
1474                        mDirtyUsers.clear();
1475                    }
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1477                } break;
1478                case CHECK_PENDING_VERIFICATION: {
1479                    final int verificationId = msg.arg1;
1480                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1481
1482                    if ((state != null) && !state.timeoutExtended()) {
1483                        final InstallArgs args = state.getInstallArgs();
1484                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1485
1486                        Slog.i(TAG, "Verification timed out for " + originUri);
1487                        mPendingVerification.remove(verificationId);
1488
1489                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1490
1491                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1492                            Slog.i(TAG, "Continuing with installation of " + originUri);
1493                            state.setVerifierResponse(Binder.getCallingUid(),
1494                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1495                            broadcastPackageVerified(verificationId, originUri,
1496                                    PackageManager.VERIFICATION_ALLOW,
1497                                    state.getInstallArgs().getUser());
1498                            try {
1499                                ret = args.copyApk(mContainerService, true);
1500                            } catch (RemoteException e) {
1501                                Slog.e(TAG, "Could not contact the ContainerService");
1502                            }
1503                        } else {
1504                            broadcastPackageVerified(verificationId, originUri,
1505                                    PackageManager.VERIFICATION_REJECT,
1506                                    state.getInstallArgs().getUser());
1507                        }
1508
1509                        processPendingInstall(args, ret);
1510                        mHandler.sendEmptyMessage(MCS_UNBIND);
1511                    }
1512                    break;
1513                }
1514                case PACKAGE_VERIFIED: {
1515                    final int verificationId = msg.arg1;
1516
1517                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1518                    if (state == null) {
1519                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1520                        break;
1521                    }
1522
1523                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1524
1525                    state.setVerifierResponse(response.callerUid, response.code);
1526
1527                    if (state.isVerificationComplete()) {
1528                        mPendingVerification.remove(verificationId);
1529
1530                        final InstallArgs args = state.getInstallArgs();
1531                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1532
1533                        int ret;
1534                        if (state.isInstallAllowed()) {
1535                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1536                            broadcastPackageVerified(verificationId, originUri,
1537                                    response.code, state.getInstallArgs().getUser());
1538                            try {
1539                                ret = args.copyApk(mContainerService, true);
1540                            } catch (RemoteException e) {
1541                                Slog.e(TAG, "Could not contact the ContainerService");
1542                            }
1543                        } else {
1544                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1545                        }
1546
1547                        processPendingInstall(args, ret);
1548
1549                        mHandler.sendEmptyMessage(MCS_UNBIND);
1550                    }
1551
1552                    break;
1553                }
1554                case START_INTENT_FILTER_VERIFICATIONS: {
1555                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1556                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1557                            params.replacing, params.pkg);
1558                    break;
1559                }
1560                case INTENT_FILTER_VERIFIED: {
1561                    final int verificationId = msg.arg1;
1562
1563                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1564                            verificationId);
1565                    if (state == null) {
1566                        Slog.w(TAG, "Invalid IntentFilter verification token "
1567                                + verificationId + " received");
1568                        break;
1569                    }
1570
1571                    final int userId = state.getUserId();
1572
1573                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1574                            "Processing IntentFilter verification with token:"
1575                            + verificationId + " and userId:" + userId);
1576
1577                    final IntentFilterVerificationResponse response =
1578                            (IntentFilterVerificationResponse) msg.obj;
1579
1580                    state.setVerifierResponse(response.callerUid, response.code);
1581
1582                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1583                            "IntentFilter verification with token:" + verificationId
1584                            + " and userId:" + userId
1585                            + " is settings verifier response with response code:"
1586                            + response.code);
1587
1588                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1589                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1590                                + response.getFailedDomainsString());
1591                    }
1592
1593                    if (state.isVerificationComplete()) {
1594                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1595                    } else {
1596                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1597                                "IntentFilter verification with token:" + verificationId
1598                                + " was not said to be complete");
1599                    }
1600
1601                    break;
1602                }
1603            }
1604        }
1605    }
1606
1607    private StorageEventListener mStorageListener = new StorageEventListener() {
1608        @Override
1609        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1610            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1611                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1612                    final String volumeUuid = vol.getFsUuid();
1613
1614                    // Clean up any users or apps that were removed or recreated
1615                    // while this volume was missing
1616                    reconcileUsers(volumeUuid);
1617                    reconcileApps(volumeUuid);
1618
1619                    // Clean up any install sessions that expired or were
1620                    // cancelled while this volume was missing
1621                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1622
1623                    loadPrivatePackages(vol);
1624
1625                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1626                    unloadPrivatePackages(vol);
1627                }
1628            }
1629
1630            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1631                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1632                    updateExternalMediaStatus(true, false);
1633                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1634                    updateExternalMediaStatus(false, false);
1635                }
1636            }
1637        }
1638
1639        @Override
1640        public void onVolumeForgotten(String fsUuid) {
1641            // Remove any apps installed on the forgotten volume
1642            synchronized (mPackages) {
1643                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1644                for (PackageSetting ps : packages) {
1645                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1646                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1647                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1648                }
1649
1650                mSettings.writeLPr();
1651            }
1652        }
1653    };
1654
1655    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1656        if (userId >= UserHandle.USER_OWNER) {
1657            grantRequestedRuntimePermissionsForUser(pkg, userId);
1658        } else if (userId == UserHandle.USER_ALL) {
1659            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1660                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1661            }
1662        }
1663
1664        // We could have touched GID membership, so flush out packages.list
1665        synchronized (mPackages) {
1666            mSettings.writePackageListLPr();
1667        }
1668    }
1669
1670    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1671        SettingBase sb = (SettingBase) pkg.mExtras;
1672        if (sb == null) {
1673            return;
1674        }
1675
1676        PermissionsState permissionsState = sb.getPermissionsState();
1677
1678        for (String permission : pkg.requestedPermissions) {
1679            BasePermission bp = mSettings.mPermissions.get(permission);
1680            if (bp != null && bp.isRuntime()) {
1681                permissionsState.grantRuntimePermission(bp, userId);
1682            }
1683        }
1684    }
1685
1686    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1687        Bundle extras = null;
1688        switch (res.returnCode) {
1689            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1690                extras = new Bundle();
1691                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1692                        res.origPermission);
1693                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1694                        res.origPackage);
1695                break;
1696            }
1697            case PackageManager.INSTALL_SUCCEEDED: {
1698                extras = new Bundle();
1699                extras.putBoolean(Intent.EXTRA_REPLACING,
1700                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1701                break;
1702            }
1703        }
1704        return extras;
1705    }
1706
1707    void scheduleWriteSettingsLocked() {
1708        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1709            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1710        }
1711    }
1712
1713    void scheduleWritePackageRestrictionsLocked(int userId) {
1714        if (!sUserManager.exists(userId)) return;
1715        mDirtyUsers.add(userId);
1716        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1717            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1718        }
1719    }
1720
1721    public static PackageManagerService main(Context context, Installer installer,
1722            boolean factoryTest, boolean onlyCore) {
1723        PackageManagerService m = new PackageManagerService(context, installer,
1724                factoryTest, onlyCore);
1725        ServiceManager.addService("package", m);
1726        return m;
1727    }
1728
1729    static String[] splitString(String str, char sep) {
1730        int count = 1;
1731        int i = 0;
1732        while ((i=str.indexOf(sep, i)) >= 0) {
1733            count++;
1734            i++;
1735        }
1736
1737        String[] res = new String[count];
1738        i=0;
1739        count = 0;
1740        int lastI=0;
1741        while ((i=str.indexOf(sep, i)) >= 0) {
1742            res[count] = str.substring(lastI, i);
1743            count++;
1744            i++;
1745            lastI = i;
1746        }
1747        res[count] = str.substring(lastI, str.length());
1748        return res;
1749    }
1750
1751    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1752        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1753                Context.DISPLAY_SERVICE);
1754        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1755    }
1756
1757    public PackageManagerService(Context context, Installer installer,
1758            boolean factoryTest, boolean onlyCore) {
1759        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1760                SystemClock.uptimeMillis());
1761
1762        if (mSdkVersion <= 0) {
1763            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1764        }
1765
1766        mContext = context;
1767        mFactoryTest = factoryTest;
1768        mOnlyCore = onlyCore;
1769        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1770        mMetrics = new DisplayMetrics();
1771        mSettings = new Settings(mPackages);
1772        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1773                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1774        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1775                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1776        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1777                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1778        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1779                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1780        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1781                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1782        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1783                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1784
1785        // TODO: add a property to control this?
1786        long dexOptLRUThresholdInMinutes;
1787        if (mLazyDexOpt) {
1788            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1789        } else {
1790            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1791        }
1792        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1793
1794        String separateProcesses = SystemProperties.get("debug.separate_processes");
1795        if (separateProcesses != null && separateProcesses.length() > 0) {
1796            if ("*".equals(separateProcesses)) {
1797                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1798                mSeparateProcesses = null;
1799                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1800            } else {
1801                mDefParseFlags = 0;
1802                mSeparateProcesses = separateProcesses.split(",");
1803                Slog.w(TAG, "Running with debug.separate_processes: "
1804                        + separateProcesses);
1805            }
1806        } else {
1807            mDefParseFlags = 0;
1808            mSeparateProcesses = null;
1809        }
1810
1811        mInstaller = installer;
1812        mPackageDexOptimizer = new PackageDexOptimizer(this);
1813        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1814
1815        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1816                FgThread.get().getLooper());
1817
1818        getDefaultDisplayMetrics(context, mMetrics);
1819
1820        SystemConfig systemConfig = SystemConfig.getInstance();
1821        mGlobalGids = systemConfig.getGlobalGids();
1822        mSystemPermissions = systemConfig.getSystemPermissions();
1823        mAvailableFeatures = systemConfig.getAvailableFeatures();
1824
1825        synchronized (mInstallLock) {
1826        // writer
1827        synchronized (mPackages) {
1828            mHandlerThread = new ServiceThread(TAG,
1829                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1830            mHandlerThread.start();
1831            mHandler = new PackageHandler(mHandlerThread.getLooper());
1832            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1833
1834            File dataDir = Environment.getDataDirectory();
1835            mAppDataDir = new File(dataDir, "data");
1836            mAppInstallDir = new File(dataDir, "app");
1837            mAppLib32InstallDir = new File(dataDir, "app-lib");
1838            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1839            mUserAppDataDir = new File(dataDir, "user");
1840            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1841
1842            sUserManager = new UserManagerService(context, this,
1843                    mInstallLock, mPackages);
1844
1845            // Propagate permission configuration in to package manager.
1846            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1847                    = systemConfig.getPermissions();
1848            for (int i=0; i<permConfig.size(); i++) {
1849                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1850                BasePermission bp = mSettings.mPermissions.get(perm.name);
1851                if (bp == null) {
1852                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1853                    mSettings.mPermissions.put(perm.name, bp);
1854                }
1855                if (perm.gids != null) {
1856                    bp.setGids(perm.gids, perm.perUser);
1857                }
1858            }
1859
1860            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1861            for (int i=0; i<libConfig.size(); i++) {
1862                mSharedLibraries.put(libConfig.keyAt(i),
1863                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1864            }
1865
1866            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1867
1868            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1869                    mSdkVersion, mOnlyCore);
1870
1871            String customResolverActivity = Resources.getSystem().getString(
1872                    R.string.config_customResolverActivity);
1873            if (TextUtils.isEmpty(customResolverActivity)) {
1874                customResolverActivity = null;
1875            } else {
1876                mCustomResolverComponentName = ComponentName.unflattenFromString(
1877                        customResolverActivity);
1878            }
1879
1880            long startTime = SystemClock.uptimeMillis();
1881
1882            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1883                    startTime);
1884
1885            // Set flag to monitor and not change apk file paths when
1886            // scanning install directories.
1887            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1888
1889            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1890
1891            /**
1892             * Add everything in the in the boot class path to the
1893             * list of process files because dexopt will have been run
1894             * if necessary during zygote startup.
1895             */
1896            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1897            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1898
1899            if (bootClassPath != null) {
1900                String[] bootClassPathElements = splitString(bootClassPath, ':');
1901                for (String element : bootClassPathElements) {
1902                    alreadyDexOpted.add(element);
1903                }
1904            } else {
1905                Slog.w(TAG, "No BOOTCLASSPATH found!");
1906            }
1907
1908            if (systemServerClassPath != null) {
1909                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1910                for (String element : systemServerClassPathElements) {
1911                    alreadyDexOpted.add(element);
1912                }
1913            } else {
1914                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1915            }
1916
1917            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1918            final String[] dexCodeInstructionSets =
1919                    getDexCodeInstructionSets(
1920                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1921
1922            /**
1923             * Ensure all external libraries have had dexopt run on them.
1924             */
1925            if (mSharedLibraries.size() > 0) {
1926                // NOTE: For now, we're compiling these system "shared libraries"
1927                // (and framework jars) into all available architectures. It's possible
1928                // to compile them only when we come across an app that uses them (there's
1929                // already logic for that in scanPackageLI) but that adds some complexity.
1930                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1931                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1932                        final String lib = libEntry.path;
1933                        if (lib == null) {
1934                            continue;
1935                        }
1936
1937                        try {
1938                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1939                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1940                                alreadyDexOpted.add(lib);
1941                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1942                            }
1943                        } catch (FileNotFoundException e) {
1944                            Slog.w(TAG, "Library not found: " + lib);
1945                        } catch (IOException e) {
1946                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1947                                    + e.getMessage());
1948                        }
1949                    }
1950                }
1951            }
1952
1953            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1954
1955            // Gross hack for now: we know this file doesn't contain any
1956            // code, so don't dexopt it to avoid the resulting log spew.
1957            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1958
1959            // Gross hack for now: we know this file is only part of
1960            // the boot class path for art, so don't dexopt it to
1961            // avoid the resulting log spew.
1962            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1963
1964            /**
1965             * There are a number of commands implemented in Java, which
1966             * we currently need to do the dexopt on so that they can be
1967             * run from a non-root shell.
1968             */
1969            String[] frameworkFiles = frameworkDir.list();
1970            if (frameworkFiles != null) {
1971                // TODO: We could compile these only for the most preferred ABI. We should
1972                // first double check that the dex files for these commands are not referenced
1973                // by other system apps.
1974                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1975                    for (int i=0; i<frameworkFiles.length; i++) {
1976                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1977                        String path = libPath.getPath();
1978                        // Skip the file if we already did it.
1979                        if (alreadyDexOpted.contains(path)) {
1980                            continue;
1981                        }
1982                        // Skip the file if it is not a type we want to dexopt.
1983                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1984                            continue;
1985                        }
1986                        try {
1987                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1988                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1989                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1990                            }
1991                        } catch (FileNotFoundException e) {
1992                            Slog.w(TAG, "Jar not found: " + path);
1993                        } catch (IOException e) {
1994                            Slog.w(TAG, "Exception reading jar: " + path, e);
1995                        }
1996                    }
1997                }
1998            }
1999
2000            // Collect vendor overlay packages.
2001            // (Do this before scanning any apps.)
2002            // For security and version matching reason, only consider
2003            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2004            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2005            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2006                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2007
2008            // Find base frameworks (resource packages without code).
2009            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2010                    | PackageParser.PARSE_IS_SYSTEM_DIR
2011                    | PackageParser.PARSE_IS_PRIVILEGED,
2012                    scanFlags | SCAN_NO_DEX, 0);
2013
2014            // Collected privileged system packages.
2015            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2016            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2017                    | PackageParser.PARSE_IS_SYSTEM_DIR
2018                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2019
2020            // Collect ordinary system packages.
2021            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2022            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2023                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2024
2025            // Collect all vendor packages.
2026            File vendorAppDir = new File("/vendor/app");
2027            try {
2028                vendorAppDir = vendorAppDir.getCanonicalFile();
2029            } catch (IOException e) {
2030                // failed to look up canonical path, continue with original one
2031            }
2032            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2033                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2034
2035            // Collect all OEM packages.
2036            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2037            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2038                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2039
2040            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2041            mInstaller.moveFiles();
2042
2043            // Prune any system packages that no longer exist.
2044            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2045            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2046            if (!mOnlyCore) {
2047                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2048                while (psit.hasNext()) {
2049                    PackageSetting ps = psit.next();
2050
2051                    /*
2052                     * If this is not a system app, it can't be a
2053                     * disable system app.
2054                     */
2055                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2056                        continue;
2057                    }
2058
2059                    /*
2060                     * If the package is scanned, it's not erased.
2061                     */
2062                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2063                    if (scannedPkg != null) {
2064                        /*
2065                         * If the system app is both scanned and in the
2066                         * disabled packages list, then it must have been
2067                         * added via OTA. Remove it from the currently
2068                         * scanned package so the previously user-installed
2069                         * application can be scanned.
2070                         */
2071                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2072                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2073                                    + ps.name + "; removing system app.  Last known codePath="
2074                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2075                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2076                                    + scannedPkg.mVersionCode);
2077                            removePackageLI(ps, true);
2078                            expectingBetter.put(ps.name, ps.codePath);
2079                        }
2080
2081                        continue;
2082                    }
2083
2084                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2085                        psit.remove();
2086                        logCriticalInfo(Log.WARN, "System package " + ps.name
2087                                + " no longer exists; wiping its data");
2088                        removeDataDirsLI(null, ps.name);
2089                    } else {
2090                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2091                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2092                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2093                        }
2094                    }
2095                }
2096            }
2097
2098            //look for any incomplete package installations
2099            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2100            //clean up list
2101            for(int i = 0; i < deletePkgsList.size(); i++) {
2102                //clean up here
2103                cleanupInstallFailedPackage(deletePkgsList.get(i));
2104            }
2105            //delete tmp files
2106            deleteTempPackageFiles();
2107
2108            // Remove any shared userIDs that have no associated packages
2109            mSettings.pruneSharedUsersLPw();
2110
2111            if (!mOnlyCore) {
2112                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2113                        SystemClock.uptimeMillis());
2114                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2115
2116                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2117                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2118
2119                /**
2120                 * Remove disable package settings for any updated system
2121                 * apps that were removed via an OTA. If they're not a
2122                 * previously-updated app, remove them completely.
2123                 * Otherwise, just revoke their system-level permissions.
2124                 */
2125                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2126                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2127                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2128
2129                    String msg;
2130                    if (deletedPkg == null) {
2131                        msg = "Updated system package " + deletedAppName
2132                                + " no longer exists; wiping its data";
2133                        removeDataDirsLI(null, deletedAppName);
2134                    } else {
2135                        msg = "Updated system app + " + deletedAppName
2136                                + " no longer present; removing system privileges for "
2137                                + deletedAppName;
2138
2139                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2140
2141                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2142                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2143                    }
2144                    logCriticalInfo(Log.WARN, msg);
2145                }
2146
2147                /**
2148                 * Make sure all system apps that we expected to appear on
2149                 * the userdata partition actually showed up. If they never
2150                 * appeared, crawl back and revive the system version.
2151                 */
2152                for (int i = 0; i < expectingBetter.size(); i++) {
2153                    final String packageName = expectingBetter.keyAt(i);
2154                    if (!mPackages.containsKey(packageName)) {
2155                        final File scanFile = expectingBetter.valueAt(i);
2156
2157                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2158                                + " but never showed up; reverting to system");
2159
2160                        final int reparseFlags;
2161                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2162                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2163                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2164                                    | PackageParser.PARSE_IS_PRIVILEGED;
2165                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2166                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2167                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2168                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2169                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2170                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2171                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2172                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2173                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2174                        } else {
2175                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2176                            continue;
2177                        }
2178
2179                        mSettings.enableSystemPackageLPw(packageName);
2180
2181                        try {
2182                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2183                        } catch (PackageManagerException e) {
2184                            Slog.e(TAG, "Failed to parse original system package: "
2185                                    + e.getMessage());
2186                        }
2187                    }
2188                }
2189            }
2190
2191            // Now that we know all of the shared libraries, update all clients to have
2192            // the correct library paths.
2193            updateAllSharedLibrariesLPw();
2194
2195            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2196                // NOTE: We ignore potential failures here during a system scan (like
2197                // the rest of the commands above) because there's precious little we
2198                // can do about it. A settings error is reported, though.
2199                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2200                        false /* force dexopt */, false /* defer dexopt */);
2201            }
2202
2203            // Now that we know all the packages we are keeping,
2204            // read and update their last usage times.
2205            mPackageUsage.readLP();
2206
2207            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2208                    SystemClock.uptimeMillis());
2209            Slog.i(TAG, "Time to scan packages: "
2210                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2211                    + " seconds");
2212
2213            // If the platform SDK has changed since the last time we booted,
2214            // we need to re-grant app permission to catch any new ones that
2215            // appear.  This is really a hack, and means that apps can in some
2216            // cases get permissions that the user didn't initially explicitly
2217            // allow...  it would be nice to have some better way to handle
2218            // this situation.
2219            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2220                    != mSdkVersion;
2221            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2222                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2223                    + "; regranting permissions for internal storage");
2224            mSettings.mInternalSdkPlatform = mSdkVersion;
2225
2226            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2227                    | (regrantPermissions
2228                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2229                            : 0));
2230
2231            // If this is the first boot, and it is a normal boot, then
2232            // we need to initialize the default preferred apps.
2233            if (!mRestoredSettings && !onlyCore) {
2234                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2235                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2236            }
2237
2238            // If this is first boot after an OTA, and a normal boot, then
2239            // we need to clear code cache directories.
2240            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2241            if (mIsUpgrade && !onlyCore) {
2242                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2243                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2244                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2245                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2246                }
2247                mSettings.mFingerprint = Build.FINGERPRINT;
2248            }
2249
2250            primeDomainVerificationsLPw();
2251            checkDefaultBrowser();
2252
2253            // All the changes are done during package scanning.
2254            mSettings.updateInternalDatabaseVersion();
2255
2256            // can downgrade to reader
2257            mSettings.writeLPr();
2258
2259            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2260                    SystemClock.uptimeMillis());
2261
2262            mRequiredVerifierPackage = getRequiredVerifierLPr();
2263
2264            mInstallerService = new PackageInstallerService(context, this);
2265
2266            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2267            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2268                    mIntentFilterVerifierComponent);
2269
2270        } // synchronized (mPackages)
2271        } // synchronized (mInstallLock)
2272
2273        // Now after opening every single application zip, make sure they
2274        // are all flushed.  Not really needed, but keeps things nice and
2275        // tidy.
2276        Runtime.getRuntime().gc();
2277
2278        // Expose private service for system components to use.
2279        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2280    }
2281
2282    @Override
2283    public boolean isFirstBoot() {
2284        return !mRestoredSettings;
2285    }
2286
2287    @Override
2288    public boolean isOnlyCoreApps() {
2289        return mOnlyCore;
2290    }
2291
2292    @Override
2293    public boolean isUpgrade() {
2294        return mIsUpgrade;
2295    }
2296
2297    private String getRequiredVerifierLPr() {
2298        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2299        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2300                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2301
2302        String requiredVerifier = null;
2303
2304        final int N = receivers.size();
2305        for (int i = 0; i < N; i++) {
2306            final ResolveInfo info = receivers.get(i);
2307
2308            if (info.activityInfo == null) {
2309                continue;
2310            }
2311
2312            final String packageName = info.activityInfo.packageName;
2313
2314            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2315                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2316                continue;
2317            }
2318
2319            if (requiredVerifier != null) {
2320                throw new RuntimeException("There can be only one required verifier");
2321            }
2322
2323            requiredVerifier = packageName;
2324        }
2325
2326        return requiredVerifier;
2327    }
2328
2329    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2330        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2331        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2332                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2333
2334        ComponentName verifierComponentName = null;
2335
2336        int priority = -1000;
2337        final int N = receivers.size();
2338        for (int i = 0; i < N; i++) {
2339            final ResolveInfo info = receivers.get(i);
2340
2341            if (info.activityInfo == null) {
2342                continue;
2343            }
2344
2345            final String packageName = info.activityInfo.packageName;
2346
2347            final PackageSetting ps = mSettings.mPackages.get(packageName);
2348            if (ps == null) {
2349                continue;
2350            }
2351
2352            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2353                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2354                continue;
2355            }
2356
2357            // Select the IntentFilterVerifier with the highest priority
2358            if (priority < info.priority) {
2359                priority = info.priority;
2360                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2361                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2362                        + verifierComponentName + " with priority: " + info.priority);
2363            }
2364        }
2365
2366        return verifierComponentName;
2367    }
2368
2369    private void primeDomainVerificationsLPw() {
2370        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2371        boolean updated = false;
2372        ArraySet<String> allHostsSet = new ArraySet<>();
2373        for (PackageParser.Package pkg : mPackages.values()) {
2374            final String packageName = pkg.packageName;
2375            if (!hasDomainURLs(pkg)) {
2376                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2377                            "package with no domain URLs: " + packageName);
2378                continue;
2379            }
2380            if (!pkg.isSystemApp()) {
2381                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2382                        "No priming domain verifications for a non system package : " +
2383                                packageName);
2384                continue;
2385            }
2386            for (PackageParser.Activity a : pkg.activities) {
2387                for (ActivityIntentInfo filter : a.intents) {
2388                    if (hasValidDomains(filter)) {
2389                        allHostsSet.addAll(filter.getHostsList());
2390                    }
2391                }
2392            }
2393            if (allHostsSet.size() == 0) {
2394                allHostsSet.add("*");
2395            }
2396            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2397            IntentFilterVerificationInfo ivi =
2398                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2399            if (ivi != null) {
2400                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2401                        "Priming domain verifications for package: " + packageName +
2402                        " with hosts:" + ivi.getDomainsString());
2403                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2404                updated = true;
2405            }
2406            else {
2407                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2408                        "No priming domain verifications for package: " + packageName);
2409            }
2410            allHostsSet.clear();
2411        }
2412        if (updated) {
2413            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2414                    "Will need to write primed domain verifications");
2415        }
2416        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2417    }
2418
2419    private void applyFactoryDefaultBrowserLPw(int userId) {
2420        // The default browser app's package name is stored in a string resource,
2421        // with a product-specific overlay used for vendor customization.
2422        String browserPkg = mContext.getResources().getString(
2423                com.android.internal.R.string.default_browser);
2424        if (browserPkg != null) {
2425            // non-empty string => required to be a known package
2426            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2427            if (ps == null) {
2428                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2429                browserPkg = null;
2430            } else {
2431                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2432            }
2433        }
2434
2435        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2436        // default.  If there's more than one, just leave everything alone.
2437        if (browserPkg == null) {
2438            calculateDefaultBrowserLPw(userId);
2439        }
2440    }
2441
2442    private void calculateDefaultBrowserLPw(int userId) {
2443        List<String> allBrowsers = resolveAllBrowserApps(userId);
2444        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2445        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2446    }
2447
2448    private List<String> resolveAllBrowserApps(int userId) {
2449        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2450        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2451                PackageManager.MATCH_ALL, userId);
2452
2453        final int count = list.size();
2454        List<String> result = new ArrayList<String>(count);
2455        for (int i=0; i<count; i++) {
2456            ResolveInfo info = list.get(i);
2457            if (info.activityInfo == null
2458                    || !info.handleAllWebDataURI
2459                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2460                    || result.contains(info.activityInfo.packageName)) {
2461                continue;
2462            }
2463            result.add(info.activityInfo.packageName);
2464        }
2465
2466        return result;
2467    }
2468
2469    private boolean packageIsBrowser(String packageName, int userId) {
2470        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2471                PackageManager.MATCH_ALL, userId);
2472        final int N = list.size();
2473        for (int i = 0; i < N; i++) {
2474            ResolveInfo info = list.get(i);
2475            if (packageName.equals(info.activityInfo.packageName)) {
2476                return true;
2477            }
2478        }
2479        return false;
2480    }
2481
2482    private void checkDefaultBrowser() {
2483        final int myUserId = UserHandle.myUserId();
2484        final String packageName = getDefaultBrowserPackageName(myUserId);
2485        if (packageName != null) {
2486            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2487            if (info == null) {
2488                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2489                synchronized (mPackages) {
2490                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2491                }
2492            }
2493        }
2494    }
2495
2496    @Override
2497    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2498            throws RemoteException {
2499        try {
2500            return super.onTransact(code, data, reply, flags);
2501        } catch (RuntimeException e) {
2502            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2503                Slog.wtf(TAG, "Package Manager Crash", e);
2504            }
2505            throw e;
2506        }
2507    }
2508
2509    void cleanupInstallFailedPackage(PackageSetting ps) {
2510        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2511
2512        removeDataDirsLI(ps.volumeUuid, ps.name);
2513        if (ps.codePath != null) {
2514            if (ps.codePath.isDirectory()) {
2515                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2516            } else {
2517                ps.codePath.delete();
2518            }
2519        }
2520        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2521            if (ps.resourcePath.isDirectory()) {
2522                FileUtils.deleteContents(ps.resourcePath);
2523            }
2524            ps.resourcePath.delete();
2525        }
2526        mSettings.removePackageLPw(ps.name);
2527    }
2528
2529    static int[] appendInts(int[] cur, int[] add) {
2530        if (add == null) return cur;
2531        if (cur == null) return add;
2532        final int N = add.length;
2533        for (int i=0; i<N; i++) {
2534            cur = appendInt(cur, add[i]);
2535        }
2536        return cur;
2537    }
2538
2539    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2540        if (!sUserManager.exists(userId)) return null;
2541        final PackageSetting ps = (PackageSetting) p.mExtras;
2542        if (ps == null) {
2543            return null;
2544        }
2545
2546        final PermissionsState permissionsState = ps.getPermissionsState();
2547
2548        final int[] gids = permissionsState.computeGids(userId);
2549        final Set<String> permissions = permissionsState.getPermissions(userId);
2550        final PackageUserState state = ps.readUserState(userId);
2551
2552        return PackageParser.generatePackageInfo(p, gids, flags,
2553                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2554    }
2555
2556    @Override
2557    public boolean isPackageFrozen(String packageName) {
2558        synchronized (mPackages) {
2559            final PackageSetting ps = mSettings.mPackages.get(packageName);
2560            if (ps != null) {
2561                return ps.frozen;
2562            }
2563        }
2564        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2565        return true;
2566    }
2567
2568    @Override
2569    public boolean isPackageAvailable(String packageName, int userId) {
2570        if (!sUserManager.exists(userId)) return false;
2571        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2572        synchronized (mPackages) {
2573            PackageParser.Package p = mPackages.get(packageName);
2574            if (p != null) {
2575                final PackageSetting ps = (PackageSetting) p.mExtras;
2576                if (ps != null) {
2577                    final PackageUserState state = ps.readUserState(userId);
2578                    if (state != null) {
2579                        return PackageParser.isAvailable(state);
2580                    }
2581                }
2582            }
2583        }
2584        return false;
2585    }
2586
2587    @Override
2588    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2589        if (!sUserManager.exists(userId)) return null;
2590        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2591        // reader
2592        synchronized (mPackages) {
2593            PackageParser.Package p = mPackages.get(packageName);
2594            if (DEBUG_PACKAGE_INFO)
2595                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2596            if (p != null) {
2597                return generatePackageInfo(p, flags, userId);
2598            }
2599            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2600                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2601            }
2602        }
2603        return null;
2604    }
2605
2606    @Override
2607    public String[] currentToCanonicalPackageNames(String[] names) {
2608        String[] out = new String[names.length];
2609        // reader
2610        synchronized (mPackages) {
2611            for (int i=names.length-1; i>=0; i--) {
2612                PackageSetting ps = mSettings.mPackages.get(names[i]);
2613                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2614            }
2615        }
2616        return out;
2617    }
2618
2619    @Override
2620    public String[] canonicalToCurrentPackageNames(String[] names) {
2621        String[] out = new String[names.length];
2622        // reader
2623        synchronized (mPackages) {
2624            for (int i=names.length-1; i>=0; i--) {
2625                String cur = mSettings.mRenamedPackages.get(names[i]);
2626                out[i] = cur != null ? cur : names[i];
2627            }
2628        }
2629        return out;
2630    }
2631
2632    @Override
2633    public int getPackageUid(String packageName, int userId) {
2634        if (!sUserManager.exists(userId)) return -1;
2635        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2636
2637        // reader
2638        synchronized (mPackages) {
2639            PackageParser.Package p = mPackages.get(packageName);
2640            if(p != null) {
2641                return UserHandle.getUid(userId, p.applicationInfo.uid);
2642            }
2643            PackageSetting ps = mSettings.mPackages.get(packageName);
2644            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2645                return -1;
2646            }
2647            p = ps.pkg;
2648            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2649        }
2650    }
2651
2652    @Override
2653    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2654        if (!sUserManager.exists(userId)) {
2655            return null;
2656        }
2657
2658        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2659                "getPackageGids");
2660
2661        // reader
2662        synchronized (mPackages) {
2663            PackageParser.Package p = mPackages.get(packageName);
2664            if (DEBUG_PACKAGE_INFO) {
2665                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2666            }
2667            if (p != null) {
2668                PackageSetting ps = (PackageSetting) p.mExtras;
2669                return ps.getPermissionsState().computeGids(userId);
2670            }
2671        }
2672
2673        return null;
2674    }
2675
2676    @Override
2677    public int getMountExternalMode(int uid) {
2678        if (Process.isIsolated(uid)) {
2679            return Zygote.MOUNT_EXTERNAL_NONE;
2680        } else {
2681            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2682                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2683            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2684                return Zygote.MOUNT_EXTERNAL_WRITE;
2685            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2686                return Zygote.MOUNT_EXTERNAL_READ;
2687            } else {
2688                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2689            }
2690        }
2691    }
2692
2693    static PermissionInfo generatePermissionInfo(
2694            BasePermission bp, int flags) {
2695        if (bp.perm != null) {
2696            return PackageParser.generatePermissionInfo(bp.perm, flags);
2697        }
2698        PermissionInfo pi = new PermissionInfo();
2699        pi.name = bp.name;
2700        pi.packageName = bp.sourcePackage;
2701        pi.nonLocalizedLabel = bp.name;
2702        pi.protectionLevel = bp.protectionLevel;
2703        return pi;
2704    }
2705
2706    @Override
2707    public PermissionInfo getPermissionInfo(String name, int flags) {
2708        // reader
2709        synchronized (mPackages) {
2710            final BasePermission p = mSettings.mPermissions.get(name);
2711            if (p != null) {
2712                return generatePermissionInfo(p, flags);
2713            }
2714            return null;
2715        }
2716    }
2717
2718    @Override
2719    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2720        // reader
2721        synchronized (mPackages) {
2722            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2723            for (BasePermission p : mSettings.mPermissions.values()) {
2724                if (group == null) {
2725                    if (p.perm == null || p.perm.info.group == null) {
2726                        out.add(generatePermissionInfo(p, flags));
2727                    }
2728                } else {
2729                    if (p.perm != null && group.equals(p.perm.info.group)) {
2730                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2731                    }
2732                }
2733            }
2734
2735            if (out.size() > 0) {
2736                return out;
2737            }
2738            return mPermissionGroups.containsKey(group) ? out : null;
2739        }
2740    }
2741
2742    @Override
2743    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2744        // reader
2745        synchronized (mPackages) {
2746            return PackageParser.generatePermissionGroupInfo(
2747                    mPermissionGroups.get(name), flags);
2748        }
2749    }
2750
2751    @Override
2752    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2753        // reader
2754        synchronized (mPackages) {
2755            final int N = mPermissionGroups.size();
2756            ArrayList<PermissionGroupInfo> out
2757                    = new ArrayList<PermissionGroupInfo>(N);
2758            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2759                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2760            }
2761            return out;
2762        }
2763    }
2764
2765    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2766            int userId) {
2767        if (!sUserManager.exists(userId)) return null;
2768        PackageSetting ps = mSettings.mPackages.get(packageName);
2769        if (ps != null) {
2770            if (ps.pkg == null) {
2771                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2772                        flags, userId);
2773                if (pInfo != null) {
2774                    return pInfo.applicationInfo;
2775                }
2776                return null;
2777            }
2778            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2779                    ps.readUserState(userId), userId);
2780        }
2781        return null;
2782    }
2783
2784    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2785            int userId) {
2786        if (!sUserManager.exists(userId)) return null;
2787        PackageSetting ps = mSettings.mPackages.get(packageName);
2788        if (ps != null) {
2789            PackageParser.Package pkg = ps.pkg;
2790            if (pkg == null) {
2791                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2792                    return null;
2793                }
2794                // Only data remains, so we aren't worried about code paths
2795                pkg = new PackageParser.Package(packageName);
2796                pkg.applicationInfo.packageName = packageName;
2797                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2798                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2799                pkg.applicationInfo.dataDir = Environment
2800                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2801                        .getAbsolutePath();
2802                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2803                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2804            }
2805            return generatePackageInfo(pkg, flags, userId);
2806        }
2807        return null;
2808    }
2809
2810    @Override
2811    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2812        if (!sUserManager.exists(userId)) return null;
2813        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2814        // writer
2815        synchronized (mPackages) {
2816            PackageParser.Package p = mPackages.get(packageName);
2817            if (DEBUG_PACKAGE_INFO) Log.v(
2818                    TAG, "getApplicationInfo " + packageName
2819                    + ": " + p);
2820            if (p != null) {
2821                PackageSetting ps = mSettings.mPackages.get(packageName);
2822                if (ps == null) return null;
2823                // Note: isEnabledLP() does not apply here - always return info
2824                return PackageParser.generateApplicationInfo(
2825                        p, flags, ps.readUserState(userId), userId);
2826            }
2827            if ("android".equals(packageName)||"system".equals(packageName)) {
2828                return mAndroidApplication;
2829            }
2830            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2831                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2832            }
2833        }
2834        return null;
2835    }
2836
2837    @Override
2838    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2839            final IPackageDataObserver observer) {
2840        mContext.enforceCallingOrSelfPermission(
2841                android.Manifest.permission.CLEAR_APP_CACHE, null);
2842        // Queue up an async operation since clearing cache may take a little while.
2843        mHandler.post(new Runnable() {
2844            public void run() {
2845                mHandler.removeCallbacks(this);
2846                int retCode = -1;
2847                synchronized (mInstallLock) {
2848                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2849                    if (retCode < 0) {
2850                        Slog.w(TAG, "Couldn't clear application caches");
2851                    }
2852                }
2853                if (observer != null) {
2854                    try {
2855                        observer.onRemoveCompleted(null, (retCode >= 0));
2856                    } catch (RemoteException e) {
2857                        Slog.w(TAG, "RemoveException when invoking call back");
2858                    }
2859                }
2860            }
2861        });
2862    }
2863
2864    @Override
2865    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2866            final IntentSender pi) {
2867        mContext.enforceCallingOrSelfPermission(
2868                android.Manifest.permission.CLEAR_APP_CACHE, null);
2869        // Queue up an async operation since clearing cache may take a little while.
2870        mHandler.post(new Runnable() {
2871            public void run() {
2872                mHandler.removeCallbacks(this);
2873                int retCode = -1;
2874                synchronized (mInstallLock) {
2875                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2876                    if (retCode < 0) {
2877                        Slog.w(TAG, "Couldn't clear application caches");
2878                    }
2879                }
2880                if(pi != null) {
2881                    try {
2882                        // Callback via pending intent
2883                        int code = (retCode >= 0) ? 1 : 0;
2884                        pi.sendIntent(null, code, null,
2885                                null, null);
2886                    } catch (SendIntentException e1) {
2887                        Slog.i(TAG, "Failed to send pending intent");
2888                    }
2889                }
2890            }
2891        });
2892    }
2893
2894    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2895        synchronized (mInstallLock) {
2896            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2897                throw new IOException("Failed to free enough space");
2898            }
2899        }
2900    }
2901
2902    @Override
2903    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2904        if (!sUserManager.exists(userId)) return null;
2905        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2906        synchronized (mPackages) {
2907            PackageParser.Activity a = mActivities.mActivities.get(component);
2908
2909            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2910            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2911                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2912                if (ps == null) return null;
2913                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2914                        userId);
2915            }
2916            if (mResolveComponentName.equals(component)) {
2917                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2918                        new PackageUserState(), userId);
2919            }
2920        }
2921        return null;
2922    }
2923
2924    @Override
2925    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2926            String resolvedType) {
2927        synchronized (mPackages) {
2928            PackageParser.Activity a = mActivities.mActivities.get(component);
2929            if (a == null) {
2930                return false;
2931            }
2932            for (int i=0; i<a.intents.size(); i++) {
2933                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2934                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2935                    return true;
2936                }
2937            }
2938            return false;
2939        }
2940    }
2941
2942    @Override
2943    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2944        if (!sUserManager.exists(userId)) return null;
2945        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2946        synchronized (mPackages) {
2947            PackageParser.Activity a = mReceivers.mActivities.get(component);
2948            if (DEBUG_PACKAGE_INFO) Log.v(
2949                TAG, "getReceiverInfo " + component + ": " + a);
2950            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2951                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2952                if (ps == null) return null;
2953                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2954                        userId);
2955            }
2956        }
2957        return null;
2958    }
2959
2960    @Override
2961    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2962        if (!sUserManager.exists(userId)) return null;
2963        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2964        synchronized (mPackages) {
2965            PackageParser.Service s = mServices.mServices.get(component);
2966            if (DEBUG_PACKAGE_INFO) Log.v(
2967                TAG, "getServiceInfo " + component + ": " + s);
2968            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2969                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2970                if (ps == null) return null;
2971                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2972                        userId);
2973            }
2974        }
2975        return null;
2976    }
2977
2978    @Override
2979    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2980        if (!sUserManager.exists(userId)) return null;
2981        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2982        synchronized (mPackages) {
2983            PackageParser.Provider p = mProviders.mProviders.get(component);
2984            if (DEBUG_PACKAGE_INFO) Log.v(
2985                TAG, "getProviderInfo " + component + ": " + p);
2986            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2987                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2988                if (ps == null) return null;
2989                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2990                        userId);
2991            }
2992        }
2993        return null;
2994    }
2995
2996    @Override
2997    public String[] getSystemSharedLibraryNames() {
2998        Set<String> libSet;
2999        synchronized (mPackages) {
3000            libSet = mSharedLibraries.keySet();
3001            int size = libSet.size();
3002            if (size > 0) {
3003                String[] libs = new String[size];
3004                libSet.toArray(libs);
3005                return libs;
3006            }
3007        }
3008        return null;
3009    }
3010
3011    /**
3012     * @hide
3013     */
3014    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3015        synchronized (mPackages) {
3016            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3017            if (lib != null && lib.apk != null) {
3018                return mPackages.get(lib.apk);
3019            }
3020        }
3021        return null;
3022    }
3023
3024    @Override
3025    public FeatureInfo[] getSystemAvailableFeatures() {
3026        Collection<FeatureInfo> featSet;
3027        synchronized (mPackages) {
3028            featSet = mAvailableFeatures.values();
3029            int size = featSet.size();
3030            if (size > 0) {
3031                FeatureInfo[] features = new FeatureInfo[size+1];
3032                featSet.toArray(features);
3033                FeatureInfo fi = new FeatureInfo();
3034                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3035                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3036                features[size] = fi;
3037                return features;
3038            }
3039        }
3040        return null;
3041    }
3042
3043    @Override
3044    public boolean hasSystemFeature(String name) {
3045        synchronized (mPackages) {
3046            return mAvailableFeatures.containsKey(name);
3047        }
3048    }
3049
3050    private void checkValidCaller(int uid, int userId) {
3051        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3052            return;
3053
3054        throw new SecurityException("Caller uid=" + uid
3055                + " is not privileged to communicate with user=" + userId);
3056    }
3057
3058    @Override
3059    public int checkPermission(String permName, String pkgName, int userId) {
3060        if (!sUserManager.exists(userId)) {
3061            return PackageManager.PERMISSION_DENIED;
3062        }
3063
3064        synchronized (mPackages) {
3065            final PackageParser.Package p = mPackages.get(pkgName);
3066            if (p != null && p.mExtras != null) {
3067                final PackageSetting ps = (PackageSetting) p.mExtras;
3068                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3069                    return PackageManager.PERMISSION_GRANTED;
3070                }
3071            }
3072        }
3073
3074        return PackageManager.PERMISSION_DENIED;
3075    }
3076
3077    @Override
3078    public int checkUidPermission(String permName, int uid) {
3079        final int userId = UserHandle.getUserId(uid);
3080
3081        if (!sUserManager.exists(userId)) {
3082            return PackageManager.PERMISSION_DENIED;
3083        }
3084
3085        synchronized (mPackages) {
3086            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3087            if (obj != null) {
3088                final SettingBase ps = (SettingBase) obj;
3089                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3090                    return PackageManager.PERMISSION_GRANTED;
3091                }
3092            } else {
3093                ArraySet<String> perms = mSystemPermissions.get(uid);
3094                if (perms != null && perms.contains(permName)) {
3095                    return PackageManager.PERMISSION_GRANTED;
3096                }
3097            }
3098        }
3099
3100        return PackageManager.PERMISSION_DENIED;
3101    }
3102
3103    /**
3104     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3105     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3106     * @param checkShell TODO(yamasani):
3107     * @param message the message to log on security exception
3108     */
3109    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3110            boolean checkShell, String message) {
3111        if (userId < 0) {
3112            throw new IllegalArgumentException("Invalid userId " + userId);
3113        }
3114        if (checkShell) {
3115            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3116        }
3117        if (userId == UserHandle.getUserId(callingUid)) return;
3118        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3119            if (requireFullPermission) {
3120                mContext.enforceCallingOrSelfPermission(
3121                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3122            } else {
3123                try {
3124                    mContext.enforceCallingOrSelfPermission(
3125                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3126                } catch (SecurityException se) {
3127                    mContext.enforceCallingOrSelfPermission(
3128                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3129                }
3130            }
3131        }
3132    }
3133
3134    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3135        if (callingUid == Process.SHELL_UID) {
3136            if (userHandle >= 0
3137                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3138                throw new SecurityException("Shell does not have permission to access user "
3139                        + userHandle);
3140            } else if (userHandle < 0) {
3141                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3142                        + Debug.getCallers(3));
3143            }
3144        }
3145    }
3146
3147    private BasePermission findPermissionTreeLP(String permName) {
3148        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3149            if (permName.startsWith(bp.name) &&
3150                    permName.length() > bp.name.length() &&
3151                    permName.charAt(bp.name.length()) == '.') {
3152                return bp;
3153            }
3154        }
3155        return null;
3156    }
3157
3158    private BasePermission checkPermissionTreeLP(String permName) {
3159        if (permName != null) {
3160            BasePermission bp = findPermissionTreeLP(permName);
3161            if (bp != null) {
3162                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3163                    return bp;
3164                }
3165                throw new SecurityException("Calling uid "
3166                        + Binder.getCallingUid()
3167                        + " is not allowed to add to permission tree "
3168                        + bp.name + " owned by uid " + bp.uid);
3169            }
3170        }
3171        throw new SecurityException("No permission tree found for " + permName);
3172    }
3173
3174    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3175        if (s1 == null) {
3176            return s2 == null;
3177        }
3178        if (s2 == null) {
3179            return false;
3180        }
3181        if (s1.getClass() != s2.getClass()) {
3182            return false;
3183        }
3184        return s1.equals(s2);
3185    }
3186
3187    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3188        if (pi1.icon != pi2.icon) return false;
3189        if (pi1.logo != pi2.logo) return false;
3190        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3191        if (!compareStrings(pi1.name, pi2.name)) return false;
3192        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3193        // We'll take care of setting this one.
3194        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3195        // These are not currently stored in settings.
3196        //if (!compareStrings(pi1.group, pi2.group)) return false;
3197        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3198        //if (pi1.labelRes != pi2.labelRes) return false;
3199        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3200        return true;
3201    }
3202
3203    int permissionInfoFootprint(PermissionInfo info) {
3204        int size = info.name.length();
3205        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3206        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3207        return size;
3208    }
3209
3210    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3211        int size = 0;
3212        for (BasePermission perm : mSettings.mPermissions.values()) {
3213            if (perm.uid == tree.uid) {
3214                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3215            }
3216        }
3217        return size;
3218    }
3219
3220    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3221        // We calculate the max size of permissions defined by this uid and throw
3222        // if that plus the size of 'info' would exceed our stated maximum.
3223        if (tree.uid != Process.SYSTEM_UID) {
3224            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3225            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3226                throw new SecurityException("Permission tree size cap exceeded");
3227            }
3228        }
3229    }
3230
3231    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3232        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3233            throw new SecurityException("Label must be specified in permission");
3234        }
3235        BasePermission tree = checkPermissionTreeLP(info.name);
3236        BasePermission bp = mSettings.mPermissions.get(info.name);
3237        boolean added = bp == null;
3238        boolean changed = true;
3239        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3240        if (added) {
3241            enforcePermissionCapLocked(info, tree);
3242            bp = new BasePermission(info.name, tree.sourcePackage,
3243                    BasePermission.TYPE_DYNAMIC);
3244        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3245            throw new SecurityException(
3246                    "Not allowed to modify non-dynamic permission "
3247                    + info.name);
3248        } else {
3249            if (bp.protectionLevel == fixedLevel
3250                    && bp.perm.owner.equals(tree.perm.owner)
3251                    && bp.uid == tree.uid
3252                    && comparePermissionInfos(bp.perm.info, info)) {
3253                changed = false;
3254            }
3255        }
3256        bp.protectionLevel = fixedLevel;
3257        info = new PermissionInfo(info);
3258        info.protectionLevel = fixedLevel;
3259        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3260        bp.perm.info.packageName = tree.perm.info.packageName;
3261        bp.uid = tree.uid;
3262        if (added) {
3263            mSettings.mPermissions.put(info.name, bp);
3264        }
3265        if (changed) {
3266            if (!async) {
3267                mSettings.writeLPr();
3268            } else {
3269                scheduleWriteSettingsLocked();
3270            }
3271        }
3272        return added;
3273    }
3274
3275    @Override
3276    public boolean addPermission(PermissionInfo info) {
3277        synchronized (mPackages) {
3278            return addPermissionLocked(info, false);
3279        }
3280    }
3281
3282    @Override
3283    public boolean addPermissionAsync(PermissionInfo info) {
3284        synchronized (mPackages) {
3285            return addPermissionLocked(info, true);
3286        }
3287    }
3288
3289    @Override
3290    public void removePermission(String name) {
3291        synchronized (mPackages) {
3292            checkPermissionTreeLP(name);
3293            BasePermission bp = mSettings.mPermissions.get(name);
3294            if (bp != null) {
3295                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3296                    throw new SecurityException(
3297                            "Not allowed to modify non-dynamic permission "
3298                            + name);
3299                }
3300                mSettings.mPermissions.remove(name);
3301                mSettings.writeLPr();
3302            }
3303        }
3304    }
3305
3306    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3307            BasePermission bp) {
3308        int index = pkg.requestedPermissions.indexOf(bp.name);
3309        if (index == -1) {
3310            throw new SecurityException("Package " + pkg.packageName
3311                    + " has not requested permission " + bp.name);
3312        }
3313        if (!bp.isRuntime()) {
3314            throw new SecurityException("Permission " + bp.name
3315                    + " is not a changeable permission type");
3316        }
3317    }
3318
3319    @Override
3320    public void grantRuntimePermission(String packageName, String name, final int userId) {
3321        if (!sUserManager.exists(userId)) {
3322            Log.e(TAG, "No such user:" + userId);
3323            return;
3324        }
3325
3326        mContext.enforceCallingOrSelfPermission(
3327                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3328                "grantRuntimePermission");
3329
3330        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3331                "grantRuntimePermission");
3332
3333        final int uid;
3334        final SettingBase sb;
3335
3336        synchronized (mPackages) {
3337            final PackageParser.Package pkg = mPackages.get(packageName);
3338            if (pkg == null) {
3339                throw new IllegalArgumentException("Unknown package: " + packageName);
3340            }
3341
3342            final BasePermission bp = mSettings.mPermissions.get(name);
3343            if (bp == null) {
3344                throw new IllegalArgumentException("Unknown permission: " + name);
3345            }
3346
3347            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3348
3349            uid = pkg.applicationInfo.uid;
3350            sb = (SettingBase) pkg.mExtras;
3351            if (sb == null) {
3352                throw new IllegalArgumentException("Unknown package: " + packageName);
3353            }
3354
3355            final PermissionsState permissionsState = sb.getPermissionsState();
3356
3357            final int flags = permissionsState.getPermissionFlags(name, userId);
3358            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3359                throw new SecurityException("Cannot grant system fixed permission: "
3360                        + name + " for package: " + packageName);
3361            }
3362
3363            final int result = permissionsState.grantRuntimePermission(bp, userId);
3364            switch (result) {
3365                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3366                    return;
3367                }
3368
3369                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3370                    mHandler.post(new Runnable() {
3371                        @Override
3372                        public void run() {
3373                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3374                        }
3375                    });
3376                } break;
3377            }
3378
3379            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3380
3381            // Not critical if that is lost - app has to request again.
3382            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3383        }
3384
3385        if (READ_EXTERNAL_STORAGE.equals(name)
3386                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3387            final long token = Binder.clearCallingIdentity();
3388            try {
3389                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3390                storage.remountUid(uid);
3391            } finally {
3392                Binder.restoreCallingIdentity(token);
3393            }
3394        }
3395    }
3396
3397    @Override
3398    public void revokeRuntimePermission(String packageName, String name, int userId) {
3399        if (!sUserManager.exists(userId)) {
3400            Log.e(TAG, "No such user:" + userId);
3401            return;
3402        }
3403
3404        mContext.enforceCallingOrSelfPermission(
3405                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3406                "revokeRuntimePermission");
3407
3408        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3409                "revokeRuntimePermission");
3410
3411        final SettingBase sb;
3412
3413        synchronized (mPackages) {
3414            final PackageParser.Package pkg = mPackages.get(packageName);
3415            if (pkg == null) {
3416                throw new IllegalArgumentException("Unknown package: " + packageName);
3417            }
3418
3419            final BasePermission bp = mSettings.mPermissions.get(name);
3420            if (bp == null) {
3421                throw new IllegalArgumentException("Unknown permission: " + name);
3422            }
3423
3424            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3425
3426            sb = (SettingBase) pkg.mExtras;
3427            if (sb == null) {
3428                throw new IllegalArgumentException("Unknown package: " + packageName);
3429            }
3430
3431            final PermissionsState permissionsState = sb.getPermissionsState();
3432
3433            final int flags = permissionsState.getPermissionFlags(name, userId);
3434            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3435                throw new SecurityException("Cannot revoke system fixed permission: "
3436                        + name + " for package: " + packageName);
3437            }
3438
3439            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3440                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3441                return;
3442            }
3443
3444            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3445
3446            // Critical, after this call app should never have the permission.
3447            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3448        }
3449
3450        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3451    }
3452
3453    @Override
3454    public void resetRuntimePermissions() {
3455        mContext.enforceCallingOrSelfPermission(
3456                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3457                "revokeRuntimePermission");
3458
3459        int callingUid = Binder.getCallingUid();
3460        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3461            mContext.enforceCallingOrSelfPermission(
3462                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3463                    "resetRuntimePermissions");
3464        }
3465
3466        final int[] userIds;
3467
3468        synchronized (mPackages) {
3469            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3470            final int userCount = UserManagerService.getInstance().getUserIds().length;
3471            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3472        }
3473
3474        for (int userId : userIds) {
3475            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3476        }
3477    }
3478
3479    @Override
3480    public int getPermissionFlags(String name, String packageName, int userId) {
3481        if (!sUserManager.exists(userId)) {
3482            return 0;
3483        }
3484
3485        mContext.enforceCallingOrSelfPermission(
3486                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3487                "getPermissionFlags");
3488
3489        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3490                "getPermissionFlags");
3491
3492        synchronized (mPackages) {
3493            final PackageParser.Package pkg = mPackages.get(packageName);
3494            if (pkg == null) {
3495                throw new IllegalArgumentException("Unknown package: " + packageName);
3496            }
3497
3498            final BasePermission bp = mSettings.mPermissions.get(name);
3499            if (bp == null) {
3500                throw new IllegalArgumentException("Unknown permission: " + name);
3501            }
3502
3503            SettingBase sb = (SettingBase) pkg.mExtras;
3504            if (sb == null) {
3505                throw new IllegalArgumentException("Unknown package: " + packageName);
3506            }
3507
3508            PermissionsState permissionsState = sb.getPermissionsState();
3509            return permissionsState.getPermissionFlags(name, userId);
3510        }
3511    }
3512
3513    @Override
3514    public void updatePermissionFlags(String name, String packageName, int flagMask,
3515            int flagValues, int userId) {
3516        if (!sUserManager.exists(userId)) {
3517            return;
3518        }
3519
3520        mContext.enforceCallingOrSelfPermission(
3521                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3522                "updatePermissionFlags");
3523
3524        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3525                "updatePermissionFlags");
3526
3527        // Only the system can change system fixed flags.
3528        if (getCallingUid() != Process.SYSTEM_UID) {
3529            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3530            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3531        }
3532
3533        synchronized (mPackages) {
3534            final PackageParser.Package pkg = mPackages.get(packageName);
3535            if (pkg == null) {
3536                throw new IllegalArgumentException("Unknown package: " + packageName);
3537            }
3538
3539            final BasePermission bp = mSettings.mPermissions.get(name);
3540            if (bp == null) {
3541                throw new IllegalArgumentException("Unknown permission: " + name);
3542            }
3543
3544            SettingBase sb = (SettingBase) pkg.mExtras;
3545            if (sb == null) {
3546                throw new IllegalArgumentException("Unknown package: " + packageName);
3547            }
3548
3549            PermissionsState permissionsState = sb.getPermissionsState();
3550
3551            // Only the package manager can change flags for system component permissions.
3552            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3553            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3554                return;
3555            }
3556
3557            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3558
3559            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3560                // Install and runtime permissions are stored in different places,
3561                // so figure out what permission changed and persist the change.
3562                if (permissionsState.getInstallPermissionState(name) != null) {
3563                    scheduleWriteSettingsLocked();
3564                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3565                        || hadState) {
3566                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3567                }
3568            }
3569        }
3570    }
3571
3572    /**
3573     * Update the permission flags for all packages and runtime permissions of a user in order
3574     * to allow device or profile owner to remove POLICY_FIXED.
3575     */
3576    @Override
3577    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3578        if (!sUserManager.exists(userId)) {
3579            return;
3580        }
3581
3582        mContext.enforceCallingOrSelfPermission(
3583                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3584                "updatePermissionFlagsForAllApps");
3585
3586        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3587                "updatePermissionFlagsForAllApps");
3588
3589        // Only the system can change system fixed flags.
3590        if (getCallingUid() != Process.SYSTEM_UID) {
3591            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3592            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3593        }
3594
3595        synchronized (mPackages) {
3596            boolean changed = false;
3597            final int packageCount = mPackages.size();
3598            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3599                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3600                SettingBase sb = (SettingBase) pkg.mExtras;
3601                if (sb == null) {
3602                    continue;
3603                }
3604                PermissionsState permissionsState = sb.getPermissionsState();
3605                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3606                        userId, flagMask, flagValues);
3607            }
3608            if (changed) {
3609                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3610            }
3611        }
3612    }
3613
3614    @Override
3615    public boolean shouldShowRequestPermissionRationale(String permissionName,
3616            String packageName, int userId) {
3617        if (UserHandle.getCallingUserId() != userId) {
3618            mContext.enforceCallingPermission(
3619                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3620                    "canShowRequestPermissionRationale for user " + userId);
3621        }
3622
3623        final int uid = getPackageUid(packageName, userId);
3624        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3625            return false;
3626        }
3627
3628        if (checkPermission(permissionName, packageName, userId)
3629                == PackageManager.PERMISSION_GRANTED) {
3630            return false;
3631        }
3632
3633        final int flags;
3634
3635        final long identity = Binder.clearCallingIdentity();
3636        try {
3637            flags = getPermissionFlags(permissionName,
3638                    packageName, userId);
3639        } finally {
3640            Binder.restoreCallingIdentity(identity);
3641        }
3642
3643        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3644                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3645                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3646
3647        if ((flags & fixedFlags) != 0) {
3648            return false;
3649        }
3650
3651        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3652    }
3653
3654    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3655        BasePermission bp = mSettings.mPermissions.get(permission);
3656        if (bp == null) {
3657            throw new SecurityException("Missing " + permission + " permission");
3658        }
3659
3660        SettingBase sb = (SettingBase) pkg.mExtras;
3661        PermissionsState permissionsState = sb.getPermissionsState();
3662
3663        if (permissionsState.grantInstallPermission(bp) !=
3664                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3665            scheduleWriteSettingsLocked();
3666        }
3667    }
3668
3669    @Override
3670    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3671        mContext.enforceCallingOrSelfPermission(
3672                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3673                "addOnPermissionsChangeListener");
3674
3675        synchronized (mPackages) {
3676            mOnPermissionChangeListeners.addListenerLocked(listener);
3677        }
3678    }
3679
3680    @Override
3681    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3682        synchronized (mPackages) {
3683            mOnPermissionChangeListeners.removeListenerLocked(listener);
3684        }
3685    }
3686
3687    @Override
3688    public boolean isProtectedBroadcast(String actionName) {
3689        synchronized (mPackages) {
3690            return mProtectedBroadcasts.contains(actionName);
3691        }
3692    }
3693
3694    @Override
3695    public int checkSignatures(String pkg1, String pkg2) {
3696        synchronized (mPackages) {
3697            final PackageParser.Package p1 = mPackages.get(pkg1);
3698            final PackageParser.Package p2 = mPackages.get(pkg2);
3699            if (p1 == null || p1.mExtras == null
3700                    || p2 == null || p2.mExtras == null) {
3701                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3702            }
3703            return compareSignatures(p1.mSignatures, p2.mSignatures);
3704        }
3705    }
3706
3707    @Override
3708    public int checkUidSignatures(int uid1, int uid2) {
3709        // Map to base uids.
3710        uid1 = UserHandle.getAppId(uid1);
3711        uid2 = UserHandle.getAppId(uid2);
3712        // reader
3713        synchronized (mPackages) {
3714            Signature[] s1;
3715            Signature[] s2;
3716            Object obj = mSettings.getUserIdLPr(uid1);
3717            if (obj != null) {
3718                if (obj instanceof SharedUserSetting) {
3719                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3720                } else if (obj instanceof PackageSetting) {
3721                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3722                } else {
3723                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3724                }
3725            } else {
3726                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3727            }
3728            obj = mSettings.getUserIdLPr(uid2);
3729            if (obj != null) {
3730                if (obj instanceof SharedUserSetting) {
3731                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3732                } else if (obj instanceof PackageSetting) {
3733                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3734                } else {
3735                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3736                }
3737            } else {
3738                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3739            }
3740            return compareSignatures(s1, s2);
3741        }
3742    }
3743
3744    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3745        final long identity = Binder.clearCallingIdentity();
3746        try {
3747            if (sb instanceof SharedUserSetting) {
3748                SharedUserSetting sus = (SharedUserSetting) sb;
3749                final int packageCount = sus.packages.size();
3750                for (int i = 0; i < packageCount; i++) {
3751                    PackageSetting susPs = sus.packages.valueAt(i);
3752                    if (userId == UserHandle.USER_ALL) {
3753                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3754                    } else {
3755                        final int uid = UserHandle.getUid(userId, susPs.appId);
3756                        killUid(uid, reason);
3757                    }
3758                }
3759            } else if (sb instanceof PackageSetting) {
3760                PackageSetting ps = (PackageSetting) sb;
3761                if (userId == UserHandle.USER_ALL) {
3762                    killApplication(ps.pkg.packageName, ps.appId, reason);
3763                } else {
3764                    final int uid = UserHandle.getUid(userId, ps.appId);
3765                    killUid(uid, reason);
3766                }
3767            }
3768        } finally {
3769            Binder.restoreCallingIdentity(identity);
3770        }
3771    }
3772
3773    private static void killUid(int uid, String reason) {
3774        IActivityManager am = ActivityManagerNative.getDefault();
3775        if (am != null) {
3776            try {
3777                am.killUid(uid, reason);
3778            } catch (RemoteException e) {
3779                /* ignore - same process */
3780            }
3781        }
3782    }
3783
3784    /**
3785     * Compares two sets of signatures. Returns:
3786     * <br />
3787     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3788     * <br />
3789     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3790     * <br />
3791     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3792     * <br />
3793     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3794     * <br />
3795     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3796     */
3797    static int compareSignatures(Signature[] s1, Signature[] s2) {
3798        if (s1 == null) {
3799            return s2 == null
3800                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3801                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3802        }
3803
3804        if (s2 == null) {
3805            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3806        }
3807
3808        if (s1.length != s2.length) {
3809            return PackageManager.SIGNATURE_NO_MATCH;
3810        }
3811
3812        // Since both signature sets are of size 1, we can compare without HashSets.
3813        if (s1.length == 1) {
3814            return s1[0].equals(s2[0]) ?
3815                    PackageManager.SIGNATURE_MATCH :
3816                    PackageManager.SIGNATURE_NO_MATCH;
3817        }
3818
3819        ArraySet<Signature> set1 = new ArraySet<Signature>();
3820        for (Signature sig : s1) {
3821            set1.add(sig);
3822        }
3823        ArraySet<Signature> set2 = new ArraySet<Signature>();
3824        for (Signature sig : s2) {
3825            set2.add(sig);
3826        }
3827        // Make sure s2 contains all signatures in s1.
3828        if (set1.equals(set2)) {
3829            return PackageManager.SIGNATURE_MATCH;
3830        }
3831        return PackageManager.SIGNATURE_NO_MATCH;
3832    }
3833
3834    /**
3835     * If the database version for this type of package (internal storage or
3836     * external storage) is less than the version where package signatures
3837     * were updated, return true.
3838     */
3839    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3840        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3841                DatabaseVersion.SIGNATURE_END_ENTITY))
3842                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3843                        DatabaseVersion.SIGNATURE_END_ENTITY));
3844    }
3845
3846    /**
3847     * Used for backward compatibility to make sure any packages with
3848     * certificate chains get upgraded to the new style. {@code existingSigs}
3849     * will be in the old format (since they were stored on disk from before the
3850     * system upgrade) and {@code scannedSigs} will be in the newer format.
3851     */
3852    private int compareSignaturesCompat(PackageSignatures existingSigs,
3853            PackageParser.Package scannedPkg) {
3854        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3855            return PackageManager.SIGNATURE_NO_MATCH;
3856        }
3857
3858        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3859        for (Signature sig : existingSigs.mSignatures) {
3860            existingSet.add(sig);
3861        }
3862        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3863        for (Signature sig : scannedPkg.mSignatures) {
3864            try {
3865                Signature[] chainSignatures = sig.getChainSignatures();
3866                for (Signature chainSig : chainSignatures) {
3867                    scannedCompatSet.add(chainSig);
3868                }
3869            } catch (CertificateEncodingException e) {
3870                scannedCompatSet.add(sig);
3871            }
3872        }
3873        /*
3874         * Make sure the expanded scanned set contains all signatures in the
3875         * existing one.
3876         */
3877        if (scannedCompatSet.equals(existingSet)) {
3878            // Migrate the old signatures to the new scheme.
3879            existingSigs.assignSignatures(scannedPkg.mSignatures);
3880            // The new KeySets will be re-added later in the scanning process.
3881            synchronized (mPackages) {
3882                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3883            }
3884            return PackageManager.SIGNATURE_MATCH;
3885        }
3886        return PackageManager.SIGNATURE_NO_MATCH;
3887    }
3888
3889    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3890        if (isExternal(scannedPkg)) {
3891            return mSettings.isExternalDatabaseVersionOlderThan(
3892                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3893        } else {
3894            return mSettings.isInternalDatabaseVersionOlderThan(
3895                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3896        }
3897    }
3898
3899    private int compareSignaturesRecover(PackageSignatures existingSigs,
3900            PackageParser.Package scannedPkg) {
3901        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3902            return PackageManager.SIGNATURE_NO_MATCH;
3903        }
3904
3905        String msg = null;
3906        try {
3907            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3908                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3909                        + scannedPkg.packageName);
3910                return PackageManager.SIGNATURE_MATCH;
3911            }
3912        } catch (CertificateException e) {
3913            msg = e.getMessage();
3914        }
3915
3916        logCriticalInfo(Log.INFO,
3917                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3918        return PackageManager.SIGNATURE_NO_MATCH;
3919    }
3920
3921    @Override
3922    public String[] getPackagesForUid(int uid) {
3923        uid = UserHandle.getAppId(uid);
3924        // reader
3925        synchronized (mPackages) {
3926            Object obj = mSettings.getUserIdLPr(uid);
3927            if (obj instanceof SharedUserSetting) {
3928                final SharedUserSetting sus = (SharedUserSetting) obj;
3929                final int N = sus.packages.size();
3930                final String[] res = new String[N];
3931                final Iterator<PackageSetting> it = sus.packages.iterator();
3932                int i = 0;
3933                while (it.hasNext()) {
3934                    res[i++] = it.next().name;
3935                }
3936                return res;
3937            } else if (obj instanceof PackageSetting) {
3938                final PackageSetting ps = (PackageSetting) obj;
3939                return new String[] { ps.name };
3940            }
3941        }
3942        return null;
3943    }
3944
3945    @Override
3946    public String getNameForUid(int uid) {
3947        // reader
3948        synchronized (mPackages) {
3949            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3950            if (obj instanceof SharedUserSetting) {
3951                final SharedUserSetting sus = (SharedUserSetting) obj;
3952                return sus.name + ":" + sus.userId;
3953            } else if (obj instanceof PackageSetting) {
3954                final PackageSetting ps = (PackageSetting) obj;
3955                return ps.name;
3956            }
3957        }
3958        return null;
3959    }
3960
3961    @Override
3962    public int getUidForSharedUser(String sharedUserName) {
3963        if(sharedUserName == null) {
3964            return -1;
3965        }
3966        // reader
3967        synchronized (mPackages) {
3968            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3969            if (suid == null) {
3970                return -1;
3971            }
3972            return suid.userId;
3973        }
3974    }
3975
3976    @Override
3977    public int getFlagsForUid(int uid) {
3978        synchronized (mPackages) {
3979            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3980            if (obj instanceof SharedUserSetting) {
3981                final SharedUserSetting sus = (SharedUserSetting) obj;
3982                return sus.pkgFlags;
3983            } else if (obj instanceof PackageSetting) {
3984                final PackageSetting ps = (PackageSetting) obj;
3985                return ps.pkgFlags;
3986            }
3987        }
3988        return 0;
3989    }
3990
3991    @Override
3992    public int getPrivateFlagsForUid(int uid) {
3993        synchronized (mPackages) {
3994            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3995            if (obj instanceof SharedUserSetting) {
3996                final SharedUserSetting sus = (SharedUserSetting) obj;
3997                return sus.pkgPrivateFlags;
3998            } else if (obj instanceof PackageSetting) {
3999                final PackageSetting ps = (PackageSetting) obj;
4000                return ps.pkgPrivateFlags;
4001            }
4002        }
4003        return 0;
4004    }
4005
4006    @Override
4007    public boolean isUidPrivileged(int uid) {
4008        uid = UserHandle.getAppId(uid);
4009        // reader
4010        synchronized (mPackages) {
4011            Object obj = mSettings.getUserIdLPr(uid);
4012            if (obj instanceof SharedUserSetting) {
4013                final SharedUserSetting sus = (SharedUserSetting) obj;
4014                final Iterator<PackageSetting> it = sus.packages.iterator();
4015                while (it.hasNext()) {
4016                    if (it.next().isPrivileged()) {
4017                        return true;
4018                    }
4019                }
4020            } else if (obj instanceof PackageSetting) {
4021                final PackageSetting ps = (PackageSetting) obj;
4022                return ps.isPrivileged();
4023            }
4024        }
4025        return false;
4026    }
4027
4028    @Override
4029    public String[] getAppOpPermissionPackages(String permissionName) {
4030        synchronized (mPackages) {
4031            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4032            if (pkgs == null) {
4033                return null;
4034            }
4035            return pkgs.toArray(new String[pkgs.size()]);
4036        }
4037    }
4038
4039    @Override
4040    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4041            int flags, int userId) {
4042        if (!sUserManager.exists(userId)) return null;
4043        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4044        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4045        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4046    }
4047
4048    @Override
4049    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4050            IntentFilter filter, int match, ComponentName activity) {
4051        final int userId = UserHandle.getCallingUserId();
4052        if (DEBUG_PREFERRED) {
4053            Log.v(TAG, "setLastChosenActivity intent=" + intent
4054                + " resolvedType=" + resolvedType
4055                + " flags=" + flags
4056                + " filter=" + filter
4057                + " match=" + match
4058                + " activity=" + activity);
4059            filter.dump(new PrintStreamPrinter(System.out), "    ");
4060        }
4061        intent.setComponent(null);
4062        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4063        // Find any earlier preferred or last chosen entries and nuke them
4064        findPreferredActivity(intent, resolvedType,
4065                flags, query, 0, false, true, false, userId);
4066        // Add the new activity as the last chosen for this filter
4067        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4068                "Setting last chosen");
4069    }
4070
4071    @Override
4072    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4073        final int userId = UserHandle.getCallingUserId();
4074        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4075        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4076        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4077                false, false, false, userId);
4078    }
4079
4080    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4081            int flags, List<ResolveInfo> query, int userId) {
4082        if (query != null) {
4083            final int N = query.size();
4084            if (N == 1) {
4085                return query.get(0);
4086            } else if (N > 1) {
4087                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4088                // If there is more than one activity with the same priority,
4089                // then let the user decide between them.
4090                ResolveInfo r0 = query.get(0);
4091                ResolveInfo r1 = query.get(1);
4092                if (DEBUG_INTENT_MATCHING || debug) {
4093                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4094                            + r1.activityInfo.name + "=" + r1.priority);
4095                }
4096                // If the first activity has a higher priority, or a different
4097                // default, then it is always desireable to pick it.
4098                if (r0.priority != r1.priority
4099                        || r0.preferredOrder != r1.preferredOrder
4100                        || r0.isDefault != r1.isDefault) {
4101                    return query.get(0);
4102                }
4103                // If we have saved a preference for a preferred activity for
4104                // this Intent, use that.
4105                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4106                        flags, query, r0.priority, true, false, debug, userId);
4107                if (ri != null) {
4108                    return ri;
4109                }
4110                if (userId != 0) {
4111                    ri = new ResolveInfo(mResolveInfo);
4112                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4113                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4114                            ri.activityInfo.applicationInfo);
4115                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4116                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4117                    return ri;
4118                }
4119                return mResolveInfo;
4120            }
4121        }
4122        return null;
4123    }
4124
4125    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4126            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4127        final int N = query.size();
4128        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4129                .get(userId);
4130        // Get the list of persistent preferred activities that handle the intent
4131        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4132        List<PersistentPreferredActivity> pprefs = ppir != null
4133                ? ppir.queryIntent(intent, resolvedType,
4134                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4135                : null;
4136        if (pprefs != null && pprefs.size() > 0) {
4137            final int M = pprefs.size();
4138            for (int i=0; i<M; i++) {
4139                final PersistentPreferredActivity ppa = pprefs.get(i);
4140                if (DEBUG_PREFERRED || debug) {
4141                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4142                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4143                            + "\n  component=" + ppa.mComponent);
4144                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4145                }
4146                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4147                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4148                if (DEBUG_PREFERRED || debug) {
4149                    Slog.v(TAG, "Found persistent preferred activity:");
4150                    if (ai != null) {
4151                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4152                    } else {
4153                        Slog.v(TAG, "  null");
4154                    }
4155                }
4156                if (ai == null) {
4157                    // This previously registered persistent preferred activity
4158                    // component is no longer known. Ignore it and do NOT remove it.
4159                    continue;
4160                }
4161                for (int j=0; j<N; j++) {
4162                    final ResolveInfo ri = query.get(j);
4163                    if (!ri.activityInfo.applicationInfo.packageName
4164                            .equals(ai.applicationInfo.packageName)) {
4165                        continue;
4166                    }
4167                    if (!ri.activityInfo.name.equals(ai.name)) {
4168                        continue;
4169                    }
4170                    //  Found a persistent preference that can handle the intent.
4171                    if (DEBUG_PREFERRED || debug) {
4172                        Slog.v(TAG, "Returning persistent preferred activity: " +
4173                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4174                    }
4175                    return ri;
4176                }
4177            }
4178        }
4179        return null;
4180    }
4181
4182    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4183            List<ResolveInfo> query, int priority, boolean always,
4184            boolean removeMatches, boolean debug, int userId) {
4185        if (!sUserManager.exists(userId)) return null;
4186        // writer
4187        synchronized (mPackages) {
4188            if (intent.getSelector() != null) {
4189                intent = intent.getSelector();
4190            }
4191            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4192
4193            // Try to find a matching persistent preferred activity.
4194            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4195                    debug, userId);
4196
4197            // If a persistent preferred activity matched, use it.
4198            if (pri != null) {
4199                return pri;
4200            }
4201
4202            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4203            // Get the list of preferred activities that handle the intent
4204            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4205            List<PreferredActivity> prefs = pir != null
4206                    ? pir.queryIntent(intent, resolvedType,
4207                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4208                    : null;
4209            if (prefs != null && prefs.size() > 0) {
4210                boolean changed = false;
4211                try {
4212                    // First figure out how good the original match set is.
4213                    // We will only allow preferred activities that came
4214                    // from the same match quality.
4215                    int match = 0;
4216
4217                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4218
4219                    final int N = query.size();
4220                    for (int j=0; j<N; j++) {
4221                        final ResolveInfo ri = query.get(j);
4222                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4223                                + ": 0x" + Integer.toHexString(match));
4224                        if (ri.match > match) {
4225                            match = ri.match;
4226                        }
4227                    }
4228
4229                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4230                            + Integer.toHexString(match));
4231
4232                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4233                    final int M = prefs.size();
4234                    for (int i=0; i<M; i++) {
4235                        final PreferredActivity pa = prefs.get(i);
4236                        if (DEBUG_PREFERRED || debug) {
4237                            Slog.v(TAG, "Checking PreferredActivity ds="
4238                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4239                                    + "\n  component=" + pa.mPref.mComponent);
4240                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4241                        }
4242                        if (pa.mPref.mMatch != match) {
4243                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4244                                    + Integer.toHexString(pa.mPref.mMatch));
4245                            continue;
4246                        }
4247                        // If it's not an "always" type preferred activity and that's what we're
4248                        // looking for, skip it.
4249                        if (always && !pa.mPref.mAlways) {
4250                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4251                            continue;
4252                        }
4253                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4254                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4255                        if (DEBUG_PREFERRED || debug) {
4256                            Slog.v(TAG, "Found preferred activity:");
4257                            if (ai != null) {
4258                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4259                            } else {
4260                                Slog.v(TAG, "  null");
4261                            }
4262                        }
4263                        if (ai == null) {
4264                            // This previously registered preferred activity
4265                            // component is no longer known.  Most likely an update
4266                            // to the app was installed and in the new version this
4267                            // component no longer exists.  Clean it up by removing
4268                            // it from the preferred activities list, and skip it.
4269                            Slog.w(TAG, "Removing dangling preferred activity: "
4270                                    + pa.mPref.mComponent);
4271                            pir.removeFilter(pa);
4272                            changed = true;
4273                            continue;
4274                        }
4275                        for (int j=0; j<N; j++) {
4276                            final ResolveInfo ri = query.get(j);
4277                            if (!ri.activityInfo.applicationInfo.packageName
4278                                    .equals(ai.applicationInfo.packageName)) {
4279                                continue;
4280                            }
4281                            if (!ri.activityInfo.name.equals(ai.name)) {
4282                                continue;
4283                            }
4284
4285                            if (removeMatches) {
4286                                pir.removeFilter(pa);
4287                                changed = true;
4288                                if (DEBUG_PREFERRED) {
4289                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4290                                }
4291                                break;
4292                            }
4293
4294                            // Okay we found a previously set preferred or last chosen app.
4295                            // If the result set is different from when this
4296                            // was created, we need to clear it and re-ask the
4297                            // user their preference, if we're looking for an "always" type entry.
4298                            if (always && !pa.mPref.sameSet(query)) {
4299                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4300                                        + intent + " type " + resolvedType);
4301                                if (DEBUG_PREFERRED) {
4302                                    Slog.v(TAG, "Removing preferred activity since set changed "
4303                                            + pa.mPref.mComponent);
4304                                }
4305                                pir.removeFilter(pa);
4306                                // Re-add the filter as a "last chosen" entry (!always)
4307                                PreferredActivity lastChosen = new PreferredActivity(
4308                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4309                                pir.addFilter(lastChosen);
4310                                changed = true;
4311                                return null;
4312                            }
4313
4314                            // Yay! Either the set matched or we're looking for the last chosen
4315                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4316                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4317                            return ri;
4318                        }
4319                    }
4320                } finally {
4321                    if (changed) {
4322                        if (DEBUG_PREFERRED) {
4323                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4324                        }
4325                        scheduleWritePackageRestrictionsLocked(userId);
4326                    }
4327                }
4328            }
4329        }
4330        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4331        return null;
4332    }
4333
4334    /*
4335     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4336     */
4337    @Override
4338    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4339            int targetUserId) {
4340        mContext.enforceCallingOrSelfPermission(
4341                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4342        List<CrossProfileIntentFilter> matches =
4343                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4344        if (matches != null) {
4345            int size = matches.size();
4346            for (int i = 0; i < size; i++) {
4347                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4348            }
4349        }
4350        if (hasWebURI(intent)) {
4351            // cross-profile app linking works only towards the parent.
4352            final UserInfo parent = getProfileParent(sourceUserId);
4353            synchronized(mPackages) {
4354                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4355                        parent.id) != null;
4356            }
4357        }
4358        return false;
4359    }
4360
4361    private UserInfo getProfileParent(int userId) {
4362        final long identity = Binder.clearCallingIdentity();
4363        try {
4364            return sUserManager.getProfileParent(userId);
4365        } finally {
4366            Binder.restoreCallingIdentity(identity);
4367        }
4368    }
4369
4370    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4371            String resolvedType, int userId) {
4372        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4373        if (resolver != null) {
4374            return resolver.queryIntent(intent, resolvedType, false, userId);
4375        }
4376        return null;
4377    }
4378
4379    @Override
4380    public List<ResolveInfo> queryIntentActivities(Intent intent,
4381            String resolvedType, int flags, int userId) {
4382        if (!sUserManager.exists(userId)) return Collections.emptyList();
4383        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4384        ComponentName comp = intent.getComponent();
4385        if (comp == null) {
4386            if (intent.getSelector() != null) {
4387                intent = intent.getSelector();
4388                comp = intent.getComponent();
4389            }
4390        }
4391
4392        if (comp != null) {
4393            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4394            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4395            if (ai != null) {
4396                final ResolveInfo ri = new ResolveInfo();
4397                ri.activityInfo = ai;
4398                list.add(ri);
4399            }
4400            return list;
4401        }
4402
4403        // reader
4404        synchronized (mPackages) {
4405            final String pkgName = intent.getPackage();
4406            if (pkgName == null) {
4407                List<CrossProfileIntentFilter> matchingFilters =
4408                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4409                // Check for results that need to skip the current profile.
4410                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4411                        resolvedType, flags, userId);
4412                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4413                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4414                    result.add(xpResolveInfo);
4415                    return filterIfNotPrimaryUser(result, userId);
4416                }
4417
4418                // Check for results in the current profile.
4419                List<ResolveInfo> result = mActivities.queryIntent(
4420                        intent, resolvedType, flags, userId);
4421
4422                // Check for cross profile results.
4423                xpResolveInfo = queryCrossProfileIntents(
4424                        matchingFilters, intent, resolvedType, flags, userId);
4425                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4426                    result.add(xpResolveInfo);
4427                    Collections.sort(result, mResolvePrioritySorter);
4428                }
4429                result = filterIfNotPrimaryUser(result, userId);
4430                if (hasWebURI(intent)) {
4431                    CrossProfileDomainInfo xpDomainInfo = null;
4432                    final UserInfo parent = getProfileParent(userId);
4433                    if (parent != null) {
4434                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4435                                flags, userId, parent.id);
4436                    }
4437                    if (xpDomainInfo != null) {
4438                        if (xpResolveInfo != null) {
4439                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4440                            // in the result.
4441                            result.remove(xpResolveInfo);
4442                        }
4443                        if (result.size() == 0) {
4444                            result.add(xpDomainInfo.resolveInfo);
4445                            return result;
4446                        }
4447                    } else if (result.size() <= 1) {
4448                        return result;
4449                    }
4450                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4451                            xpDomainInfo);
4452                    Collections.sort(result, mResolvePrioritySorter);
4453                }
4454                return result;
4455            }
4456            final PackageParser.Package pkg = mPackages.get(pkgName);
4457            if (pkg != null) {
4458                return filterIfNotPrimaryUser(
4459                        mActivities.queryIntentForPackage(
4460                                intent, resolvedType, flags, pkg.activities, userId),
4461                        userId);
4462            }
4463            return new ArrayList<ResolveInfo>();
4464        }
4465    }
4466
4467    private static class CrossProfileDomainInfo {
4468        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4469        ResolveInfo resolveInfo;
4470        /* Best domain verification status of the activities found in the other profile */
4471        int bestDomainVerificationStatus;
4472    }
4473
4474    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4475            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4476        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4477                sourceUserId)) {
4478            return null;
4479        }
4480        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4481                resolvedType, flags, parentUserId);
4482
4483        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4484            return null;
4485        }
4486        CrossProfileDomainInfo result = null;
4487        int size = resultTargetUser.size();
4488        for (int i = 0; i < size; i++) {
4489            ResolveInfo riTargetUser = resultTargetUser.get(i);
4490            // Intent filter verification is only for filters that specify a host. So don't return
4491            // those that handle all web uris.
4492            if (riTargetUser.handleAllWebDataURI) {
4493                continue;
4494            }
4495            String packageName = riTargetUser.activityInfo.packageName;
4496            PackageSetting ps = mSettings.mPackages.get(packageName);
4497            if (ps == null) {
4498                continue;
4499            }
4500            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4501            if (result == null) {
4502                result = new CrossProfileDomainInfo();
4503                result.resolveInfo =
4504                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4505                result.bestDomainVerificationStatus = status;
4506            } else {
4507                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4508                        result.bestDomainVerificationStatus);
4509            }
4510        }
4511        return result;
4512    }
4513
4514    /**
4515     * Verification statuses are ordered from the worse to the best, except for
4516     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4517     */
4518    private int bestDomainVerificationStatus(int status1, int status2) {
4519        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4520            return status2;
4521        }
4522        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4523            return status1;
4524        }
4525        return (int) MathUtils.max(status1, status2);
4526    }
4527
4528    private boolean isUserEnabled(int userId) {
4529        long callingId = Binder.clearCallingIdentity();
4530        try {
4531            UserInfo userInfo = sUserManager.getUserInfo(userId);
4532            return userInfo != null && userInfo.isEnabled();
4533        } finally {
4534            Binder.restoreCallingIdentity(callingId);
4535        }
4536    }
4537
4538    /**
4539     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4540     *
4541     * @return filtered list
4542     */
4543    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4544        if (userId == UserHandle.USER_OWNER) {
4545            return resolveInfos;
4546        }
4547        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4548            ResolveInfo info = resolveInfos.get(i);
4549            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4550                resolveInfos.remove(i);
4551            }
4552        }
4553        return resolveInfos;
4554    }
4555
4556    private static boolean hasWebURI(Intent intent) {
4557        if (intent.getData() == null) {
4558            return false;
4559        }
4560        final String scheme = intent.getScheme();
4561        if (TextUtils.isEmpty(scheme)) {
4562            return false;
4563        }
4564        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4565    }
4566
4567    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4568            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4569        if (DEBUG_PREFERRED) {
4570            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4571                    candidates.size());
4572        }
4573
4574        final int userId = UserHandle.getCallingUserId();
4575        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4576        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4577        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4578        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4579        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4580
4581        synchronized (mPackages) {
4582            final int count = candidates.size();
4583            // First, try to use the domain preferred app. Partition the candidates into four lists:
4584            // one for the final results, one for the "do not use ever", one for "undefined status"
4585            // and finally one for "Browser App type".
4586            for (int n=0; n<count; n++) {
4587                ResolveInfo info = candidates.get(n);
4588                String packageName = info.activityInfo.packageName;
4589                PackageSetting ps = mSettings.mPackages.get(packageName);
4590                if (ps != null) {
4591                    // Add to the special match all list (Browser use case)
4592                    if (info.handleAllWebDataURI) {
4593                        matchAllList.add(info);
4594                        continue;
4595                    }
4596                    // Try to get the status from User settings first
4597                    int status = getDomainVerificationStatusLPr(ps, userId);
4598                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4599                        alwaysList.add(info);
4600                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4601                        neverList.add(info);
4602                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4603                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4604                        undefinedList.add(info);
4605                    }
4606                }
4607            }
4608            // First try to add the "always" resolution for the current user if there is any
4609            if (alwaysList.size() > 0) {
4610                result.addAll(alwaysList);
4611            // if there is an "always" for the parent user, add it.
4612            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4613                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4614                result.add(xpDomainInfo.resolveInfo);
4615            } else {
4616                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4617                result.addAll(undefinedList);
4618                if (xpDomainInfo != null && (
4619                        xpDomainInfo.bestDomainVerificationStatus
4620                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4621                        || xpDomainInfo.bestDomainVerificationStatus
4622                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4623                    result.add(xpDomainInfo.resolveInfo);
4624                }
4625                // Also add Browsers (all of them or only the default one)
4626                if ((flags & MATCH_ALL) != 0) {
4627                    result.addAll(matchAllList);
4628                } else {
4629                    // Try to add the Default Browser if we can
4630                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4631                            UserHandle.myUserId());
4632                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4633                        boolean defaultBrowserFound = false;
4634                        final int browserCount = matchAllList.size();
4635                        for (int n=0; n<browserCount; n++) {
4636                            ResolveInfo browser = matchAllList.get(n);
4637                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4638                                result.add(browser);
4639                                defaultBrowserFound = true;
4640                                break;
4641                            }
4642                        }
4643                        if (!defaultBrowserFound) {
4644                            result.addAll(matchAllList);
4645                        }
4646                    } else {
4647                        result.addAll(matchAllList);
4648                    }
4649                }
4650
4651                // If there is nothing selected, add all candidates and remove the ones that the User
4652                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4653                if (result.size() == 0) {
4654                    result.addAll(candidates);
4655                    result.removeAll(neverList);
4656                }
4657            }
4658        }
4659        if (DEBUG_PREFERRED) {
4660            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4661                    result.size());
4662        }
4663        return result;
4664    }
4665
4666    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4667        int status = ps.getDomainVerificationStatusForUser(userId);
4668        // if none available, get the master status
4669        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4670            if (ps.getIntentFilterVerificationInfo() != null) {
4671                status = ps.getIntentFilterVerificationInfo().getStatus();
4672            }
4673        }
4674        return status;
4675    }
4676
4677    private ResolveInfo querySkipCurrentProfileIntents(
4678            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4679            int flags, int sourceUserId) {
4680        if (matchingFilters != null) {
4681            int size = matchingFilters.size();
4682            for (int i = 0; i < size; i ++) {
4683                CrossProfileIntentFilter filter = matchingFilters.get(i);
4684                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4685                    // Checking if there are activities in the target user that can handle the
4686                    // intent.
4687                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4688                            flags, sourceUserId);
4689                    if (resolveInfo != null) {
4690                        return resolveInfo;
4691                    }
4692                }
4693            }
4694        }
4695        return null;
4696    }
4697
4698    // Return matching ResolveInfo if any for skip current profile intent filters.
4699    private ResolveInfo queryCrossProfileIntents(
4700            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4701            int flags, int sourceUserId) {
4702        if (matchingFilters != null) {
4703            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4704            // match the same intent. For performance reasons, it is better not to
4705            // run queryIntent twice for the same userId
4706            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4707            int size = matchingFilters.size();
4708            for (int i = 0; i < size; i++) {
4709                CrossProfileIntentFilter filter = matchingFilters.get(i);
4710                int targetUserId = filter.getTargetUserId();
4711                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4712                        && !alreadyTriedUserIds.get(targetUserId)) {
4713                    // Checking if there are activities in the target user that can handle the
4714                    // intent.
4715                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4716                            flags, sourceUserId);
4717                    if (resolveInfo != null) return resolveInfo;
4718                    alreadyTriedUserIds.put(targetUserId, true);
4719                }
4720            }
4721        }
4722        return null;
4723    }
4724
4725    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4726            String resolvedType, int flags, int sourceUserId) {
4727        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4728                resolvedType, flags, filter.getTargetUserId());
4729        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4730            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4731        }
4732        return null;
4733    }
4734
4735    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4736            int sourceUserId, int targetUserId) {
4737        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4738        String className;
4739        if (targetUserId == UserHandle.USER_OWNER) {
4740            className = FORWARD_INTENT_TO_USER_OWNER;
4741        } else {
4742            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4743        }
4744        ComponentName forwardingActivityComponentName = new ComponentName(
4745                mAndroidApplication.packageName, className);
4746        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4747                sourceUserId);
4748        if (targetUserId == UserHandle.USER_OWNER) {
4749            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4750            forwardingResolveInfo.noResourceId = true;
4751        }
4752        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4753        forwardingResolveInfo.priority = 0;
4754        forwardingResolveInfo.preferredOrder = 0;
4755        forwardingResolveInfo.match = 0;
4756        forwardingResolveInfo.isDefault = true;
4757        forwardingResolveInfo.filter = filter;
4758        forwardingResolveInfo.targetUserId = targetUserId;
4759        return forwardingResolveInfo;
4760    }
4761
4762    @Override
4763    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4764            Intent[] specifics, String[] specificTypes, Intent intent,
4765            String resolvedType, int flags, int userId) {
4766        if (!sUserManager.exists(userId)) return Collections.emptyList();
4767        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4768                false, "query intent activity options");
4769        final String resultsAction = intent.getAction();
4770
4771        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4772                | PackageManager.GET_RESOLVED_FILTER, userId);
4773
4774        if (DEBUG_INTENT_MATCHING) {
4775            Log.v(TAG, "Query " + intent + ": " + results);
4776        }
4777
4778        int specificsPos = 0;
4779        int N;
4780
4781        // todo: note that the algorithm used here is O(N^2).  This
4782        // isn't a problem in our current environment, but if we start running
4783        // into situations where we have more than 5 or 10 matches then this
4784        // should probably be changed to something smarter...
4785
4786        // First we go through and resolve each of the specific items
4787        // that were supplied, taking care of removing any corresponding
4788        // duplicate items in the generic resolve list.
4789        if (specifics != null) {
4790            for (int i=0; i<specifics.length; i++) {
4791                final Intent sintent = specifics[i];
4792                if (sintent == null) {
4793                    continue;
4794                }
4795
4796                if (DEBUG_INTENT_MATCHING) {
4797                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4798                }
4799
4800                String action = sintent.getAction();
4801                if (resultsAction != null && resultsAction.equals(action)) {
4802                    // If this action was explicitly requested, then don't
4803                    // remove things that have it.
4804                    action = null;
4805                }
4806
4807                ResolveInfo ri = null;
4808                ActivityInfo ai = null;
4809
4810                ComponentName comp = sintent.getComponent();
4811                if (comp == null) {
4812                    ri = resolveIntent(
4813                        sintent,
4814                        specificTypes != null ? specificTypes[i] : null,
4815                            flags, userId);
4816                    if (ri == null) {
4817                        continue;
4818                    }
4819                    if (ri == mResolveInfo) {
4820                        // ACK!  Must do something better with this.
4821                    }
4822                    ai = ri.activityInfo;
4823                    comp = new ComponentName(ai.applicationInfo.packageName,
4824                            ai.name);
4825                } else {
4826                    ai = getActivityInfo(comp, flags, userId);
4827                    if (ai == null) {
4828                        continue;
4829                    }
4830                }
4831
4832                // Look for any generic query activities that are duplicates
4833                // of this specific one, and remove them from the results.
4834                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4835                N = results.size();
4836                int j;
4837                for (j=specificsPos; j<N; j++) {
4838                    ResolveInfo sri = results.get(j);
4839                    if ((sri.activityInfo.name.equals(comp.getClassName())
4840                            && sri.activityInfo.applicationInfo.packageName.equals(
4841                                    comp.getPackageName()))
4842                        || (action != null && sri.filter.matchAction(action))) {
4843                        results.remove(j);
4844                        if (DEBUG_INTENT_MATCHING) Log.v(
4845                            TAG, "Removing duplicate item from " + j
4846                            + " due to specific " + specificsPos);
4847                        if (ri == null) {
4848                            ri = sri;
4849                        }
4850                        j--;
4851                        N--;
4852                    }
4853                }
4854
4855                // Add this specific item to its proper place.
4856                if (ri == null) {
4857                    ri = new ResolveInfo();
4858                    ri.activityInfo = ai;
4859                }
4860                results.add(specificsPos, ri);
4861                ri.specificIndex = i;
4862                specificsPos++;
4863            }
4864        }
4865
4866        // Now we go through the remaining generic results and remove any
4867        // duplicate actions that are found here.
4868        N = results.size();
4869        for (int i=specificsPos; i<N-1; i++) {
4870            final ResolveInfo rii = results.get(i);
4871            if (rii.filter == null) {
4872                continue;
4873            }
4874
4875            // Iterate over all of the actions of this result's intent
4876            // filter...  typically this should be just one.
4877            final Iterator<String> it = rii.filter.actionsIterator();
4878            if (it == null) {
4879                continue;
4880            }
4881            while (it.hasNext()) {
4882                final String action = it.next();
4883                if (resultsAction != null && resultsAction.equals(action)) {
4884                    // If this action was explicitly requested, then don't
4885                    // remove things that have it.
4886                    continue;
4887                }
4888                for (int j=i+1; j<N; j++) {
4889                    final ResolveInfo rij = results.get(j);
4890                    if (rij.filter != null && rij.filter.hasAction(action)) {
4891                        results.remove(j);
4892                        if (DEBUG_INTENT_MATCHING) Log.v(
4893                            TAG, "Removing duplicate item from " + j
4894                            + " due to action " + action + " at " + i);
4895                        j--;
4896                        N--;
4897                    }
4898                }
4899            }
4900
4901            // If the caller didn't request filter information, drop it now
4902            // so we don't have to marshall/unmarshall it.
4903            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4904                rii.filter = null;
4905            }
4906        }
4907
4908        // Filter out the caller activity if so requested.
4909        if (caller != null) {
4910            N = results.size();
4911            for (int i=0; i<N; i++) {
4912                ActivityInfo ainfo = results.get(i).activityInfo;
4913                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4914                        && caller.getClassName().equals(ainfo.name)) {
4915                    results.remove(i);
4916                    break;
4917                }
4918            }
4919        }
4920
4921        // If the caller didn't request filter information,
4922        // drop them now so we don't have to
4923        // marshall/unmarshall it.
4924        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4925            N = results.size();
4926            for (int i=0; i<N; i++) {
4927                results.get(i).filter = null;
4928            }
4929        }
4930
4931        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4932        return results;
4933    }
4934
4935    @Override
4936    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4937            int userId) {
4938        if (!sUserManager.exists(userId)) return Collections.emptyList();
4939        ComponentName comp = intent.getComponent();
4940        if (comp == null) {
4941            if (intent.getSelector() != null) {
4942                intent = intent.getSelector();
4943                comp = intent.getComponent();
4944            }
4945        }
4946        if (comp != null) {
4947            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4948            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4949            if (ai != null) {
4950                ResolveInfo ri = new ResolveInfo();
4951                ri.activityInfo = ai;
4952                list.add(ri);
4953            }
4954            return list;
4955        }
4956
4957        // reader
4958        synchronized (mPackages) {
4959            String pkgName = intent.getPackage();
4960            if (pkgName == null) {
4961                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4962            }
4963            final PackageParser.Package pkg = mPackages.get(pkgName);
4964            if (pkg != null) {
4965                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4966                        userId);
4967            }
4968            return null;
4969        }
4970    }
4971
4972    @Override
4973    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4974        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4975        if (!sUserManager.exists(userId)) return null;
4976        if (query != null) {
4977            if (query.size() >= 1) {
4978                // If there is more than one service with the same priority,
4979                // just arbitrarily pick the first one.
4980                return query.get(0);
4981            }
4982        }
4983        return null;
4984    }
4985
4986    @Override
4987    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4988            int userId) {
4989        if (!sUserManager.exists(userId)) return Collections.emptyList();
4990        ComponentName comp = intent.getComponent();
4991        if (comp == null) {
4992            if (intent.getSelector() != null) {
4993                intent = intent.getSelector();
4994                comp = intent.getComponent();
4995            }
4996        }
4997        if (comp != null) {
4998            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4999            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5000            if (si != null) {
5001                final ResolveInfo ri = new ResolveInfo();
5002                ri.serviceInfo = si;
5003                list.add(ri);
5004            }
5005            return list;
5006        }
5007
5008        // reader
5009        synchronized (mPackages) {
5010            String pkgName = intent.getPackage();
5011            if (pkgName == null) {
5012                return mServices.queryIntent(intent, resolvedType, flags, userId);
5013            }
5014            final PackageParser.Package pkg = mPackages.get(pkgName);
5015            if (pkg != null) {
5016                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5017                        userId);
5018            }
5019            return null;
5020        }
5021    }
5022
5023    @Override
5024    public List<ResolveInfo> queryIntentContentProviders(
5025            Intent intent, String resolvedType, int flags, int userId) {
5026        if (!sUserManager.exists(userId)) return Collections.emptyList();
5027        ComponentName comp = intent.getComponent();
5028        if (comp == null) {
5029            if (intent.getSelector() != null) {
5030                intent = intent.getSelector();
5031                comp = intent.getComponent();
5032            }
5033        }
5034        if (comp != null) {
5035            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5036            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5037            if (pi != null) {
5038                final ResolveInfo ri = new ResolveInfo();
5039                ri.providerInfo = pi;
5040                list.add(ri);
5041            }
5042            return list;
5043        }
5044
5045        // reader
5046        synchronized (mPackages) {
5047            String pkgName = intent.getPackage();
5048            if (pkgName == null) {
5049                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5050            }
5051            final PackageParser.Package pkg = mPackages.get(pkgName);
5052            if (pkg != null) {
5053                return mProviders.queryIntentForPackage(
5054                        intent, resolvedType, flags, pkg.providers, userId);
5055            }
5056            return null;
5057        }
5058    }
5059
5060    @Override
5061    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5062        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5063
5064        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5065
5066        // writer
5067        synchronized (mPackages) {
5068            ArrayList<PackageInfo> list;
5069            if (listUninstalled) {
5070                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5071                for (PackageSetting ps : mSettings.mPackages.values()) {
5072                    PackageInfo pi;
5073                    if (ps.pkg != null) {
5074                        pi = generatePackageInfo(ps.pkg, flags, userId);
5075                    } else {
5076                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5077                    }
5078                    if (pi != null) {
5079                        list.add(pi);
5080                    }
5081                }
5082            } else {
5083                list = new ArrayList<PackageInfo>(mPackages.size());
5084                for (PackageParser.Package p : mPackages.values()) {
5085                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5086                    if (pi != null) {
5087                        list.add(pi);
5088                    }
5089                }
5090            }
5091
5092            return new ParceledListSlice<PackageInfo>(list);
5093        }
5094    }
5095
5096    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5097            String[] permissions, boolean[] tmp, int flags, int userId) {
5098        int numMatch = 0;
5099        final PermissionsState permissionsState = ps.getPermissionsState();
5100        for (int i=0; i<permissions.length; i++) {
5101            final String permission = permissions[i];
5102            if (permissionsState.hasPermission(permission, userId)) {
5103                tmp[i] = true;
5104                numMatch++;
5105            } else {
5106                tmp[i] = false;
5107            }
5108        }
5109        if (numMatch == 0) {
5110            return;
5111        }
5112        PackageInfo pi;
5113        if (ps.pkg != null) {
5114            pi = generatePackageInfo(ps.pkg, flags, userId);
5115        } else {
5116            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5117        }
5118        // The above might return null in cases of uninstalled apps or install-state
5119        // skew across users/profiles.
5120        if (pi != null) {
5121            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5122                if (numMatch == permissions.length) {
5123                    pi.requestedPermissions = permissions;
5124                } else {
5125                    pi.requestedPermissions = new String[numMatch];
5126                    numMatch = 0;
5127                    for (int i=0; i<permissions.length; i++) {
5128                        if (tmp[i]) {
5129                            pi.requestedPermissions[numMatch] = permissions[i];
5130                            numMatch++;
5131                        }
5132                    }
5133                }
5134            }
5135            list.add(pi);
5136        }
5137    }
5138
5139    @Override
5140    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5141            String[] permissions, int flags, int userId) {
5142        if (!sUserManager.exists(userId)) return null;
5143        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5144
5145        // writer
5146        synchronized (mPackages) {
5147            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5148            boolean[] tmpBools = new boolean[permissions.length];
5149            if (listUninstalled) {
5150                for (PackageSetting ps : mSettings.mPackages.values()) {
5151                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5152                }
5153            } else {
5154                for (PackageParser.Package pkg : mPackages.values()) {
5155                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5156                    if (ps != null) {
5157                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5158                                userId);
5159                    }
5160                }
5161            }
5162
5163            return new ParceledListSlice<PackageInfo>(list);
5164        }
5165    }
5166
5167    @Override
5168    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5169        if (!sUserManager.exists(userId)) return null;
5170        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5171
5172        // writer
5173        synchronized (mPackages) {
5174            ArrayList<ApplicationInfo> list;
5175            if (listUninstalled) {
5176                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5177                for (PackageSetting ps : mSettings.mPackages.values()) {
5178                    ApplicationInfo ai;
5179                    if (ps.pkg != null) {
5180                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5181                                ps.readUserState(userId), userId);
5182                    } else {
5183                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5184                    }
5185                    if (ai != null) {
5186                        list.add(ai);
5187                    }
5188                }
5189            } else {
5190                list = new ArrayList<ApplicationInfo>(mPackages.size());
5191                for (PackageParser.Package p : mPackages.values()) {
5192                    if (p.mExtras != null) {
5193                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5194                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5195                        if (ai != null) {
5196                            list.add(ai);
5197                        }
5198                    }
5199                }
5200            }
5201
5202            return new ParceledListSlice<ApplicationInfo>(list);
5203        }
5204    }
5205
5206    public List<ApplicationInfo> getPersistentApplications(int flags) {
5207        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5208
5209        // reader
5210        synchronized (mPackages) {
5211            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5212            final int userId = UserHandle.getCallingUserId();
5213            while (i.hasNext()) {
5214                final PackageParser.Package p = i.next();
5215                if (p.applicationInfo != null
5216                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5217                        && (!mSafeMode || isSystemApp(p))) {
5218                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5219                    if (ps != null) {
5220                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5221                                ps.readUserState(userId), userId);
5222                        if (ai != null) {
5223                            finalList.add(ai);
5224                        }
5225                    }
5226                }
5227            }
5228        }
5229
5230        return finalList;
5231    }
5232
5233    @Override
5234    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5235        if (!sUserManager.exists(userId)) return null;
5236        // reader
5237        synchronized (mPackages) {
5238            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5239            PackageSetting ps = provider != null
5240                    ? mSettings.mPackages.get(provider.owner.packageName)
5241                    : null;
5242            return ps != null
5243                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5244                    && (!mSafeMode || (provider.info.applicationInfo.flags
5245                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5246                    ? PackageParser.generateProviderInfo(provider, flags,
5247                            ps.readUserState(userId), userId)
5248                    : null;
5249        }
5250    }
5251
5252    /**
5253     * @deprecated
5254     */
5255    @Deprecated
5256    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5257        // reader
5258        synchronized (mPackages) {
5259            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5260                    .entrySet().iterator();
5261            final int userId = UserHandle.getCallingUserId();
5262            while (i.hasNext()) {
5263                Map.Entry<String, PackageParser.Provider> entry = i.next();
5264                PackageParser.Provider p = entry.getValue();
5265                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5266
5267                if (ps != null && p.syncable
5268                        && (!mSafeMode || (p.info.applicationInfo.flags
5269                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5270                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5271                            ps.readUserState(userId), userId);
5272                    if (info != null) {
5273                        outNames.add(entry.getKey());
5274                        outInfo.add(info);
5275                    }
5276                }
5277            }
5278        }
5279    }
5280
5281    @Override
5282    public List<ProviderInfo> queryContentProviders(String processName,
5283            int uid, int flags) {
5284        ArrayList<ProviderInfo> finalList = null;
5285        // reader
5286        synchronized (mPackages) {
5287            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5288            final int userId = processName != null ?
5289                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5290            while (i.hasNext()) {
5291                final PackageParser.Provider p = i.next();
5292                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5293                if (ps != null && p.info.authority != null
5294                        && (processName == null
5295                                || (p.info.processName.equals(processName)
5296                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5297                        && mSettings.isEnabledLPr(p.info, flags, userId)
5298                        && (!mSafeMode
5299                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5300                    if (finalList == null) {
5301                        finalList = new ArrayList<ProviderInfo>(3);
5302                    }
5303                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5304                            ps.readUserState(userId), userId);
5305                    if (info != null) {
5306                        finalList.add(info);
5307                    }
5308                }
5309            }
5310        }
5311
5312        if (finalList != null) {
5313            Collections.sort(finalList, mProviderInitOrderSorter);
5314        }
5315
5316        return finalList;
5317    }
5318
5319    @Override
5320    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5321            int flags) {
5322        // reader
5323        synchronized (mPackages) {
5324            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5325            return PackageParser.generateInstrumentationInfo(i, flags);
5326        }
5327    }
5328
5329    @Override
5330    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5331            int flags) {
5332        ArrayList<InstrumentationInfo> finalList =
5333            new ArrayList<InstrumentationInfo>();
5334
5335        // reader
5336        synchronized (mPackages) {
5337            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5338            while (i.hasNext()) {
5339                final PackageParser.Instrumentation p = i.next();
5340                if (targetPackage == null
5341                        || targetPackage.equals(p.info.targetPackage)) {
5342                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5343                            flags);
5344                    if (ii != null) {
5345                        finalList.add(ii);
5346                    }
5347                }
5348            }
5349        }
5350
5351        return finalList;
5352    }
5353
5354    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5355        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5356        if (overlays == null) {
5357            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5358            return;
5359        }
5360        for (PackageParser.Package opkg : overlays.values()) {
5361            // Not much to do if idmap fails: we already logged the error
5362            // and we certainly don't want to abort installation of pkg simply
5363            // because an overlay didn't fit properly. For these reasons,
5364            // ignore the return value of createIdmapForPackagePairLI.
5365            createIdmapForPackagePairLI(pkg, opkg);
5366        }
5367    }
5368
5369    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5370            PackageParser.Package opkg) {
5371        if (!opkg.mTrustedOverlay) {
5372            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5373                    opkg.baseCodePath + ": overlay not trusted");
5374            return false;
5375        }
5376        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5377        if (overlaySet == null) {
5378            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5379                    opkg.baseCodePath + " but target package has no known overlays");
5380            return false;
5381        }
5382        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5383        // TODO: generate idmap for split APKs
5384        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5385            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5386                    + opkg.baseCodePath);
5387            return false;
5388        }
5389        PackageParser.Package[] overlayArray =
5390            overlaySet.values().toArray(new PackageParser.Package[0]);
5391        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5392            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5393                return p1.mOverlayPriority - p2.mOverlayPriority;
5394            }
5395        };
5396        Arrays.sort(overlayArray, cmp);
5397
5398        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5399        int i = 0;
5400        for (PackageParser.Package p : overlayArray) {
5401            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5402        }
5403        return true;
5404    }
5405
5406    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5407        final File[] files = dir.listFiles();
5408        if (ArrayUtils.isEmpty(files)) {
5409            Log.d(TAG, "No files in app dir " + dir);
5410            return;
5411        }
5412
5413        if (DEBUG_PACKAGE_SCANNING) {
5414            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5415                    + " flags=0x" + Integer.toHexString(parseFlags));
5416        }
5417
5418        for (File file : files) {
5419            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5420                    && !PackageInstallerService.isStageName(file.getName());
5421            if (!isPackage) {
5422                // Ignore entries which are not packages
5423                continue;
5424            }
5425            try {
5426                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5427                        scanFlags, currentTime, null);
5428            } catch (PackageManagerException e) {
5429                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5430
5431                // Delete invalid userdata apps
5432                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5433                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5434                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5435                    if (file.isDirectory()) {
5436                        mInstaller.rmPackageDir(file.getAbsolutePath());
5437                    } else {
5438                        file.delete();
5439                    }
5440                }
5441            }
5442        }
5443    }
5444
5445    private static File getSettingsProblemFile() {
5446        File dataDir = Environment.getDataDirectory();
5447        File systemDir = new File(dataDir, "system");
5448        File fname = new File(systemDir, "uiderrors.txt");
5449        return fname;
5450    }
5451
5452    static void reportSettingsProblem(int priority, String msg) {
5453        logCriticalInfo(priority, msg);
5454    }
5455
5456    static void logCriticalInfo(int priority, String msg) {
5457        Slog.println(priority, TAG, msg);
5458        EventLogTags.writePmCriticalInfo(msg);
5459        try {
5460            File fname = getSettingsProblemFile();
5461            FileOutputStream out = new FileOutputStream(fname, true);
5462            PrintWriter pw = new FastPrintWriter(out);
5463            SimpleDateFormat formatter = new SimpleDateFormat();
5464            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5465            pw.println(dateString + ": " + msg);
5466            pw.close();
5467            FileUtils.setPermissions(
5468                    fname.toString(),
5469                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5470                    -1, -1);
5471        } catch (java.io.IOException e) {
5472        }
5473    }
5474
5475    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5476            PackageParser.Package pkg, File srcFile, int parseFlags)
5477            throws PackageManagerException {
5478        if (ps != null
5479                && ps.codePath.equals(srcFile)
5480                && ps.timeStamp == srcFile.lastModified()
5481                && !isCompatSignatureUpdateNeeded(pkg)
5482                && !isRecoverSignatureUpdateNeeded(pkg)) {
5483            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5484            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5485            ArraySet<PublicKey> signingKs;
5486            synchronized (mPackages) {
5487                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5488            }
5489            if (ps.signatures.mSignatures != null
5490                    && ps.signatures.mSignatures.length != 0
5491                    && signingKs != null) {
5492                // Optimization: reuse the existing cached certificates
5493                // if the package appears to be unchanged.
5494                pkg.mSignatures = ps.signatures.mSignatures;
5495                pkg.mSigningKeys = signingKs;
5496                return;
5497            }
5498
5499            Slog.w(TAG, "PackageSetting for " + ps.name
5500                    + " is missing signatures.  Collecting certs again to recover them.");
5501        } else {
5502            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5503        }
5504
5505        try {
5506            pp.collectCertificates(pkg, parseFlags);
5507            pp.collectManifestDigest(pkg);
5508        } catch (PackageParserException e) {
5509            throw PackageManagerException.from(e);
5510        }
5511    }
5512
5513    /*
5514     *  Scan a package and return the newly parsed package.
5515     *  Returns null in case of errors and the error code is stored in mLastScanError
5516     */
5517    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5518            long currentTime, UserHandle user) throws PackageManagerException {
5519        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5520        parseFlags |= mDefParseFlags;
5521        PackageParser pp = new PackageParser();
5522        pp.setSeparateProcesses(mSeparateProcesses);
5523        pp.setOnlyCoreApps(mOnlyCore);
5524        pp.setDisplayMetrics(mMetrics);
5525
5526        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5527            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5528        }
5529
5530        final PackageParser.Package pkg;
5531        try {
5532            pkg = pp.parsePackage(scanFile, parseFlags);
5533        } catch (PackageParserException e) {
5534            throw PackageManagerException.from(e);
5535        }
5536
5537        PackageSetting ps = null;
5538        PackageSetting updatedPkg;
5539        // reader
5540        synchronized (mPackages) {
5541            // Look to see if we already know about this package.
5542            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5543            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5544                // This package has been renamed to its original name.  Let's
5545                // use that.
5546                ps = mSettings.peekPackageLPr(oldName);
5547            }
5548            // If there was no original package, see one for the real package name.
5549            if (ps == null) {
5550                ps = mSettings.peekPackageLPr(pkg.packageName);
5551            }
5552            // Check to see if this package could be hiding/updating a system
5553            // package.  Must look for it either under the original or real
5554            // package name depending on our state.
5555            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5556            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5557        }
5558        boolean updatedPkgBetter = false;
5559        // First check if this is a system package that may involve an update
5560        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5561            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5562            // it needs to drop FLAG_PRIVILEGED.
5563            if (locationIsPrivileged(scanFile)) {
5564                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5565            } else {
5566                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5567            }
5568
5569            if (ps != null && !ps.codePath.equals(scanFile)) {
5570                // The path has changed from what was last scanned...  check the
5571                // version of the new path against what we have stored to determine
5572                // what to do.
5573                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5574                if (pkg.mVersionCode <= ps.versionCode) {
5575                    // The system package has been updated and the code path does not match
5576                    // Ignore entry. Skip it.
5577                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5578                            + " ignored: updated version " + ps.versionCode
5579                            + " better than this " + pkg.mVersionCode);
5580                    if (!updatedPkg.codePath.equals(scanFile)) {
5581                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5582                                + ps.name + " changing from " + updatedPkg.codePathString
5583                                + " to " + scanFile);
5584                        updatedPkg.codePath = scanFile;
5585                        updatedPkg.codePathString = scanFile.toString();
5586                        updatedPkg.resourcePath = scanFile;
5587                        updatedPkg.resourcePathString = scanFile.toString();
5588                    }
5589                    updatedPkg.pkg = pkg;
5590                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5591                } else {
5592                    // The current app on the system partition is better than
5593                    // what we have updated to on the data partition; switch
5594                    // back to the system partition version.
5595                    // At this point, its safely assumed that package installation for
5596                    // apps in system partition will go through. If not there won't be a working
5597                    // version of the app
5598                    // writer
5599                    synchronized (mPackages) {
5600                        // Just remove the loaded entries from package lists.
5601                        mPackages.remove(ps.name);
5602                    }
5603
5604                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5605                            + " reverting from " + ps.codePathString
5606                            + ": new version " + pkg.mVersionCode
5607                            + " better than installed " + ps.versionCode);
5608
5609                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5610                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5611                    synchronized (mInstallLock) {
5612                        args.cleanUpResourcesLI();
5613                    }
5614                    synchronized (mPackages) {
5615                        mSettings.enableSystemPackageLPw(ps.name);
5616                    }
5617                    updatedPkgBetter = true;
5618                }
5619            }
5620        }
5621
5622        if (updatedPkg != null) {
5623            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5624            // initially
5625            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5626
5627            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5628            // flag set initially
5629            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5630                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5631            }
5632        }
5633
5634        // Verify certificates against what was last scanned
5635        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5636
5637        /*
5638         * A new system app appeared, but we already had a non-system one of the
5639         * same name installed earlier.
5640         */
5641        boolean shouldHideSystemApp = false;
5642        if (updatedPkg == null && ps != null
5643                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5644            /*
5645             * Check to make sure the signatures match first. If they don't,
5646             * wipe the installed application and its data.
5647             */
5648            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5649                    != PackageManager.SIGNATURE_MATCH) {
5650                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5651                        + " signatures don't match existing userdata copy; removing");
5652                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5653                ps = null;
5654            } else {
5655                /*
5656                 * If the newly-added system app is an older version than the
5657                 * already installed version, hide it. It will be scanned later
5658                 * and re-added like an update.
5659                 */
5660                if (pkg.mVersionCode <= ps.versionCode) {
5661                    shouldHideSystemApp = true;
5662                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5663                            + " but new version " + pkg.mVersionCode + " better than installed "
5664                            + ps.versionCode + "; hiding system");
5665                } else {
5666                    /*
5667                     * The newly found system app is a newer version that the
5668                     * one previously installed. Simply remove the
5669                     * already-installed application and replace it with our own
5670                     * while keeping the application data.
5671                     */
5672                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5673                            + " reverting from " + ps.codePathString + ": new version "
5674                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5675                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5676                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5677                    synchronized (mInstallLock) {
5678                        args.cleanUpResourcesLI();
5679                    }
5680                }
5681            }
5682        }
5683
5684        // The apk is forward locked (not public) if its code and resources
5685        // are kept in different files. (except for app in either system or
5686        // vendor path).
5687        // TODO grab this value from PackageSettings
5688        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5689            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5690                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5691            }
5692        }
5693
5694        // TODO: extend to support forward-locked splits
5695        String resourcePath = null;
5696        String baseResourcePath = null;
5697        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5698            if (ps != null && ps.resourcePathString != null) {
5699                resourcePath = ps.resourcePathString;
5700                baseResourcePath = ps.resourcePathString;
5701            } else {
5702                // Should not happen at all. Just log an error.
5703                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5704            }
5705        } else {
5706            resourcePath = pkg.codePath;
5707            baseResourcePath = pkg.baseCodePath;
5708        }
5709
5710        // Set application objects path explicitly.
5711        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5712        pkg.applicationInfo.setCodePath(pkg.codePath);
5713        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5714        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5715        pkg.applicationInfo.setResourcePath(resourcePath);
5716        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5717        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5718
5719        // Note that we invoke the following method only if we are about to unpack an application
5720        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5721                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5722
5723        /*
5724         * If the system app should be overridden by a previously installed
5725         * data, hide the system app now and let the /data/app scan pick it up
5726         * again.
5727         */
5728        if (shouldHideSystemApp) {
5729            synchronized (mPackages) {
5730                /*
5731                 * We have to grant systems permissions before we hide, because
5732                 * grantPermissions will assume the package update is trying to
5733                 * expand its permissions.
5734                 */
5735                grantPermissionsLPw(pkg, true, pkg.packageName);
5736                mSettings.disableSystemPackageLPw(pkg.packageName);
5737            }
5738        }
5739
5740        return scannedPkg;
5741    }
5742
5743    private static String fixProcessName(String defProcessName,
5744            String processName, int uid) {
5745        if (processName == null) {
5746            return defProcessName;
5747        }
5748        return processName;
5749    }
5750
5751    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5752            throws PackageManagerException {
5753        if (pkgSetting.signatures.mSignatures != null) {
5754            // Already existing package. Make sure signatures match
5755            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5756                    == PackageManager.SIGNATURE_MATCH;
5757            if (!match) {
5758                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5759                        == PackageManager.SIGNATURE_MATCH;
5760            }
5761            if (!match) {
5762                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5763                        == PackageManager.SIGNATURE_MATCH;
5764            }
5765            if (!match) {
5766                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5767                        + pkg.packageName + " signatures do not match the "
5768                        + "previously installed version; ignoring!");
5769            }
5770        }
5771
5772        // Check for shared user signatures
5773        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5774            // Already existing package. Make sure signatures match
5775            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5776                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5777            if (!match) {
5778                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5779                        == PackageManager.SIGNATURE_MATCH;
5780            }
5781            if (!match) {
5782                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5783                        == PackageManager.SIGNATURE_MATCH;
5784            }
5785            if (!match) {
5786                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5787                        "Package " + pkg.packageName
5788                        + " has no signatures that match those in shared user "
5789                        + pkgSetting.sharedUser.name + "; ignoring!");
5790            }
5791        }
5792    }
5793
5794    /**
5795     * Enforces that only the system UID or root's UID can call a method exposed
5796     * via Binder.
5797     *
5798     * @param message used as message if SecurityException is thrown
5799     * @throws SecurityException if the caller is not system or root
5800     */
5801    private static final void enforceSystemOrRoot(String message) {
5802        final int uid = Binder.getCallingUid();
5803        if (uid != Process.SYSTEM_UID && uid != 0) {
5804            throw new SecurityException(message);
5805        }
5806    }
5807
5808    @Override
5809    public void performBootDexOpt() {
5810        enforceSystemOrRoot("Only the system can request dexopt be performed");
5811
5812        // Before everything else, see whether we need to fstrim.
5813        try {
5814            IMountService ms = PackageHelper.getMountService();
5815            if (ms != null) {
5816                final boolean isUpgrade = isUpgrade();
5817                boolean doTrim = isUpgrade;
5818                if (doTrim) {
5819                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5820                } else {
5821                    final long interval = android.provider.Settings.Global.getLong(
5822                            mContext.getContentResolver(),
5823                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5824                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5825                    if (interval > 0) {
5826                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5827                        if (timeSinceLast > interval) {
5828                            doTrim = true;
5829                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5830                                    + "; running immediately");
5831                        }
5832                    }
5833                }
5834                if (doTrim) {
5835                    if (!isFirstBoot()) {
5836                        try {
5837                            ActivityManagerNative.getDefault().showBootMessage(
5838                                    mContext.getResources().getString(
5839                                            R.string.android_upgrading_fstrim), true);
5840                        } catch (RemoteException e) {
5841                        }
5842                    }
5843                    ms.runMaintenance();
5844                }
5845            } else {
5846                Slog.e(TAG, "Mount service unavailable!");
5847            }
5848        } catch (RemoteException e) {
5849            // Can't happen; MountService is local
5850        }
5851
5852        final ArraySet<PackageParser.Package> pkgs;
5853        synchronized (mPackages) {
5854            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5855        }
5856
5857        if (pkgs != null) {
5858            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5859            // in case the device runs out of space.
5860            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5861            // Give priority to core apps.
5862            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5863                PackageParser.Package pkg = it.next();
5864                if (pkg.coreApp) {
5865                    if (DEBUG_DEXOPT) {
5866                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5867                    }
5868                    sortedPkgs.add(pkg);
5869                    it.remove();
5870                }
5871            }
5872            // Give priority to system apps that listen for pre boot complete.
5873            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5874            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5875            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5876                PackageParser.Package pkg = it.next();
5877                if (pkgNames.contains(pkg.packageName)) {
5878                    if (DEBUG_DEXOPT) {
5879                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5880                    }
5881                    sortedPkgs.add(pkg);
5882                    it.remove();
5883                }
5884            }
5885            // Give priority to system apps.
5886            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5887                PackageParser.Package pkg = it.next();
5888                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5889                    if (DEBUG_DEXOPT) {
5890                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5891                    }
5892                    sortedPkgs.add(pkg);
5893                    it.remove();
5894                }
5895            }
5896            // Give priority to updated system apps.
5897            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5898                PackageParser.Package pkg = it.next();
5899                if (pkg.isUpdatedSystemApp()) {
5900                    if (DEBUG_DEXOPT) {
5901                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5902                    }
5903                    sortedPkgs.add(pkg);
5904                    it.remove();
5905                }
5906            }
5907            // Give priority to apps that listen for boot complete.
5908            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5909            pkgNames = getPackageNamesForIntent(intent);
5910            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5911                PackageParser.Package pkg = it.next();
5912                if (pkgNames.contains(pkg.packageName)) {
5913                    if (DEBUG_DEXOPT) {
5914                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5915                    }
5916                    sortedPkgs.add(pkg);
5917                    it.remove();
5918                }
5919            }
5920            // Filter out packages that aren't recently used.
5921            filterRecentlyUsedApps(pkgs);
5922            // Add all remaining apps.
5923            for (PackageParser.Package pkg : pkgs) {
5924                if (DEBUG_DEXOPT) {
5925                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5926                }
5927                sortedPkgs.add(pkg);
5928            }
5929
5930            // If we want to be lazy, filter everything that wasn't recently used.
5931            if (mLazyDexOpt) {
5932                filterRecentlyUsedApps(sortedPkgs);
5933            }
5934
5935            int i = 0;
5936            int total = sortedPkgs.size();
5937            File dataDir = Environment.getDataDirectory();
5938            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5939            if (lowThreshold == 0) {
5940                throw new IllegalStateException("Invalid low memory threshold");
5941            }
5942            for (PackageParser.Package pkg : sortedPkgs) {
5943                long usableSpace = dataDir.getUsableSpace();
5944                if (usableSpace < lowThreshold) {
5945                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5946                    break;
5947                }
5948                performBootDexOpt(pkg, ++i, total);
5949            }
5950        }
5951    }
5952
5953    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5954        // Filter out packages that aren't recently used.
5955        //
5956        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5957        // should do a full dexopt.
5958        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5959            int total = pkgs.size();
5960            int skipped = 0;
5961            long now = System.currentTimeMillis();
5962            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5963                PackageParser.Package pkg = i.next();
5964                long then = pkg.mLastPackageUsageTimeInMills;
5965                if (then + mDexOptLRUThresholdInMills < now) {
5966                    if (DEBUG_DEXOPT) {
5967                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5968                              ((then == 0) ? "never" : new Date(then)));
5969                    }
5970                    i.remove();
5971                    skipped++;
5972                }
5973            }
5974            if (DEBUG_DEXOPT) {
5975                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5976            }
5977        }
5978    }
5979
5980    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5981        List<ResolveInfo> ris = null;
5982        try {
5983            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5984                    intent, null, 0, UserHandle.USER_OWNER);
5985        } catch (RemoteException e) {
5986        }
5987        ArraySet<String> pkgNames = new ArraySet<String>();
5988        if (ris != null) {
5989            for (ResolveInfo ri : ris) {
5990                pkgNames.add(ri.activityInfo.packageName);
5991            }
5992        }
5993        return pkgNames;
5994    }
5995
5996    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5997        if (DEBUG_DEXOPT) {
5998            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5999        }
6000        if (!isFirstBoot()) {
6001            try {
6002                ActivityManagerNative.getDefault().showBootMessage(
6003                        mContext.getResources().getString(R.string.android_upgrading_apk,
6004                                curr, total), true);
6005            } catch (RemoteException e) {
6006            }
6007        }
6008        PackageParser.Package p = pkg;
6009        synchronized (mInstallLock) {
6010            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6011                    false /* force dex */, false /* defer */, true /* include dependencies */);
6012        }
6013    }
6014
6015    @Override
6016    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6017        return performDexOpt(packageName, instructionSet, false);
6018    }
6019
6020    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6021        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6022        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6023        if (!dexopt && !updateUsage) {
6024            // We aren't going to dexopt or update usage, so bail early.
6025            return false;
6026        }
6027        PackageParser.Package p;
6028        final String targetInstructionSet;
6029        synchronized (mPackages) {
6030            p = mPackages.get(packageName);
6031            if (p == null) {
6032                return false;
6033            }
6034            if (updateUsage) {
6035                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6036            }
6037            mPackageUsage.write(false);
6038            if (!dexopt) {
6039                // We aren't going to dexopt, so bail early.
6040                return false;
6041            }
6042
6043            targetInstructionSet = instructionSet != null ? instructionSet :
6044                    getPrimaryInstructionSet(p.applicationInfo);
6045            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6046                return false;
6047            }
6048        }
6049
6050        synchronized (mInstallLock) {
6051            final String[] instructionSets = new String[] { targetInstructionSet };
6052            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6053                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6054            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6055        }
6056    }
6057
6058    public ArraySet<String> getPackagesThatNeedDexOpt() {
6059        ArraySet<String> pkgs = null;
6060        synchronized (mPackages) {
6061            for (PackageParser.Package p : mPackages.values()) {
6062                if (DEBUG_DEXOPT) {
6063                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6064                }
6065                if (!p.mDexOptPerformed.isEmpty()) {
6066                    continue;
6067                }
6068                if (pkgs == null) {
6069                    pkgs = new ArraySet<String>();
6070                }
6071                pkgs.add(p.packageName);
6072            }
6073        }
6074        return pkgs;
6075    }
6076
6077    public void shutdown() {
6078        mPackageUsage.write(true);
6079    }
6080
6081    @Override
6082    public void forceDexOpt(String packageName) {
6083        enforceSystemOrRoot("forceDexOpt");
6084
6085        PackageParser.Package pkg;
6086        synchronized (mPackages) {
6087            pkg = mPackages.get(packageName);
6088            if (pkg == null) {
6089                throw new IllegalArgumentException("Missing package: " + packageName);
6090            }
6091        }
6092
6093        synchronized (mInstallLock) {
6094            final String[] instructionSets = new String[] {
6095                    getPrimaryInstructionSet(pkg.applicationInfo) };
6096            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6097                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6098            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6099                throw new IllegalStateException("Failed to dexopt: " + res);
6100            }
6101        }
6102    }
6103
6104    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6105        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6106            Slog.w(TAG, "Unable to update from " + oldPkg.name
6107                    + " to " + newPkg.packageName
6108                    + ": old package not in system partition");
6109            return false;
6110        } else if (mPackages.get(oldPkg.name) != null) {
6111            Slog.w(TAG, "Unable to update from " + oldPkg.name
6112                    + " to " + newPkg.packageName
6113                    + ": old package still exists");
6114            return false;
6115        }
6116        return true;
6117    }
6118
6119    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6120        int[] users = sUserManager.getUserIds();
6121        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6122        if (res < 0) {
6123            return res;
6124        }
6125        for (int user : users) {
6126            if (user != 0) {
6127                res = mInstaller.createUserData(volumeUuid, packageName,
6128                        UserHandle.getUid(user, uid), user, seinfo);
6129                if (res < 0) {
6130                    return res;
6131                }
6132            }
6133        }
6134        return res;
6135    }
6136
6137    private int removeDataDirsLI(String volumeUuid, String packageName) {
6138        int[] users = sUserManager.getUserIds();
6139        int res = 0;
6140        for (int user : users) {
6141            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6142            if (resInner < 0) {
6143                res = resInner;
6144            }
6145        }
6146
6147        return res;
6148    }
6149
6150    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6151        int[] users = sUserManager.getUserIds();
6152        int res = 0;
6153        for (int user : users) {
6154            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6155            if (resInner < 0) {
6156                res = resInner;
6157            }
6158        }
6159        return res;
6160    }
6161
6162    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6163            PackageParser.Package changingLib) {
6164        if (file.path != null) {
6165            usesLibraryFiles.add(file.path);
6166            return;
6167        }
6168        PackageParser.Package p = mPackages.get(file.apk);
6169        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6170            // If we are doing this while in the middle of updating a library apk,
6171            // then we need to make sure to use that new apk for determining the
6172            // dependencies here.  (We haven't yet finished committing the new apk
6173            // to the package manager state.)
6174            if (p == null || p.packageName.equals(changingLib.packageName)) {
6175                p = changingLib;
6176            }
6177        }
6178        if (p != null) {
6179            usesLibraryFiles.addAll(p.getAllCodePaths());
6180        }
6181    }
6182
6183    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6184            PackageParser.Package changingLib) throws PackageManagerException {
6185        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6186            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6187            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6188            for (int i=0; i<N; i++) {
6189                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6190                if (file == null) {
6191                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6192                            "Package " + pkg.packageName + " requires unavailable shared library "
6193                            + pkg.usesLibraries.get(i) + "; failing!");
6194                }
6195                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6196            }
6197            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6198            for (int i=0; i<N; i++) {
6199                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6200                if (file == null) {
6201                    Slog.w(TAG, "Package " + pkg.packageName
6202                            + " desires unavailable shared library "
6203                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6204                } else {
6205                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6206                }
6207            }
6208            N = usesLibraryFiles.size();
6209            if (N > 0) {
6210                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6211            } else {
6212                pkg.usesLibraryFiles = null;
6213            }
6214        }
6215    }
6216
6217    private static boolean hasString(List<String> list, List<String> which) {
6218        if (list == null) {
6219            return false;
6220        }
6221        for (int i=list.size()-1; i>=0; i--) {
6222            for (int j=which.size()-1; j>=0; j--) {
6223                if (which.get(j).equals(list.get(i))) {
6224                    return true;
6225                }
6226            }
6227        }
6228        return false;
6229    }
6230
6231    private void updateAllSharedLibrariesLPw() {
6232        for (PackageParser.Package pkg : mPackages.values()) {
6233            try {
6234                updateSharedLibrariesLPw(pkg, null);
6235            } catch (PackageManagerException e) {
6236                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6237            }
6238        }
6239    }
6240
6241    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6242            PackageParser.Package changingPkg) {
6243        ArrayList<PackageParser.Package> res = null;
6244        for (PackageParser.Package pkg : mPackages.values()) {
6245            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6246                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6247                if (res == null) {
6248                    res = new ArrayList<PackageParser.Package>();
6249                }
6250                res.add(pkg);
6251                try {
6252                    updateSharedLibrariesLPw(pkg, changingPkg);
6253                } catch (PackageManagerException e) {
6254                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6255                }
6256            }
6257        }
6258        return res;
6259    }
6260
6261    /**
6262     * Derive the value of the {@code cpuAbiOverride} based on the provided
6263     * value and an optional stored value from the package settings.
6264     */
6265    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6266        String cpuAbiOverride = null;
6267
6268        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6269            cpuAbiOverride = null;
6270        } else if (abiOverride != null) {
6271            cpuAbiOverride = abiOverride;
6272        } else if (settings != null) {
6273            cpuAbiOverride = settings.cpuAbiOverrideString;
6274        }
6275
6276        return cpuAbiOverride;
6277    }
6278
6279    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6280            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6281        boolean success = false;
6282        try {
6283            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6284                    currentTime, user);
6285            success = true;
6286            return res;
6287        } finally {
6288            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6289                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6290            }
6291        }
6292    }
6293
6294    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6295            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6296        final File scanFile = new File(pkg.codePath);
6297        if (pkg.applicationInfo.getCodePath() == null ||
6298                pkg.applicationInfo.getResourcePath() == null) {
6299            // Bail out. The resource and code paths haven't been set.
6300            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6301                    "Code and resource paths haven't been set correctly");
6302        }
6303
6304        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6305            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6306        } else {
6307            // Only allow system apps to be flagged as core apps.
6308            pkg.coreApp = false;
6309        }
6310
6311        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6312            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6313        }
6314
6315        if (mCustomResolverComponentName != null &&
6316                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6317            setUpCustomResolverActivity(pkg);
6318        }
6319
6320        if (pkg.packageName.equals("android")) {
6321            synchronized (mPackages) {
6322                if (mAndroidApplication != null) {
6323                    Slog.w(TAG, "*************************************************");
6324                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6325                    Slog.w(TAG, " file=" + scanFile);
6326                    Slog.w(TAG, "*************************************************");
6327                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6328                            "Core android package being redefined.  Skipping.");
6329                }
6330
6331                // Set up information for our fall-back user intent resolution activity.
6332                mPlatformPackage = pkg;
6333                pkg.mVersionCode = mSdkVersion;
6334                mAndroidApplication = pkg.applicationInfo;
6335
6336                if (!mResolverReplaced) {
6337                    mResolveActivity.applicationInfo = mAndroidApplication;
6338                    mResolveActivity.name = ResolverActivity.class.getName();
6339                    mResolveActivity.packageName = mAndroidApplication.packageName;
6340                    mResolveActivity.processName = "system:ui";
6341                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6342                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6343                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6344                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6345                    mResolveActivity.exported = true;
6346                    mResolveActivity.enabled = true;
6347                    mResolveInfo.activityInfo = mResolveActivity;
6348                    mResolveInfo.priority = 0;
6349                    mResolveInfo.preferredOrder = 0;
6350                    mResolveInfo.match = 0;
6351                    mResolveComponentName = new ComponentName(
6352                            mAndroidApplication.packageName, mResolveActivity.name);
6353                }
6354            }
6355        }
6356
6357        if (DEBUG_PACKAGE_SCANNING) {
6358            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6359                Log.d(TAG, "Scanning package " + pkg.packageName);
6360        }
6361
6362        if (mPackages.containsKey(pkg.packageName)
6363                || mSharedLibraries.containsKey(pkg.packageName)) {
6364            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6365                    "Application package " + pkg.packageName
6366                    + " already installed.  Skipping duplicate.");
6367        }
6368
6369        // If we're only installing presumed-existing packages, require that the
6370        // scanned APK is both already known and at the path previously established
6371        // for it.  Previously unknown packages we pick up normally, but if we have an
6372        // a priori expectation about this package's install presence, enforce it.
6373        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6374            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6375            if (known != null) {
6376                if (DEBUG_PACKAGE_SCANNING) {
6377                    Log.d(TAG, "Examining " + pkg.codePath
6378                            + " and requiring known paths " + known.codePathString
6379                            + " & " + known.resourcePathString);
6380                }
6381                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6382                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6383                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6384                            "Application package " + pkg.packageName
6385                            + " found at " + pkg.applicationInfo.getCodePath()
6386                            + " but expected at " + known.codePathString + "; ignoring.");
6387                }
6388            }
6389        }
6390
6391        // Initialize package source and resource directories
6392        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6393        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6394
6395        SharedUserSetting suid = null;
6396        PackageSetting pkgSetting = null;
6397
6398        if (!isSystemApp(pkg)) {
6399            // Only system apps can use these features.
6400            pkg.mOriginalPackages = null;
6401            pkg.mRealPackage = null;
6402            pkg.mAdoptPermissions = null;
6403        }
6404
6405        // writer
6406        synchronized (mPackages) {
6407            if (pkg.mSharedUserId != null) {
6408                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6409                if (suid == null) {
6410                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6411                            "Creating application package " + pkg.packageName
6412                            + " for shared user failed");
6413                }
6414                if (DEBUG_PACKAGE_SCANNING) {
6415                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6416                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6417                                + "): packages=" + suid.packages);
6418                }
6419            }
6420
6421            // Check if we are renaming from an original package name.
6422            PackageSetting origPackage = null;
6423            String realName = null;
6424            if (pkg.mOriginalPackages != null) {
6425                // This package may need to be renamed to a previously
6426                // installed name.  Let's check on that...
6427                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6428                if (pkg.mOriginalPackages.contains(renamed)) {
6429                    // This package had originally been installed as the
6430                    // original name, and we have already taken care of
6431                    // transitioning to the new one.  Just update the new
6432                    // one to continue using the old name.
6433                    realName = pkg.mRealPackage;
6434                    if (!pkg.packageName.equals(renamed)) {
6435                        // Callers into this function may have already taken
6436                        // care of renaming the package; only do it here if
6437                        // it is not already done.
6438                        pkg.setPackageName(renamed);
6439                    }
6440
6441                } else {
6442                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6443                        if ((origPackage = mSettings.peekPackageLPr(
6444                                pkg.mOriginalPackages.get(i))) != null) {
6445                            // We do have the package already installed under its
6446                            // original name...  should we use it?
6447                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6448                                // New package is not compatible with original.
6449                                origPackage = null;
6450                                continue;
6451                            } else if (origPackage.sharedUser != null) {
6452                                // Make sure uid is compatible between packages.
6453                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6454                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6455                                            + " to " + pkg.packageName + ": old uid "
6456                                            + origPackage.sharedUser.name
6457                                            + " differs from " + pkg.mSharedUserId);
6458                                    origPackage = null;
6459                                    continue;
6460                                }
6461                            } else {
6462                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6463                                        + pkg.packageName + " to old name " + origPackage.name);
6464                            }
6465                            break;
6466                        }
6467                    }
6468                }
6469            }
6470
6471            if (mTransferedPackages.contains(pkg.packageName)) {
6472                Slog.w(TAG, "Package " + pkg.packageName
6473                        + " was transferred to another, but its .apk remains");
6474            }
6475
6476            // Just create the setting, don't add it yet. For already existing packages
6477            // the PkgSetting exists already and doesn't have to be created.
6478            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6479                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6480                    pkg.applicationInfo.primaryCpuAbi,
6481                    pkg.applicationInfo.secondaryCpuAbi,
6482                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6483                    user, false);
6484            if (pkgSetting == null) {
6485                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6486                        "Creating application package " + pkg.packageName + " failed");
6487            }
6488
6489            if (pkgSetting.origPackage != null) {
6490                // If we are first transitioning from an original package,
6491                // fix up the new package's name now.  We need to do this after
6492                // looking up the package under its new name, so getPackageLP
6493                // can take care of fiddling things correctly.
6494                pkg.setPackageName(origPackage.name);
6495
6496                // File a report about this.
6497                String msg = "New package " + pkgSetting.realName
6498                        + " renamed to replace old package " + pkgSetting.name;
6499                reportSettingsProblem(Log.WARN, msg);
6500
6501                // Make a note of it.
6502                mTransferedPackages.add(origPackage.name);
6503
6504                // No longer need to retain this.
6505                pkgSetting.origPackage = null;
6506            }
6507
6508            if (realName != null) {
6509                // Make a note of it.
6510                mTransferedPackages.add(pkg.packageName);
6511            }
6512
6513            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6514                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6515            }
6516
6517            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6518                // Check all shared libraries and map to their actual file path.
6519                // We only do this here for apps not on a system dir, because those
6520                // are the only ones that can fail an install due to this.  We
6521                // will take care of the system apps by updating all of their
6522                // library paths after the scan is done.
6523                updateSharedLibrariesLPw(pkg, null);
6524            }
6525
6526            if (mFoundPolicyFile) {
6527                SELinuxMMAC.assignSeinfoValue(pkg);
6528            }
6529
6530            pkg.applicationInfo.uid = pkgSetting.appId;
6531            pkg.mExtras = pkgSetting;
6532            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6533                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6534                    // We just determined the app is signed correctly, so bring
6535                    // over the latest parsed certs.
6536                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6537                } else {
6538                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6539                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6540                                "Package " + pkg.packageName + " upgrade keys do not match the "
6541                                + "previously installed version");
6542                    } else {
6543                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6544                        String msg = "System package " + pkg.packageName
6545                            + " signature changed; retaining data.";
6546                        reportSettingsProblem(Log.WARN, msg);
6547                    }
6548                }
6549            } else {
6550                try {
6551                    verifySignaturesLP(pkgSetting, pkg);
6552                    // We just determined the app is signed correctly, so bring
6553                    // over the latest parsed certs.
6554                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6555                } catch (PackageManagerException e) {
6556                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6557                        throw e;
6558                    }
6559                    // The signature has changed, but this package is in the system
6560                    // image...  let's recover!
6561                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6562                    // However...  if this package is part of a shared user, but it
6563                    // doesn't match the signature of the shared user, let's fail.
6564                    // What this means is that you can't change the signatures
6565                    // associated with an overall shared user, which doesn't seem all
6566                    // that unreasonable.
6567                    if (pkgSetting.sharedUser != null) {
6568                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6569                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6570                            throw new PackageManagerException(
6571                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6572                                            "Signature mismatch for shared user : "
6573                                            + pkgSetting.sharedUser);
6574                        }
6575                    }
6576                    // File a report about this.
6577                    String msg = "System package " + pkg.packageName
6578                        + " signature changed; retaining data.";
6579                    reportSettingsProblem(Log.WARN, msg);
6580                }
6581            }
6582            // Verify that this new package doesn't have any content providers
6583            // that conflict with existing packages.  Only do this if the
6584            // package isn't already installed, since we don't want to break
6585            // things that are installed.
6586            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6587                final int N = pkg.providers.size();
6588                int i;
6589                for (i=0; i<N; i++) {
6590                    PackageParser.Provider p = pkg.providers.get(i);
6591                    if (p.info.authority != null) {
6592                        String names[] = p.info.authority.split(";");
6593                        for (int j = 0; j < names.length; j++) {
6594                            if (mProvidersByAuthority.containsKey(names[j])) {
6595                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6596                                final String otherPackageName =
6597                                        ((other != null && other.getComponentName() != null) ?
6598                                                other.getComponentName().getPackageName() : "?");
6599                                throw new PackageManagerException(
6600                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6601                                                "Can't install because provider name " + names[j]
6602                                                + " (in package " + pkg.applicationInfo.packageName
6603                                                + ") is already used by " + otherPackageName);
6604                            }
6605                        }
6606                    }
6607                }
6608            }
6609
6610            if (pkg.mAdoptPermissions != null) {
6611                // This package wants to adopt ownership of permissions from
6612                // another package.
6613                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6614                    final String origName = pkg.mAdoptPermissions.get(i);
6615                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6616                    if (orig != null) {
6617                        if (verifyPackageUpdateLPr(orig, pkg)) {
6618                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6619                                    + pkg.packageName);
6620                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6621                        }
6622                    }
6623                }
6624            }
6625        }
6626
6627        final String pkgName = pkg.packageName;
6628
6629        final long scanFileTime = scanFile.lastModified();
6630        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6631        pkg.applicationInfo.processName = fixProcessName(
6632                pkg.applicationInfo.packageName,
6633                pkg.applicationInfo.processName,
6634                pkg.applicationInfo.uid);
6635
6636        File dataPath;
6637        if (mPlatformPackage == pkg) {
6638            // The system package is special.
6639            dataPath = new File(Environment.getDataDirectory(), "system");
6640
6641            pkg.applicationInfo.dataDir = dataPath.getPath();
6642
6643        } else {
6644            // This is a normal package, need to make its data directory.
6645            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6646                    UserHandle.USER_OWNER, pkg.packageName);
6647
6648            boolean uidError = false;
6649            if (dataPath.exists()) {
6650                int currentUid = 0;
6651                try {
6652                    StructStat stat = Os.stat(dataPath.getPath());
6653                    currentUid = stat.st_uid;
6654                } catch (ErrnoException e) {
6655                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6656                }
6657
6658                // If we have mismatched owners for the data path, we have a problem.
6659                if (currentUid != pkg.applicationInfo.uid) {
6660                    boolean recovered = false;
6661                    if (currentUid == 0) {
6662                        // The directory somehow became owned by root.  Wow.
6663                        // This is probably because the system was stopped while
6664                        // installd was in the middle of messing with its libs
6665                        // directory.  Ask installd to fix that.
6666                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6667                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6668                        if (ret >= 0) {
6669                            recovered = true;
6670                            String msg = "Package " + pkg.packageName
6671                                    + " unexpectedly changed to uid 0; recovered to " +
6672                                    + pkg.applicationInfo.uid;
6673                            reportSettingsProblem(Log.WARN, msg);
6674                        }
6675                    }
6676                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6677                            || (scanFlags&SCAN_BOOTING) != 0)) {
6678                        // If this is a system app, we can at least delete its
6679                        // current data so the application will still work.
6680                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6681                        if (ret >= 0) {
6682                            // TODO: Kill the processes first
6683                            // Old data gone!
6684                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6685                                    ? "System package " : "Third party package ";
6686                            String msg = prefix + pkg.packageName
6687                                    + " has changed from uid: "
6688                                    + currentUid + " to "
6689                                    + pkg.applicationInfo.uid + "; old data erased";
6690                            reportSettingsProblem(Log.WARN, msg);
6691                            recovered = true;
6692
6693                            // And now re-install the app.
6694                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6695                                    pkg.applicationInfo.seinfo);
6696                            if (ret == -1) {
6697                                // Ack should not happen!
6698                                msg = prefix + pkg.packageName
6699                                        + " could not have data directory re-created after delete.";
6700                                reportSettingsProblem(Log.WARN, msg);
6701                                throw new PackageManagerException(
6702                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6703                            }
6704                        }
6705                        if (!recovered) {
6706                            mHasSystemUidErrors = true;
6707                        }
6708                    } else if (!recovered) {
6709                        // If we allow this install to proceed, we will be broken.
6710                        // Abort, abort!
6711                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6712                                "scanPackageLI");
6713                    }
6714                    if (!recovered) {
6715                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6716                            + pkg.applicationInfo.uid + "/fs_"
6717                            + currentUid;
6718                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6719                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6720                        String msg = "Package " + pkg.packageName
6721                                + " has mismatched uid: "
6722                                + currentUid + " on disk, "
6723                                + pkg.applicationInfo.uid + " in settings";
6724                        // writer
6725                        synchronized (mPackages) {
6726                            mSettings.mReadMessages.append(msg);
6727                            mSettings.mReadMessages.append('\n');
6728                            uidError = true;
6729                            if (!pkgSetting.uidError) {
6730                                reportSettingsProblem(Log.ERROR, msg);
6731                            }
6732                        }
6733                    }
6734                }
6735                pkg.applicationInfo.dataDir = dataPath.getPath();
6736                if (mShouldRestoreconData) {
6737                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6738                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6739                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6740                }
6741            } else {
6742                if (DEBUG_PACKAGE_SCANNING) {
6743                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6744                        Log.v(TAG, "Want this data dir: " + dataPath);
6745                }
6746                //invoke installer to do the actual installation
6747                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6748                        pkg.applicationInfo.seinfo);
6749                if (ret < 0) {
6750                    // Error from installer
6751                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6752                            "Unable to create data dirs [errorCode=" + ret + "]");
6753                }
6754
6755                if (dataPath.exists()) {
6756                    pkg.applicationInfo.dataDir = dataPath.getPath();
6757                } else {
6758                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6759                    pkg.applicationInfo.dataDir = null;
6760                }
6761            }
6762
6763            pkgSetting.uidError = uidError;
6764        }
6765
6766        final String path = scanFile.getPath();
6767        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6768
6769        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6770            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6771
6772            // Some system apps still use directory structure for native libraries
6773            // in which case we might end up not detecting abi solely based on apk
6774            // structure. Try to detect abi based on directory structure.
6775            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6776                    pkg.applicationInfo.primaryCpuAbi == null) {
6777                setBundledAppAbisAndRoots(pkg, pkgSetting);
6778                setNativeLibraryPaths(pkg);
6779            }
6780
6781        } else {
6782            if ((scanFlags & SCAN_MOVE) != 0) {
6783                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6784                // but we already have this packages package info in the PackageSetting. We just
6785                // use that and derive the native library path based on the new codepath.
6786                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6787                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6788            }
6789
6790            // Set native library paths again. For moves, the path will be updated based on the
6791            // ABIs we've determined above. For non-moves, the path will be updated based on the
6792            // ABIs we determined during compilation, but the path will depend on the final
6793            // package path (after the rename away from the stage path).
6794            setNativeLibraryPaths(pkg);
6795        }
6796
6797        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6798        final int[] userIds = sUserManager.getUserIds();
6799        synchronized (mInstallLock) {
6800            // Make sure all user data directories are ready to roll; we're okay
6801            // if they already exist
6802            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6803                for (int userId : userIds) {
6804                    if (userId != 0) {
6805                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6806                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6807                                pkg.applicationInfo.seinfo);
6808                    }
6809                }
6810            }
6811
6812            // Create a native library symlink only if we have native libraries
6813            // and if the native libraries are 32 bit libraries. We do not provide
6814            // this symlink for 64 bit libraries.
6815            if (pkg.applicationInfo.primaryCpuAbi != null &&
6816                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6817                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6818                for (int userId : userIds) {
6819                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6820                            nativeLibPath, userId) < 0) {
6821                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6822                                "Failed linking native library dir (user=" + userId + ")");
6823                    }
6824                }
6825            }
6826        }
6827
6828        // This is a special case for the "system" package, where the ABI is
6829        // dictated by the zygote configuration (and init.rc). We should keep track
6830        // of this ABI so that we can deal with "normal" applications that run under
6831        // the same UID correctly.
6832        if (mPlatformPackage == pkg) {
6833            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6834                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6835        }
6836
6837        // If there's a mismatch between the abi-override in the package setting
6838        // and the abiOverride specified for the install. Warn about this because we
6839        // would've already compiled the app without taking the package setting into
6840        // account.
6841        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6842            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6843                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6844                        " for package: " + pkg.packageName);
6845            }
6846        }
6847
6848        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6849        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6850        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6851
6852        // Copy the derived override back to the parsed package, so that we can
6853        // update the package settings accordingly.
6854        pkg.cpuAbiOverride = cpuAbiOverride;
6855
6856        if (DEBUG_ABI_SELECTION) {
6857            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6858                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6859                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6860        }
6861
6862        // Push the derived path down into PackageSettings so we know what to
6863        // clean up at uninstall time.
6864        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6865
6866        if (DEBUG_ABI_SELECTION) {
6867            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6868                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6869                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6870        }
6871
6872        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6873            // We don't do this here during boot because we can do it all
6874            // at once after scanning all existing packages.
6875            //
6876            // We also do this *before* we perform dexopt on this package, so that
6877            // we can avoid redundant dexopts, and also to make sure we've got the
6878            // code and package path correct.
6879            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6880                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6881        }
6882
6883        if ((scanFlags & SCAN_NO_DEX) == 0) {
6884            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6885                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6886            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6887                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6888            }
6889        }
6890        if (mFactoryTest && pkg.requestedPermissions.contains(
6891                android.Manifest.permission.FACTORY_TEST)) {
6892            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6893        }
6894
6895        ArrayList<PackageParser.Package> clientLibPkgs = null;
6896
6897        // writer
6898        synchronized (mPackages) {
6899            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6900                // Only system apps can add new shared libraries.
6901                if (pkg.libraryNames != null) {
6902                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6903                        String name = pkg.libraryNames.get(i);
6904                        boolean allowed = false;
6905                        if (pkg.isUpdatedSystemApp()) {
6906                            // New library entries can only be added through the
6907                            // system image.  This is important to get rid of a lot
6908                            // of nasty edge cases: for example if we allowed a non-
6909                            // system update of the app to add a library, then uninstalling
6910                            // the update would make the library go away, and assumptions
6911                            // we made such as through app install filtering would now
6912                            // have allowed apps on the device which aren't compatible
6913                            // with it.  Better to just have the restriction here, be
6914                            // conservative, and create many fewer cases that can negatively
6915                            // impact the user experience.
6916                            final PackageSetting sysPs = mSettings
6917                                    .getDisabledSystemPkgLPr(pkg.packageName);
6918                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6919                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6920                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6921                                        allowed = true;
6922                                        allowed = true;
6923                                        break;
6924                                    }
6925                                }
6926                            }
6927                        } else {
6928                            allowed = true;
6929                        }
6930                        if (allowed) {
6931                            if (!mSharedLibraries.containsKey(name)) {
6932                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6933                            } else if (!name.equals(pkg.packageName)) {
6934                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6935                                        + name + " already exists; skipping");
6936                            }
6937                        } else {
6938                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6939                                    + name + " that is not declared on system image; skipping");
6940                        }
6941                    }
6942                    if ((scanFlags&SCAN_BOOTING) == 0) {
6943                        // If we are not booting, we need to update any applications
6944                        // that are clients of our shared library.  If we are booting,
6945                        // this will all be done once the scan is complete.
6946                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6947                    }
6948                }
6949            }
6950        }
6951
6952        // We also need to dexopt any apps that are dependent on this library.  Note that
6953        // if these fail, we should abort the install since installing the library will
6954        // result in some apps being broken.
6955        if (clientLibPkgs != null) {
6956            if ((scanFlags & SCAN_NO_DEX) == 0) {
6957                for (int i = 0; i < clientLibPkgs.size(); i++) {
6958                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6959                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6960                            null /* instruction sets */, forceDex,
6961                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6962                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6963                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6964                                "scanPackageLI failed to dexopt clientLibPkgs");
6965                    }
6966                }
6967            }
6968        }
6969
6970        // Also need to kill any apps that are dependent on the library.
6971        if (clientLibPkgs != null) {
6972            for (int i=0; i<clientLibPkgs.size(); i++) {
6973                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6974                killApplication(clientPkg.applicationInfo.packageName,
6975                        clientPkg.applicationInfo.uid, "update lib");
6976            }
6977        }
6978
6979        // Make sure we're not adding any bogus keyset info
6980        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6981        ksms.assertScannedPackageValid(pkg);
6982
6983        // writer
6984        synchronized (mPackages) {
6985            // We don't expect installation to fail beyond this point
6986
6987            // Add the new setting to mSettings
6988            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6989            // Add the new setting to mPackages
6990            mPackages.put(pkg.applicationInfo.packageName, pkg);
6991            // Make sure we don't accidentally delete its data.
6992            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6993            while (iter.hasNext()) {
6994                PackageCleanItem item = iter.next();
6995                if (pkgName.equals(item.packageName)) {
6996                    iter.remove();
6997                }
6998            }
6999
7000            // Take care of first install / last update times.
7001            if (currentTime != 0) {
7002                if (pkgSetting.firstInstallTime == 0) {
7003                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7004                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7005                    pkgSetting.lastUpdateTime = currentTime;
7006                }
7007            } else if (pkgSetting.firstInstallTime == 0) {
7008                // We need *something*.  Take time time stamp of the file.
7009                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7010            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7011                if (scanFileTime != pkgSetting.timeStamp) {
7012                    // A package on the system image has changed; consider this
7013                    // to be an update.
7014                    pkgSetting.lastUpdateTime = scanFileTime;
7015                }
7016            }
7017
7018            // Add the package's KeySets to the global KeySetManagerService
7019            ksms.addScannedPackageLPw(pkg);
7020
7021            int N = pkg.providers.size();
7022            StringBuilder r = null;
7023            int i;
7024            for (i=0; i<N; i++) {
7025                PackageParser.Provider p = pkg.providers.get(i);
7026                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7027                        p.info.processName, pkg.applicationInfo.uid);
7028                mProviders.addProvider(p);
7029                p.syncable = p.info.isSyncable;
7030                if (p.info.authority != null) {
7031                    String names[] = p.info.authority.split(";");
7032                    p.info.authority = null;
7033                    for (int j = 0; j < names.length; j++) {
7034                        if (j == 1 && p.syncable) {
7035                            // We only want the first authority for a provider to possibly be
7036                            // syncable, so if we already added this provider using a different
7037                            // authority clear the syncable flag. We copy the provider before
7038                            // changing it because the mProviders object contains a reference
7039                            // to a provider that we don't want to change.
7040                            // Only do this for the second authority since the resulting provider
7041                            // object can be the same for all future authorities for this provider.
7042                            p = new PackageParser.Provider(p);
7043                            p.syncable = false;
7044                        }
7045                        if (!mProvidersByAuthority.containsKey(names[j])) {
7046                            mProvidersByAuthority.put(names[j], p);
7047                            if (p.info.authority == null) {
7048                                p.info.authority = names[j];
7049                            } else {
7050                                p.info.authority = p.info.authority + ";" + names[j];
7051                            }
7052                            if (DEBUG_PACKAGE_SCANNING) {
7053                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7054                                    Log.d(TAG, "Registered content provider: " + names[j]
7055                                            + ", className = " + p.info.name + ", isSyncable = "
7056                                            + p.info.isSyncable);
7057                            }
7058                        } else {
7059                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7060                            Slog.w(TAG, "Skipping provider name " + names[j] +
7061                                    " (in package " + pkg.applicationInfo.packageName +
7062                                    "): name already used by "
7063                                    + ((other != null && other.getComponentName() != null)
7064                                            ? other.getComponentName().getPackageName() : "?"));
7065                        }
7066                    }
7067                }
7068                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7069                    if (r == null) {
7070                        r = new StringBuilder(256);
7071                    } else {
7072                        r.append(' ');
7073                    }
7074                    r.append(p.info.name);
7075                }
7076            }
7077            if (r != null) {
7078                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7079            }
7080
7081            N = pkg.services.size();
7082            r = null;
7083            for (i=0; i<N; i++) {
7084                PackageParser.Service s = pkg.services.get(i);
7085                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7086                        s.info.processName, pkg.applicationInfo.uid);
7087                mServices.addService(s);
7088                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7089                    if (r == null) {
7090                        r = new StringBuilder(256);
7091                    } else {
7092                        r.append(' ');
7093                    }
7094                    r.append(s.info.name);
7095                }
7096            }
7097            if (r != null) {
7098                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7099            }
7100
7101            N = pkg.receivers.size();
7102            r = null;
7103            for (i=0; i<N; i++) {
7104                PackageParser.Activity a = pkg.receivers.get(i);
7105                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7106                        a.info.processName, pkg.applicationInfo.uid);
7107                mReceivers.addActivity(a, "receiver");
7108                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7109                    if (r == null) {
7110                        r = new StringBuilder(256);
7111                    } else {
7112                        r.append(' ');
7113                    }
7114                    r.append(a.info.name);
7115                }
7116            }
7117            if (r != null) {
7118                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7119            }
7120
7121            N = pkg.activities.size();
7122            r = null;
7123            for (i=0; i<N; i++) {
7124                PackageParser.Activity a = pkg.activities.get(i);
7125                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7126                        a.info.processName, pkg.applicationInfo.uid);
7127                mActivities.addActivity(a, "activity");
7128                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7129                    if (r == null) {
7130                        r = new StringBuilder(256);
7131                    } else {
7132                        r.append(' ');
7133                    }
7134                    r.append(a.info.name);
7135                }
7136            }
7137            if (r != null) {
7138                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7139            }
7140
7141            N = pkg.permissionGroups.size();
7142            r = null;
7143            for (i=0; i<N; i++) {
7144                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7145                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7146                if (cur == null) {
7147                    mPermissionGroups.put(pg.info.name, pg);
7148                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7149                        if (r == null) {
7150                            r = new StringBuilder(256);
7151                        } else {
7152                            r.append(' ');
7153                        }
7154                        r.append(pg.info.name);
7155                    }
7156                } else {
7157                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7158                            + pg.info.packageName + " ignored: original from "
7159                            + cur.info.packageName);
7160                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7161                        if (r == null) {
7162                            r = new StringBuilder(256);
7163                        } else {
7164                            r.append(' ');
7165                        }
7166                        r.append("DUP:");
7167                        r.append(pg.info.name);
7168                    }
7169                }
7170            }
7171            if (r != null) {
7172                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7173            }
7174
7175            N = pkg.permissions.size();
7176            r = null;
7177            for (i=0; i<N; i++) {
7178                PackageParser.Permission p = pkg.permissions.get(i);
7179
7180                // Now that permission groups have a special meaning, we ignore permission
7181                // groups for legacy apps to prevent unexpected behavior. In particular,
7182                // permissions for one app being granted to someone just becuase they happen
7183                // to be in a group defined by another app (before this had no implications).
7184                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7185                    p.group = mPermissionGroups.get(p.info.group);
7186                    // Warn for a permission in an unknown group.
7187                    if (p.info.group != null && p.group == null) {
7188                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7189                                + p.info.packageName + " in an unknown group " + p.info.group);
7190                    }
7191                }
7192
7193                ArrayMap<String, BasePermission> permissionMap =
7194                        p.tree ? mSettings.mPermissionTrees
7195                                : mSettings.mPermissions;
7196                BasePermission bp = permissionMap.get(p.info.name);
7197
7198                // Allow system apps to redefine non-system permissions
7199                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7200                    final boolean currentOwnerIsSystem = (bp.perm != null
7201                            && isSystemApp(bp.perm.owner));
7202                    if (isSystemApp(p.owner)) {
7203                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7204                            // It's a built-in permission and no owner, take ownership now
7205                            bp.packageSetting = pkgSetting;
7206                            bp.perm = p;
7207                            bp.uid = pkg.applicationInfo.uid;
7208                            bp.sourcePackage = p.info.packageName;
7209                        } else if (!currentOwnerIsSystem) {
7210                            String msg = "New decl " + p.owner + " of permission  "
7211                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7212                            reportSettingsProblem(Log.WARN, msg);
7213                            bp = null;
7214                        }
7215                    }
7216                }
7217
7218                if (bp == null) {
7219                    bp = new BasePermission(p.info.name, p.info.packageName,
7220                            BasePermission.TYPE_NORMAL);
7221                    permissionMap.put(p.info.name, bp);
7222                }
7223
7224                if (bp.perm == null) {
7225                    if (bp.sourcePackage == null
7226                            || bp.sourcePackage.equals(p.info.packageName)) {
7227                        BasePermission tree = findPermissionTreeLP(p.info.name);
7228                        if (tree == null
7229                                || tree.sourcePackage.equals(p.info.packageName)) {
7230                            bp.packageSetting = pkgSetting;
7231                            bp.perm = p;
7232                            bp.uid = pkg.applicationInfo.uid;
7233                            bp.sourcePackage = p.info.packageName;
7234                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7235                                if (r == null) {
7236                                    r = new StringBuilder(256);
7237                                } else {
7238                                    r.append(' ');
7239                                }
7240                                r.append(p.info.name);
7241                            }
7242                        } else {
7243                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7244                                    + p.info.packageName + " ignored: base tree "
7245                                    + tree.name + " is from package "
7246                                    + tree.sourcePackage);
7247                        }
7248                    } else {
7249                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7250                                + p.info.packageName + " ignored: original from "
7251                                + bp.sourcePackage);
7252                    }
7253                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7254                    if (r == null) {
7255                        r = new StringBuilder(256);
7256                    } else {
7257                        r.append(' ');
7258                    }
7259                    r.append("DUP:");
7260                    r.append(p.info.name);
7261                }
7262                if (bp.perm == p) {
7263                    bp.protectionLevel = p.info.protectionLevel;
7264                }
7265            }
7266
7267            if (r != null) {
7268                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7269            }
7270
7271            N = pkg.instrumentation.size();
7272            r = null;
7273            for (i=0; i<N; i++) {
7274                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7275                a.info.packageName = pkg.applicationInfo.packageName;
7276                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7277                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7278                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7279                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7280                a.info.dataDir = pkg.applicationInfo.dataDir;
7281
7282                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7283                // need other information about the application, like the ABI and what not ?
7284                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7285                mInstrumentation.put(a.getComponentName(), a);
7286                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7287                    if (r == null) {
7288                        r = new StringBuilder(256);
7289                    } else {
7290                        r.append(' ');
7291                    }
7292                    r.append(a.info.name);
7293                }
7294            }
7295            if (r != null) {
7296                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7297            }
7298
7299            if (pkg.protectedBroadcasts != null) {
7300                N = pkg.protectedBroadcasts.size();
7301                for (i=0; i<N; i++) {
7302                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7303                }
7304            }
7305
7306            pkgSetting.setTimeStamp(scanFileTime);
7307
7308            // Create idmap files for pairs of (packages, overlay packages).
7309            // Note: "android", ie framework-res.apk, is handled by native layers.
7310            if (pkg.mOverlayTarget != null) {
7311                // This is an overlay package.
7312                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7313                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7314                        mOverlays.put(pkg.mOverlayTarget,
7315                                new ArrayMap<String, PackageParser.Package>());
7316                    }
7317                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7318                    map.put(pkg.packageName, pkg);
7319                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7320                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7321                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7322                                "scanPackageLI failed to createIdmap");
7323                    }
7324                }
7325            } else if (mOverlays.containsKey(pkg.packageName) &&
7326                    !pkg.packageName.equals("android")) {
7327                // This is a regular package, with one or more known overlay packages.
7328                createIdmapsForPackageLI(pkg);
7329            }
7330        }
7331
7332        return pkg;
7333    }
7334
7335    /**
7336     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7337     * is derived purely on the basis of the contents of {@code scanFile} and
7338     * {@code cpuAbiOverride}.
7339     *
7340     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7341     */
7342    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7343                                 String cpuAbiOverride, boolean extractLibs)
7344            throws PackageManagerException {
7345        // TODO: We can probably be smarter about this stuff. For installed apps,
7346        // we can calculate this information at install time once and for all. For
7347        // system apps, we can probably assume that this information doesn't change
7348        // after the first boot scan. As things stand, we do lots of unnecessary work.
7349
7350        // Give ourselves some initial paths; we'll come back for another
7351        // pass once we've determined ABI below.
7352        setNativeLibraryPaths(pkg);
7353
7354        // We would never need to extract libs for forward-locked and external packages,
7355        // since the container service will do it for us. We shouldn't attempt to
7356        // extract libs from system app when it was not updated.
7357        if (pkg.isForwardLocked() || isExternal(pkg) ||
7358            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7359            extractLibs = false;
7360        }
7361
7362        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7363        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7364
7365        NativeLibraryHelper.Handle handle = null;
7366        try {
7367            handle = NativeLibraryHelper.Handle.create(pkg);
7368            // TODO(multiArch): This can be null for apps that didn't go through the
7369            // usual installation process. We can calculate it again, like we
7370            // do during install time.
7371            //
7372            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7373            // unnecessary.
7374            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7375
7376            // Null out the abis so that they can be recalculated.
7377            pkg.applicationInfo.primaryCpuAbi = null;
7378            pkg.applicationInfo.secondaryCpuAbi = null;
7379            if (isMultiArch(pkg.applicationInfo)) {
7380                // Warn if we've set an abiOverride for multi-lib packages..
7381                // By definition, we need to copy both 32 and 64 bit libraries for
7382                // such packages.
7383                if (pkg.cpuAbiOverride != null
7384                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7385                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7386                }
7387
7388                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7389                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7390                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7391                    if (extractLibs) {
7392                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7393                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7394                                useIsaSpecificSubdirs);
7395                    } else {
7396                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7397                    }
7398                }
7399
7400                maybeThrowExceptionForMultiArchCopy(
7401                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7402
7403                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7404                    if (extractLibs) {
7405                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7406                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7407                                useIsaSpecificSubdirs);
7408                    } else {
7409                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7410                    }
7411                }
7412
7413                maybeThrowExceptionForMultiArchCopy(
7414                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7415
7416                if (abi64 >= 0) {
7417                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7418                }
7419
7420                if (abi32 >= 0) {
7421                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7422                    if (abi64 >= 0) {
7423                        pkg.applicationInfo.secondaryCpuAbi = abi;
7424                    } else {
7425                        pkg.applicationInfo.primaryCpuAbi = abi;
7426                    }
7427                }
7428            } else {
7429                String[] abiList = (cpuAbiOverride != null) ?
7430                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7431
7432                // Enable gross and lame hacks for apps that are built with old
7433                // SDK tools. We must scan their APKs for renderscript bitcode and
7434                // not launch them if it's present. Don't bother checking on devices
7435                // that don't have 64 bit support.
7436                boolean needsRenderScriptOverride = false;
7437                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7438                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7439                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7440                    needsRenderScriptOverride = true;
7441                }
7442
7443                final int copyRet;
7444                if (extractLibs) {
7445                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7446                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7447                } else {
7448                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7449                }
7450
7451                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7452                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7453                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7454                }
7455
7456                if (copyRet >= 0) {
7457                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7458                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7459                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7460                } else if (needsRenderScriptOverride) {
7461                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7462                }
7463            }
7464        } catch (IOException ioe) {
7465            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7466        } finally {
7467            IoUtils.closeQuietly(handle);
7468        }
7469
7470        // Now that we've calculated the ABIs and determined if it's an internal app,
7471        // we will go ahead and populate the nativeLibraryPath.
7472        setNativeLibraryPaths(pkg);
7473    }
7474
7475    /**
7476     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7477     * i.e, so that all packages can be run inside a single process if required.
7478     *
7479     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7480     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7481     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7482     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7483     * updating a package that belongs to a shared user.
7484     *
7485     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7486     * adds unnecessary complexity.
7487     */
7488    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7489            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7490        String requiredInstructionSet = null;
7491        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7492            requiredInstructionSet = VMRuntime.getInstructionSet(
7493                     scannedPackage.applicationInfo.primaryCpuAbi);
7494        }
7495
7496        PackageSetting requirer = null;
7497        for (PackageSetting ps : packagesForUser) {
7498            // If packagesForUser contains scannedPackage, we skip it. This will happen
7499            // when scannedPackage is an update of an existing package. Without this check,
7500            // we will never be able to change the ABI of any package belonging to a shared
7501            // user, even if it's compatible with other packages.
7502            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7503                if (ps.primaryCpuAbiString == null) {
7504                    continue;
7505                }
7506
7507                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7508                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7509                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7510                    // this but there's not much we can do.
7511                    String errorMessage = "Instruction set mismatch, "
7512                            + ((requirer == null) ? "[caller]" : requirer)
7513                            + " requires " + requiredInstructionSet + " whereas " + ps
7514                            + " requires " + instructionSet;
7515                    Slog.w(TAG, errorMessage);
7516                }
7517
7518                if (requiredInstructionSet == null) {
7519                    requiredInstructionSet = instructionSet;
7520                    requirer = ps;
7521                }
7522            }
7523        }
7524
7525        if (requiredInstructionSet != null) {
7526            String adjustedAbi;
7527            if (requirer != null) {
7528                // requirer != null implies that either scannedPackage was null or that scannedPackage
7529                // did not require an ABI, in which case we have to adjust scannedPackage to match
7530                // the ABI of the set (which is the same as requirer's ABI)
7531                adjustedAbi = requirer.primaryCpuAbiString;
7532                if (scannedPackage != null) {
7533                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7534                }
7535            } else {
7536                // requirer == null implies that we're updating all ABIs in the set to
7537                // match scannedPackage.
7538                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7539            }
7540
7541            for (PackageSetting ps : packagesForUser) {
7542                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7543                    if (ps.primaryCpuAbiString != null) {
7544                        continue;
7545                    }
7546
7547                    ps.primaryCpuAbiString = adjustedAbi;
7548                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7549                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7550                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7551
7552                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7553                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7554                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7555                            ps.primaryCpuAbiString = null;
7556                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7557                            return;
7558                        } else {
7559                            mInstaller.rmdex(ps.codePathString,
7560                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7561                        }
7562                    }
7563                }
7564            }
7565        }
7566    }
7567
7568    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7569        synchronized (mPackages) {
7570            mResolverReplaced = true;
7571            // Set up information for custom user intent resolution activity.
7572            mResolveActivity.applicationInfo = pkg.applicationInfo;
7573            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7574            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7575            mResolveActivity.processName = pkg.applicationInfo.packageName;
7576            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7577            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7578                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7579            mResolveActivity.theme = 0;
7580            mResolveActivity.exported = true;
7581            mResolveActivity.enabled = true;
7582            mResolveInfo.activityInfo = mResolveActivity;
7583            mResolveInfo.priority = 0;
7584            mResolveInfo.preferredOrder = 0;
7585            mResolveInfo.match = 0;
7586            mResolveComponentName = mCustomResolverComponentName;
7587            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7588                    mResolveComponentName);
7589        }
7590    }
7591
7592    private static String calculateBundledApkRoot(final String codePathString) {
7593        final File codePath = new File(codePathString);
7594        final File codeRoot;
7595        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7596            codeRoot = Environment.getRootDirectory();
7597        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7598            codeRoot = Environment.getOemDirectory();
7599        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7600            codeRoot = Environment.getVendorDirectory();
7601        } else {
7602            // Unrecognized code path; take its top real segment as the apk root:
7603            // e.g. /something/app/blah.apk => /something
7604            try {
7605                File f = codePath.getCanonicalFile();
7606                File parent = f.getParentFile();    // non-null because codePath is a file
7607                File tmp;
7608                while ((tmp = parent.getParentFile()) != null) {
7609                    f = parent;
7610                    parent = tmp;
7611                }
7612                codeRoot = f;
7613                Slog.w(TAG, "Unrecognized code path "
7614                        + codePath + " - using " + codeRoot);
7615            } catch (IOException e) {
7616                // Can't canonicalize the code path -- shenanigans?
7617                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7618                return Environment.getRootDirectory().getPath();
7619            }
7620        }
7621        return codeRoot.getPath();
7622    }
7623
7624    /**
7625     * Derive and set the location of native libraries for the given package,
7626     * which varies depending on where and how the package was installed.
7627     */
7628    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7629        final ApplicationInfo info = pkg.applicationInfo;
7630        final String codePath = pkg.codePath;
7631        final File codeFile = new File(codePath);
7632        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7633        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7634
7635        info.nativeLibraryRootDir = null;
7636        info.nativeLibraryRootRequiresIsa = false;
7637        info.nativeLibraryDir = null;
7638        info.secondaryNativeLibraryDir = null;
7639
7640        if (isApkFile(codeFile)) {
7641            // Monolithic install
7642            if (bundledApp) {
7643                // If "/system/lib64/apkname" exists, assume that is the per-package
7644                // native library directory to use; otherwise use "/system/lib/apkname".
7645                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7646                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7647                        getPrimaryInstructionSet(info));
7648
7649                // This is a bundled system app so choose the path based on the ABI.
7650                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7651                // is just the default path.
7652                final String apkName = deriveCodePathName(codePath);
7653                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7654                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7655                        apkName).getAbsolutePath();
7656
7657                if (info.secondaryCpuAbi != null) {
7658                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7659                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7660                            secondaryLibDir, apkName).getAbsolutePath();
7661                }
7662            } else if (asecApp) {
7663                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7664                        .getAbsolutePath();
7665            } else {
7666                final String apkName = deriveCodePathName(codePath);
7667                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7668                        .getAbsolutePath();
7669            }
7670
7671            info.nativeLibraryRootRequiresIsa = false;
7672            info.nativeLibraryDir = info.nativeLibraryRootDir;
7673        } else {
7674            // Cluster install
7675            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7676            info.nativeLibraryRootRequiresIsa = true;
7677
7678            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7679                    getPrimaryInstructionSet(info)).getAbsolutePath();
7680
7681            if (info.secondaryCpuAbi != null) {
7682                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7683                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7684            }
7685        }
7686    }
7687
7688    /**
7689     * Calculate the abis and roots for a bundled app. These can uniquely
7690     * be determined from the contents of the system partition, i.e whether
7691     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7692     * of this information, and instead assume that the system was built
7693     * sensibly.
7694     */
7695    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7696                                           PackageSetting pkgSetting) {
7697        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7698
7699        // If "/system/lib64/apkname" exists, assume that is the per-package
7700        // native library directory to use; otherwise use "/system/lib/apkname".
7701        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7702        setBundledAppAbi(pkg, apkRoot, apkName);
7703        // pkgSetting might be null during rescan following uninstall of updates
7704        // to a bundled app, so accommodate that possibility.  The settings in
7705        // that case will be established later from the parsed package.
7706        //
7707        // If the settings aren't null, sync them up with what we've just derived.
7708        // note that apkRoot isn't stored in the package settings.
7709        if (pkgSetting != null) {
7710            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7711            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7712        }
7713    }
7714
7715    /**
7716     * Deduces the ABI of a bundled app and sets the relevant fields on the
7717     * parsed pkg object.
7718     *
7719     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7720     *        under which system libraries are installed.
7721     * @param apkName the name of the installed package.
7722     */
7723    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7724        final File codeFile = new File(pkg.codePath);
7725
7726        final boolean has64BitLibs;
7727        final boolean has32BitLibs;
7728        if (isApkFile(codeFile)) {
7729            // Monolithic install
7730            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7731            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7732        } else {
7733            // Cluster install
7734            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7735            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7736                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7737                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7738                has64BitLibs = (new File(rootDir, isa)).exists();
7739            } else {
7740                has64BitLibs = false;
7741            }
7742            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7743                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7744                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7745                has32BitLibs = (new File(rootDir, isa)).exists();
7746            } else {
7747                has32BitLibs = false;
7748            }
7749        }
7750
7751        if (has64BitLibs && !has32BitLibs) {
7752            // The package has 64 bit libs, but not 32 bit libs. Its primary
7753            // ABI should be 64 bit. We can safely assume here that the bundled
7754            // native libraries correspond to the most preferred ABI in the list.
7755
7756            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7757            pkg.applicationInfo.secondaryCpuAbi = null;
7758        } else if (has32BitLibs && !has64BitLibs) {
7759            // The package has 32 bit libs but not 64 bit libs. Its primary
7760            // ABI should be 32 bit.
7761
7762            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7763            pkg.applicationInfo.secondaryCpuAbi = null;
7764        } else if (has32BitLibs && has64BitLibs) {
7765            // The application has both 64 and 32 bit bundled libraries. We check
7766            // here that the app declares multiArch support, and warn if it doesn't.
7767            //
7768            // We will be lenient here and record both ABIs. The primary will be the
7769            // ABI that's higher on the list, i.e, a device that's configured to prefer
7770            // 64 bit apps will see a 64 bit primary ABI,
7771
7772            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7773                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7774            }
7775
7776            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7777                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7778                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7779            } else {
7780                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7781                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7782            }
7783        } else {
7784            pkg.applicationInfo.primaryCpuAbi = null;
7785            pkg.applicationInfo.secondaryCpuAbi = null;
7786        }
7787    }
7788
7789    private void killApplication(String pkgName, int appId, String reason) {
7790        // Request the ActivityManager to kill the process(only for existing packages)
7791        // so that we do not end up in a confused state while the user is still using the older
7792        // version of the application while the new one gets installed.
7793        IActivityManager am = ActivityManagerNative.getDefault();
7794        if (am != null) {
7795            try {
7796                am.killApplicationWithAppId(pkgName, appId, reason);
7797            } catch (RemoteException e) {
7798            }
7799        }
7800    }
7801
7802    void removePackageLI(PackageSetting ps, boolean chatty) {
7803        if (DEBUG_INSTALL) {
7804            if (chatty)
7805                Log.d(TAG, "Removing package " + ps.name);
7806        }
7807
7808        // writer
7809        synchronized (mPackages) {
7810            mPackages.remove(ps.name);
7811            final PackageParser.Package pkg = ps.pkg;
7812            if (pkg != null) {
7813                cleanPackageDataStructuresLILPw(pkg, chatty);
7814            }
7815        }
7816    }
7817
7818    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7819        if (DEBUG_INSTALL) {
7820            if (chatty)
7821                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7822        }
7823
7824        // writer
7825        synchronized (mPackages) {
7826            mPackages.remove(pkg.applicationInfo.packageName);
7827            cleanPackageDataStructuresLILPw(pkg, chatty);
7828        }
7829    }
7830
7831    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7832        int N = pkg.providers.size();
7833        StringBuilder r = null;
7834        int i;
7835        for (i=0; i<N; i++) {
7836            PackageParser.Provider p = pkg.providers.get(i);
7837            mProviders.removeProvider(p);
7838            if (p.info.authority == null) {
7839
7840                /* There was another ContentProvider with this authority when
7841                 * this app was installed so this authority is null,
7842                 * Ignore it as we don't have to unregister the provider.
7843                 */
7844                continue;
7845            }
7846            String names[] = p.info.authority.split(";");
7847            for (int j = 0; j < names.length; j++) {
7848                if (mProvidersByAuthority.get(names[j]) == p) {
7849                    mProvidersByAuthority.remove(names[j]);
7850                    if (DEBUG_REMOVE) {
7851                        if (chatty)
7852                            Log.d(TAG, "Unregistered content provider: " + names[j]
7853                                    + ", className = " + p.info.name + ", isSyncable = "
7854                                    + p.info.isSyncable);
7855                    }
7856                }
7857            }
7858            if (DEBUG_REMOVE && chatty) {
7859                if (r == null) {
7860                    r = new StringBuilder(256);
7861                } else {
7862                    r.append(' ');
7863                }
7864                r.append(p.info.name);
7865            }
7866        }
7867        if (r != null) {
7868            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7869        }
7870
7871        N = pkg.services.size();
7872        r = null;
7873        for (i=0; i<N; i++) {
7874            PackageParser.Service s = pkg.services.get(i);
7875            mServices.removeService(s);
7876            if (chatty) {
7877                if (r == null) {
7878                    r = new StringBuilder(256);
7879                } else {
7880                    r.append(' ');
7881                }
7882                r.append(s.info.name);
7883            }
7884        }
7885        if (r != null) {
7886            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7887        }
7888
7889        N = pkg.receivers.size();
7890        r = null;
7891        for (i=0; i<N; i++) {
7892            PackageParser.Activity a = pkg.receivers.get(i);
7893            mReceivers.removeActivity(a, "receiver");
7894            if (DEBUG_REMOVE && chatty) {
7895                if (r == null) {
7896                    r = new StringBuilder(256);
7897                } else {
7898                    r.append(' ');
7899                }
7900                r.append(a.info.name);
7901            }
7902        }
7903        if (r != null) {
7904            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7905        }
7906
7907        N = pkg.activities.size();
7908        r = null;
7909        for (i=0; i<N; i++) {
7910            PackageParser.Activity a = pkg.activities.get(i);
7911            mActivities.removeActivity(a, "activity");
7912            if (DEBUG_REMOVE && chatty) {
7913                if (r == null) {
7914                    r = new StringBuilder(256);
7915                } else {
7916                    r.append(' ');
7917                }
7918                r.append(a.info.name);
7919            }
7920        }
7921        if (r != null) {
7922            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7923        }
7924
7925        N = pkg.permissions.size();
7926        r = null;
7927        for (i=0; i<N; i++) {
7928            PackageParser.Permission p = pkg.permissions.get(i);
7929            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7930            if (bp == null) {
7931                bp = mSettings.mPermissionTrees.get(p.info.name);
7932            }
7933            if (bp != null && bp.perm == p) {
7934                bp.perm = null;
7935                if (DEBUG_REMOVE && chatty) {
7936                    if (r == null) {
7937                        r = new StringBuilder(256);
7938                    } else {
7939                        r.append(' ');
7940                    }
7941                    r.append(p.info.name);
7942                }
7943            }
7944            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7945                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7946                if (appOpPerms != null) {
7947                    appOpPerms.remove(pkg.packageName);
7948                }
7949            }
7950        }
7951        if (r != null) {
7952            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7953        }
7954
7955        N = pkg.requestedPermissions.size();
7956        r = null;
7957        for (i=0; i<N; i++) {
7958            String perm = pkg.requestedPermissions.get(i);
7959            BasePermission bp = mSettings.mPermissions.get(perm);
7960            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7961                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7962                if (appOpPerms != null) {
7963                    appOpPerms.remove(pkg.packageName);
7964                    if (appOpPerms.isEmpty()) {
7965                        mAppOpPermissionPackages.remove(perm);
7966                    }
7967                }
7968            }
7969        }
7970        if (r != null) {
7971            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7972        }
7973
7974        N = pkg.instrumentation.size();
7975        r = null;
7976        for (i=0; i<N; i++) {
7977            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7978            mInstrumentation.remove(a.getComponentName());
7979            if (DEBUG_REMOVE && chatty) {
7980                if (r == null) {
7981                    r = new StringBuilder(256);
7982                } else {
7983                    r.append(' ');
7984                }
7985                r.append(a.info.name);
7986            }
7987        }
7988        if (r != null) {
7989            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7990        }
7991
7992        r = null;
7993        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7994            // Only system apps can hold shared libraries.
7995            if (pkg.libraryNames != null) {
7996                for (i=0; i<pkg.libraryNames.size(); i++) {
7997                    String name = pkg.libraryNames.get(i);
7998                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7999                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8000                        mSharedLibraries.remove(name);
8001                        if (DEBUG_REMOVE && chatty) {
8002                            if (r == null) {
8003                                r = new StringBuilder(256);
8004                            } else {
8005                                r.append(' ');
8006                            }
8007                            r.append(name);
8008                        }
8009                    }
8010                }
8011            }
8012        }
8013        if (r != null) {
8014            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8015        }
8016    }
8017
8018    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8019        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8020            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8021                return true;
8022            }
8023        }
8024        return false;
8025    }
8026
8027    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8028    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8029    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8030
8031    private void updatePermissionsLPw(String changingPkg,
8032            PackageParser.Package pkgInfo, int flags) {
8033        // Make sure there are no dangling permission trees.
8034        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8035        while (it.hasNext()) {
8036            final BasePermission bp = it.next();
8037            if (bp.packageSetting == null) {
8038                // We may not yet have parsed the package, so just see if
8039                // we still know about its settings.
8040                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8041            }
8042            if (bp.packageSetting == null) {
8043                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8044                        + " from package " + bp.sourcePackage);
8045                it.remove();
8046            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8047                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8048                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8049                            + " from package " + bp.sourcePackage);
8050                    flags |= UPDATE_PERMISSIONS_ALL;
8051                    it.remove();
8052                }
8053            }
8054        }
8055
8056        // Make sure all dynamic permissions have been assigned to a package,
8057        // and make sure there are no dangling permissions.
8058        it = mSettings.mPermissions.values().iterator();
8059        while (it.hasNext()) {
8060            final BasePermission bp = it.next();
8061            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8062                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8063                        + bp.name + " pkg=" + bp.sourcePackage
8064                        + " info=" + bp.pendingInfo);
8065                if (bp.packageSetting == null && bp.pendingInfo != null) {
8066                    final BasePermission tree = findPermissionTreeLP(bp.name);
8067                    if (tree != null && tree.perm != null) {
8068                        bp.packageSetting = tree.packageSetting;
8069                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8070                                new PermissionInfo(bp.pendingInfo));
8071                        bp.perm.info.packageName = tree.perm.info.packageName;
8072                        bp.perm.info.name = bp.name;
8073                        bp.uid = tree.uid;
8074                    }
8075                }
8076            }
8077            if (bp.packageSetting == null) {
8078                // We may not yet have parsed the package, so just see if
8079                // we still know about its settings.
8080                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8081            }
8082            if (bp.packageSetting == null) {
8083                Slog.w(TAG, "Removing dangling permission: " + bp.name
8084                        + " from package " + bp.sourcePackage);
8085                it.remove();
8086            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8087                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8088                    Slog.i(TAG, "Removing old permission: " + bp.name
8089                            + " from package " + bp.sourcePackage);
8090                    flags |= UPDATE_PERMISSIONS_ALL;
8091                    it.remove();
8092                }
8093            }
8094        }
8095
8096        // Now update the permissions for all packages, in particular
8097        // replace the granted permissions of the system packages.
8098        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8099            for (PackageParser.Package pkg : mPackages.values()) {
8100                if (pkg != pkgInfo) {
8101                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8102                            changingPkg);
8103                }
8104            }
8105        }
8106
8107        if (pkgInfo != null) {
8108            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8109        }
8110    }
8111
8112    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8113            String packageOfInterest) {
8114        // IMPORTANT: There are two types of permissions: install and runtime.
8115        // Install time permissions are granted when the app is installed to
8116        // all device users and users added in the future. Runtime permissions
8117        // are granted at runtime explicitly to specific users. Normal and signature
8118        // protected permissions are install time permissions. Dangerous permissions
8119        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8120        // otherwise they are runtime permissions. This function does not manage
8121        // runtime permissions except for the case an app targeting Lollipop MR1
8122        // being upgraded to target a newer SDK, in which case dangerous permissions
8123        // are transformed from install time to runtime ones.
8124
8125        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8126        if (ps == null) {
8127            return;
8128        }
8129
8130        PermissionsState permissionsState = ps.getPermissionsState();
8131        PermissionsState origPermissions = permissionsState;
8132
8133        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8134
8135        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8136
8137        boolean changedInstallPermission = false;
8138
8139        if (replace) {
8140            ps.installPermissionsFixed = false;
8141            if (!ps.isSharedUser()) {
8142                origPermissions = new PermissionsState(permissionsState);
8143                permissionsState.reset();
8144            }
8145        }
8146
8147        permissionsState.setGlobalGids(mGlobalGids);
8148
8149        final int N = pkg.requestedPermissions.size();
8150        for (int i=0; i<N; i++) {
8151            final String name = pkg.requestedPermissions.get(i);
8152            final BasePermission bp = mSettings.mPermissions.get(name);
8153
8154            if (DEBUG_INSTALL) {
8155                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8156            }
8157
8158            if (bp == null || bp.packageSetting == null) {
8159                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8160                    Slog.w(TAG, "Unknown permission " + name
8161                            + " in package " + pkg.packageName);
8162                }
8163                continue;
8164            }
8165
8166            final String perm = bp.name;
8167            boolean allowedSig = false;
8168            int grant = GRANT_DENIED;
8169
8170            // Keep track of app op permissions.
8171            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8172                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8173                if (pkgs == null) {
8174                    pkgs = new ArraySet<>();
8175                    mAppOpPermissionPackages.put(bp.name, pkgs);
8176                }
8177                pkgs.add(pkg.packageName);
8178            }
8179
8180            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8181            switch (level) {
8182                case PermissionInfo.PROTECTION_NORMAL: {
8183                    // For all apps normal permissions are install time ones.
8184                    grant = GRANT_INSTALL;
8185                } break;
8186
8187                case PermissionInfo.PROTECTION_DANGEROUS: {
8188                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8189                        // For legacy apps dangerous permissions are install time ones.
8190                        grant = GRANT_INSTALL_LEGACY;
8191                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8192                        // For legacy apps that became modern, install becomes runtime.
8193                        grant = GRANT_UPGRADE;
8194                    } else {
8195                        // For modern apps keep runtime permissions unchanged.
8196                        grant = GRANT_RUNTIME;
8197                    }
8198                } break;
8199
8200                case PermissionInfo.PROTECTION_SIGNATURE: {
8201                    // For all apps signature permissions are install time ones.
8202                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8203                    if (allowedSig) {
8204                        grant = GRANT_INSTALL;
8205                    }
8206                } break;
8207            }
8208
8209            if (DEBUG_INSTALL) {
8210                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8211            }
8212
8213            if (grant != GRANT_DENIED) {
8214                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8215                    // If this is an existing, non-system package, then
8216                    // we can't add any new permissions to it.
8217                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8218                        // Except...  if this is a permission that was added
8219                        // to the platform (note: need to only do this when
8220                        // updating the platform).
8221                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8222                            grant = GRANT_DENIED;
8223                        }
8224                    }
8225                }
8226
8227                switch (grant) {
8228                    case GRANT_INSTALL: {
8229                        // Revoke this as runtime permission to handle the case of
8230                        // a runtime permission being downgraded to an install one.
8231                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8232                            if (origPermissions.getRuntimePermissionState(
8233                                    bp.name, userId) != null) {
8234                                // Revoke the runtime permission and clear the flags.
8235                                origPermissions.revokeRuntimePermission(bp, userId);
8236                                origPermissions.updatePermissionFlags(bp, userId,
8237                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8238                                // If we revoked a permission permission, we have to write.
8239                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8240                                        changedRuntimePermissionUserIds, userId);
8241                            }
8242                        }
8243                        // Grant an install permission.
8244                        if (permissionsState.grantInstallPermission(bp) !=
8245                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8246                            changedInstallPermission = true;
8247                        }
8248                    } break;
8249
8250                    case GRANT_INSTALL_LEGACY: {
8251                        // Grant an install permission.
8252                        if (permissionsState.grantInstallPermission(bp) !=
8253                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8254                            changedInstallPermission = true;
8255                        }
8256                    } break;
8257
8258                    case GRANT_RUNTIME: {
8259                        // Grant previously granted runtime permissions.
8260                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8261                            PermissionState permissionState = origPermissions
8262                                    .getRuntimePermissionState(bp.name, userId);
8263                            final int flags = permissionState != null
8264                                    ? permissionState.getFlags() : 0;
8265                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8266                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8267                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8268                                    // If we cannot put the permission as it was, we have to write.
8269                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8270                                            changedRuntimePermissionUserIds, userId);
8271                                }
8272                            }
8273                            // Propagate the permission flags.
8274                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8275                        }
8276                    } break;
8277
8278                    case GRANT_UPGRADE: {
8279                        // Grant runtime permissions for a previously held install permission.
8280                        PermissionState permissionState = origPermissions
8281                                .getInstallPermissionState(bp.name);
8282                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8283
8284                        if (origPermissions.revokeInstallPermission(bp)
8285                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8286                            // We will be transferring the permission flags, so clear them.
8287                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8288                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8289                            changedInstallPermission = true;
8290                        }
8291
8292                        // If the permission is not to be promoted to runtime we ignore it and
8293                        // also its other flags as they are not applicable to install permissions.
8294                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8295                            for (int userId : currentUserIds) {
8296                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8297                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8298                                    // Transfer the permission flags.
8299                                    permissionsState.updatePermissionFlags(bp, userId,
8300                                            flags, flags);
8301                                    // If we granted the permission, we have to write.
8302                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8303                                            changedRuntimePermissionUserIds, userId);
8304                                }
8305                            }
8306                        }
8307                    } break;
8308
8309                    default: {
8310                        if (packageOfInterest == null
8311                                || packageOfInterest.equals(pkg.packageName)) {
8312                            Slog.w(TAG, "Not granting permission " + perm
8313                                    + " to package " + pkg.packageName
8314                                    + " because it was previously installed without");
8315                        }
8316                    } break;
8317                }
8318            } else {
8319                if (permissionsState.revokeInstallPermission(bp) !=
8320                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8321                    // Also drop the permission flags.
8322                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8323                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8324                    changedInstallPermission = true;
8325                    Slog.i(TAG, "Un-granting permission " + perm
8326                            + " from package " + pkg.packageName
8327                            + " (protectionLevel=" + bp.protectionLevel
8328                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8329                            + ")");
8330                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8331                    // Don't print warning for app op permissions, since it is fine for them
8332                    // not to be granted, there is a UI for the user to decide.
8333                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8334                        Slog.w(TAG, "Not granting permission " + perm
8335                                + " to package " + pkg.packageName
8336                                + " (protectionLevel=" + bp.protectionLevel
8337                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8338                                + ")");
8339                    }
8340                }
8341            }
8342        }
8343
8344        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8345                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8346            // This is the first that we have heard about this package, so the
8347            // permissions we have now selected are fixed until explicitly
8348            // changed.
8349            ps.installPermissionsFixed = true;
8350        }
8351
8352        // Persist the runtime permissions state for users with changes.
8353        for (int userId : changedRuntimePermissionUserIds) {
8354            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8355        }
8356    }
8357
8358    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8359        boolean allowed = false;
8360        final int NP = PackageParser.NEW_PERMISSIONS.length;
8361        for (int ip=0; ip<NP; ip++) {
8362            final PackageParser.NewPermissionInfo npi
8363                    = PackageParser.NEW_PERMISSIONS[ip];
8364            if (npi.name.equals(perm)
8365                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8366                allowed = true;
8367                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8368                        + pkg.packageName);
8369                break;
8370            }
8371        }
8372        return allowed;
8373    }
8374
8375    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8376            BasePermission bp, PermissionsState origPermissions) {
8377        boolean allowed;
8378        allowed = (compareSignatures(
8379                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8380                        == PackageManager.SIGNATURE_MATCH)
8381                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8382                        == PackageManager.SIGNATURE_MATCH);
8383        if (!allowed && (bp.protectionLevel
8384                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8385            if (isSystemApp(pkg)) {
8386                // For updated system applications, a system permission
8387                // is granted only if it had been defined by the original application.
8388                if (pkg.isUpdatedSystemApp()) {
8389                    final PackageSetting sysPs = mSettings
8390                            .getDisabledSystemPkgLPr(pkg.packageName);
8391                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8392                        // If the original was granted this permission, we take
8393                        // that grant decision as read and propagate it to the
8394                        // update.
8395                        if (sysPs.isPrivileged()) {
8396                            allowed = true;
8397                        }
8398                    } else {
8399                        // The system apk may have been updated with an older
8400                        // version of the one on the data partition, but which
8401                        // granted a new system permission that it didn't have
8402                        // before.  In this case we do want to allow the app to
8403                        // now get the new permission if the ancestral apk is
8404                        // privileged to get it.
8405                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8406                            for (int j=0;
8407                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8408                                if (perm.equals(
8409                                        sysPs.pkg.requestedPermissions.get(j))) {
8410                                    allowed = true;
8411                                    break;
8412                                }
8413                            }
8414                        }
8415                    }
8416                } else {
8417                    allowed = isPrivilegedApp(pkg);
8418                }
8419            }
8420        }
8421        if (!allowed && (bp.protectionLevel
8422                & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8423                && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8424            // If this was a previously normal/dangerous permission that got moved
8425            // to a system permission as part of the runtime permission redesign, then
8426            // we still want to blindly grant it to old apps.
8427            allowed = true;
8428        }
8429        if (!allowed && (bp.protectionLevel
8430                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8431            // For development permissions, a development permission
8432            // is granted only if it was already granted.
8433            allowed = origPermissions.hasInstallPermission(perm);
8434        }
8435        return allowed;
8436    }
8437
8438    final class ActivityIntentResolver
8439            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8440        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8441                boolean defaultOnly, int userId) {
8442            if (!sUserManager.exists(userId)) return null;
8443            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8444            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8445        }
8446
8447        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8448                int userId) {
8449            if (!sUserManager.exists(userId)) return null;
8450            mFlags = flags;
8451            return super.queryIntent(intent, resolvedType,
8452                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8453        }
8454
8455        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8456                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8457            if (!sUserManager.exists(userId)) return null;
8458            if (packageActivities == null) {
8459                return null;
8460            }
8461            mFlags = flags;
8462            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8463            final int N = packageActivities.size();
8464            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8465                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8466
8467            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8468            for (int i = 0; i < N; ++i) {
8469                intentFilters = packageActivities.get(i).intents;
8470                if (intentFilters != null && intentFilters.size() > 0) {
8471                    PackageParser.ActivityIntentInfo[] array =
8472                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8473                    intentFilters.toArray(array);
8474                    listCut.add(array);
8475                }
8476            }
8477            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8478        }
8479
8480        public final void addActivity(PackageParser.Activity a, String type) {
8481            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8482            mActivities.put(a.getComponentName(), a);
8483            if (DEBUG_SHOW_INFO)
8484                Log.v(
8485                TAG, "  " + type + " " +
8486                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8487            if (DEBUG_SHOW_INFO)
8488                Log.v(TAG, "    Class=" + a.info.name);
8489            final int NI = a.intents.size();
8490            for (int j=0; j<NI; j++) {
8491                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8492                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8493                    intent.setPriority(0);
8494                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8495                            + a.className + " with priority > 0, forcing to 0");
8496                }
8497                if (DEBUG_SHOW_INFO) {
8498                    Log.v(TAG, "    IntentFilter:");
8499                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8500                }
8501                if (!intent.debugCheck()) {
8502                    Log.w(TAG, "==> For Activity " + a.info.name);
8503                }
8504                addFilter(intent);
8505            }
8506        }
8507
8508        public final void removeActivity(PackageParser.Activity a, String type) {
8509            mActivities.remove(a.getComponentName());
8510            if (DEBUG_SHOW_INFO) {
8511                Log.v(TAG, "  " + type + " "
8512                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8513                                : a.info.name) + ":");
8514                Log.v(TAG, "    Class=" + a.info.name);
8515            }
8516            final int NI = a.intents.size();
8517            for (int j=0; j<NI; j++) {
8518                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8519                if (DEBUG_SHOW_INFO) {
8520                    Log.v(TAG, "    IntentFilter:");
8521                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8522                }
8523                removeFilter(intent);
8524            }
8525        }
8526
8527        @Override
8528        protected boolean allowFilterResult(
8529                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8530            ActivityInfo filterAi = filter.activity.info;
8531            for (int i=dest.size()-1; i>=0; i--) {
8532                ActivityInfo destAi = dest.get(i).activityInfo;
8533                if (destAi.name == filterAi.name
8534                        && destAi.packageName == filterAi.packageName) {
8535                    return false;
8536                }
8537            }
8538            return true;
8539        }
8540
8541        @Override
8542        protected ActivityIntentInfo[] newArray(int size) {
8543            return new ActivityIntentInfo[size];
8544        }
8545
8546        @Override
8547        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8548            if (!sUserManager.exists(userId)) return true;
8549            PackageParser.Package p = filter.activity.owner;
8550            if (p != null) {
8551                PackageSetting ps = (PackageSetting)p.mExtras;
8552                if (ps != null) {
8553                    // System apps are never considered stopped for purposes of
8554                    // filtering, because there may be no way for the user to
8555                    // actually re-launch them.
8556                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8557                            && ps.getStopped(userId);
8558                }
8559            }
8560            return false;
8561        }
8562
8563        @Override
8564        protected boolean isPackageForFilter(String packageName,
8565                PackageParser.ActivityIntentInfo info) {
8566            return packageName.equals(info.activity.owner.packageName);
8567        }
8568
8569        @Override
8570        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8571                int match, int userId) {
8572            if (!sUserManager.exists(userId)) return null;
8573            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8574                return null;
8575            }
8576            final PackageParser.Activity activity = info.activity;
8577            if (mSafeMode && (activity.info.applicationInfo.flags
8578                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8579                return null;
8580            }
8581            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8582            if (ps == null) {
8583                return null;
8584            }
8585            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8586                    ps.readUserState(userId), userId);
8587            if (ai == null) {
8588                return null;
8589            }
8590            final ResolveInfo res = new ResolveInfo();
8591            res.activityInfo = ai;
8592            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8593                res.filter = info;
8594            }
8595            if (info != null) {
8596                res.handleAllWebDataURI = info.handleAllWebDataURI();
8597            }
8598            res.priority = info.getPriority();
8599            res.preferredOrder = activity.owner.mPreferredOrder;
8600            //System.out.println("Result: " + res.activityInfo.className +
8601            //                   " = " + res.priority);
8602            res.match = match;
8603            res.isDefault = info.hasDefault;
8604            res.labelRes = info.labelRes;
8605            res.nonLocalizedLabel = info.nonLocalizedLabel;
8606            if (userNeedsBadging(userId)) {
8607                res.noResourceId = true;
8608            } else {
8609                res.icon = info.icon;
8610            }
8611            res.iconResourceId = info.icon;
8612            res.system = res.activityInfo.applicationInfo.isSystemApp();
8613            return res;
8614        }
8615
8616        @Override
8617        protected void sortResults(List<ResolveInfo> results) {
8618            Collections.sort(results, mResolvePrioritySorter);
8619        }
8620
8621        @Override
8622        protected void dumpFilter(PrintWriter out, String prefix,
8623                PackageParser.ActivityIntentInfo filter) {
8624            out.print(prefix); out.print(
8625                    Integer.toHexString(System.identityHashCode(filter.activity)));
8626                    out.print(' ');
8627                    filter.activity.printComponentShortName(out);
8628                    out.print(" filter ");
8629                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8630        }
8631
8632        @Override
8633        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8634            return filter.activity;
8635        }
8636
8637        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8638            PackageParser.Activity activity = (PackageParser.Activity)label;
8639            out.print(prefix); out.print(
8640                    Integer.toHexString(System.identityHashCode(activity)));
8641                    out.print(' ');
8642                    activity.printComponentShortName(out);
8643            if (count > 1) {
8644                out.print(" ("); out.print(count); out.print(" filters)");
8645            }
8646            out.println();
8647        }
8648
8649//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8650//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8651//            final List<ResolveInfo> retList = Lists.newArrayList();
8652//            while (i.hasNext()) {
8653//                final ResolveInfo resolveInfo = i.next();
8654//                if (isEnabledLP(resolveInfo.activityInfo)) {
8655//                    retList.add(resolveInfo);
8656//                }
8657//            }
8658//            return retList;
8659//        }
8660
8661        // Keys are String (activity class name), values are Activity.
8662        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8663                = new ArrayMap<ComponentName, PackageParser.Activity>();
8664        private int mFlags;
8665    }
8666
8667    private final class ServiceIntentResolver
8668            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8669        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8670                boolean defaultOnly, int userId) {
8671            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8672            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8673        }
8674
8675        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8676                int userId) {
8677            if (!sUserManager.exists(userId)) return null;
8678            mFlags = flags;
8679            return super.queryIntent(intent, resolvedType,
8680                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8681        }
8682
8683        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8684                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8685            if (!sUserManager.exists(userId)) return null;
8686            if (packageServices == null) {
8687                return null;
8688            }
8689            mFlags = flags;
8690            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8691            final int N = packageServices.size();
8692            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8693                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8694
8695            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8696            for (int i = 0; i < N; ++i) {
8697                intentFilters = packageServices.get(i).intents;
8698                if (intentFilters != null && intentFilters.size() > 0) {
8699                    PackageParser.ServiceIntentInfo[] array =
8700                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8701                    intentFilters.toArray(array);
8702                    listCut.add(array);
8703                }
8704            }
8705            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8706        }
8707
8708        public final void addService(PackageParser.Service s) {
8709            mServices.put(s.getComponentName(), s);
8710            if (DEBUG_SHOW_INFO) {
8711                Log.v(TAG, "  "
8712                        + (s.info.nonLocalizedLabel != null
8713                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8714                Log.v(TAG, "    Class=" + s.info.name);
8715            }
8716            final int NI = s.intents.size();
8717            int j;
8718            for (j=0; j<NI; j++) {
8719                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8720                if (DEBUG_SHOW_INFO) {
8721                    Log.v(TAG, "    IntentFilter:");
8722                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8723                }
8724                if (!intent.debugCheck()) {
8725                    Log.w(TAG, "==> For Service " + s.info.name);
8726                }
8727                addFilter(intent);
8728            }
8729        }
8730
8731        public final void removeService(PackageParser.Service s) {
8732            mServices.remove(s.getComponentName());
8733            if (DEBUG_SHOW_INFO) {
8734                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8735                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8736                Log.v(TAG, "    Class=" + s.info.name);
8737            }
8738            final int NI = s.intents.size();
8739            int j;
8740            for (j=0; j<NI; j++) {
8741                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8742                if (DEBUG_SHOW_INFO) {
8743                    Log.v(TAG, "    IntentFilter:");
8744                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8745                }
8746                removeFilter(intent);
8747            }
8748        }
8749
8750        @Override
8751        protected boolean allowFilterResult(
8752                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8753            ServiceInfo filterSi = filter.service.info;
8754            for (int i=dest.size()-1; i>=0; i--) {
8755                ServiceInfo destAi = dest.get(i).serviceInfo;
8756                if (destAi.name == filterSi.name
8757                        && destAi.packageName == filterSi.packageName) {
8758                    return false;
8759                }
8760            }
8761            return true;
8762        }
8763
8764        @Override
8765        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8766            return new PackageParser.ServiceIntentInfo[size];
8767        }
8768
8769        @Override
8770        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8771            if (!sUserManager.exists(userId)) return true;
8772            PackageParser.Package p = filter.service.owner;
8773            if (p != null) {
8774                PackageSetting ps = (PackageSetting)p.mExtras;
8775                if (ps != null) {
8776                    // System apps are never considered stopped for purposes of
8777                    // filtering, because there may be no way for the user to
8778                    // actually re-launch them.
8779                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8780                            && ps.getStopped(userId);
8781                }
8782            }
8783            return false;
8784        }
8785
8786        @Override
8787        protected boolean isPackageForFilter(String packageName,
8788                PackageParser.ServiceIntentInfo info) {
8789            return packageName.equals(info.service.owner.packageName);
8790        }
8791
8792        @Override
8793        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8794                int match, int userId) {
8795            if (!sUserManager.exists(userId)) return null;
8796            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8797            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8798                return null;
8799            }
8800            final PackageParser.Service service = info.service;
8801            if (mSafeMode && (service.info.applicationInfo.flags
8802                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8803                return null;
8804            }
8805            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8806            if (ps == null) {
8807                return null;
8808            }
8809            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8810                    ps.readUserState(userId), userId);
8811            if (si == null) {
8812                return null;
8813            }
8814            final ResolveInfo res = new ResolveInfo();
8815            res.serviceInfo = si;
8816            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8817                res.filter = filter;
8818            }
8819            res.priority = info.getPriority();
8820            res.preferredOrder = service.owner.mPreferredOrder;
8821            res.match = match;
8822            res.isDefault = info.hasDefault;
8823            res.labelRes = info.labelRes;
8824            res.nonLocalizedLabel = info.nonLocalizedLabel;
8825            res.icon = info.icon;
8826            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8827            return res;
8828        }
8829
8830        @Override
8831        protected void sortResults(List<ResolveInfo> results) {
8832            Collections.sort(results, mResolvePrioritySorter);
8833        }
8834
8835        @Override
8836        protected void dumpFilter(PrintWriter out, String prefix,
8837                PackageParser.ServiceIntentInfo filter) {
8838            out.print(prefix); out.print(
8839                    Integer.toHexString(System.identityHashCode(filter.service)));
8840                    out.print(' ');
8841                    filter.service.printComponentShortName(out);
8842                    out.print(" filter ");
8843                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8844        }
8845
8846        @Override
8847        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8848            return filter.service;
8849        }
8850
8851        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8852            PackageParser.Service service = (PackageParser.Service)label;
8853            out.print(prefix); out.print(
8854                    Integer.toHexString(System.identityHashCode(service)));
8855                    out.print(' ');
8856                    service.printComponentShortName(out);
8857            if (count > 1) {
8858                out.print(" ("); out.print(count); out.print(" filters)");
8859            }
8860            out.println();
8861        }
8862
8863//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8864//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8865//            final List<ResolveInfo> retList = Lists.newArrayList();
8866//            while (i.hasNext()) {
8867//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8868//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8869//                    retList.add(resolveInfo);
8870//                }
8871//            }
8872//            return retList;
8873//        }
8874
8875        // Keys are String (activity class name), values are Activity.
8876        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8877                = new ArrayMap<ComponentName, PackageParser.Service>();
8878        private int mFlags;
8879    };
8880
8881    private final class ProviderIntentResolver
8882            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8883        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8884                boolean defaultOnly, int userId) {
8885            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8886            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8887        }
8888
8889        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8890                int userId) {
8891            if (!sUserManager.exists(userId))
8892                return null;
8893            mFlags = flags;
8894            return super.queryIntent(intent, resolvedType,
8895                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8896        }
8897
8898        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8899                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8900            if (!sUserManager.exists(userId))
8901                return null;
8902            if (packageProviders == null) {
8903                return null;
8904            }
8905            mFlags = flags;
8906            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8907            final int N = packageProviders.size();
8908            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8909                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8910
8911            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8912            for (int i = 0; i < N; ++i) {
8913                intentFilters = packageProviders.get(i).intents;
8914                if (intentFilters != null && intentFilters.size() > 0) {
8915                    PackageParser.ProviderIntentInfo[] array =
8916                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8917                    intentFilters.toArray(array);
8918                    listCut.add(array);
8919                }
8920            }
8921            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8922        }
8923
8924        public final void addProvider(PackageParser.Provider p) {
8925            if (mProviders.containsKey(p.getComponentName())) {
8926                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8927                return;
8928            }
8929
8930            mProviders.put(p.getComponentName(), p);
8931            if (DEBUG_SHOW_INFO) {
8932                Log.v(TAG, "  "
8933                        + (p.info.nonLocalizedLabel != null
8934                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8935                Log.v(TAG, "    Class=" + p.info.name);
8936            }
8937            final int NI = p.intents.size();
8938            int j;
8939            for (j = 0; j < NI; j++) {
8940                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8941                if (DEBUG_SHOW_INFO) {
8942                    Log.v(TAG, "    IntentFilter:");
8943                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8944                }
8945                if (!intent.debugCheck()) {
8946                    Log.w(TAG, "==> For Provider " + p.info.name);
8947                }
8948                addFilter(intent);
8949            }
8950        }
8951
8952        public final void removeProvider(PackageParser.Provider p) {
8953            mProviders.remove(p.getComponentName());
8954            if (DEBUG_SHOW_INFO) {
8955                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8956                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8957                Log.v(TAG, "    Class=" + p.info.name);
8958            }
8959            final int NI = p.intents.size();
8960            int j;
8961            for (j = 0; j < NI; j++) {
8962                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8963                if (DEBUG_SHOW_INFO) {
8964                    Log.v(TAG, "    IntentFilter:");
8965                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8966                }
8967                removeFilter(intent);
8968            }
8969        }
8970
8971        @Override
8972        protected boolean allowFilterResult(
8973                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8974            ProviderInfo filterPi = filter.provider.info;
8975            for (int i = dest.size() - 1; i >= 0; i--) {
8976                ProviderInfo destPi = dest.get(i).providerInfo;
8977                if (destPi.name == filterPi.name
8978                        && destPi.packageName == filterPi.packageName) {
8979                    return false;
8980                }
8981            }
8982            return true;
8983        }
8984
8985        @Override
8986        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8987            return new PackageParser.ProviderIntentInfo[size];
8988        }
8989
8990        @Override
8991        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8992            if (!sUserManager.exists(userId))
8993                return true;
8994            PackageParser.Package p = filter.provider.owner;
8995            if (p != null) {
8996                PackageSetting ps = (PackageSetting) p.mExtras;
8997                if (ps != null) {
8998                    // System apps are never considered stopped for purposes of
8999                    // filtering, because there may be no way for the user to
9000                    // actually re-launch them.
9001                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9002                            && ps.getStopped(userId);
9003                }
9004            }
9005            return false;
9006        }
9007
9008        @Override
9009        protected boolean isPackageForFilter(String packageName,
9010                PackageParser.ProviderIntentInfo info) {
9011            return packageName.equals(info.provider.owner.packageName);
9012        }
9013
9014        @Override
9015        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9016                int match, int userId) {
9017            if (!sUserManager.exists(userId))
9018                return null;
9019            final PackageParser.ProviderIntentInfo info = filter;
9020            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9021                return null;
9022            }
9023            final PackageParser.Provider provider = info.provider;
9024            if (mSafeMode && (provider.info.applicationInfo.flags
9025                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9026                return null;
9027            }
9028            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9029            if (ps == null) {
9030                return null;
9031            }
9032            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9033                    ps.readUserState(userId), userId);
9034            if (pi == null) {
9035                return null;
9036            }
9037            final ResolveInfo res = new ResolveInfo();
9038            res.providerInfo = pi;
9039            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9040                res.filter = filter;
9041            }
9042            res.priority = info.getPriority();
9043            res.preferredOrder = provider.owner.mPreferredOrder;
9044            res.match = match;
9045            res.isDefault = info.hasDefault;
9046            res.labelRes = info.labelRes;
9047            res.nonLocalizedLabel = info.nonLocalizedLabel;
9048            res.icon = info.icon;
9049            res.system = res.providerInfo.applicationInfo.isSystemApp();
9050            return res;
9051        }
9052
9053        @Override
9054        protected void sortResults(List<ResolveInfo> results) {
9055            Collections.sort(results, mResolvePrioritySorter);
9056        }
9057
9058        @Override
9059        protected void dumpFilter(PrintWriter out, String prefix,
9060                PackageParser.ProviderIntentInfo filter) {
9061            out.print(prefix);
9062            out.print(
9063                    Integer.toHexString(System.identityHashCode(filter.provider)));
9064            out.print(' ');
9065            filter.provider.printComponentShortName(out);
9066            out.print(" filter ");
9067            out.println(Integer.toHexString(System.identityHashCode(filter)));
9068        }
9069
9070        @Override
9071        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9072            return filter.provider;
9073        }
9074
9075        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9076            PackageParser.Provider provider = (PackageParser.Provider)label;
9077            out.print(prefix); out.print(
9078                    Integer.toHexString(System.identityHashCode(provider)));
9079                    out.print(' ');
9080                    provider.printComponentShortName(out);
9081            if (count > 1) {
9082                out.print(" ("); out.print(count); out.print(" filters)");
9083            }
9084            out.println();
9085        }
9086
9087        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9088                = new ArrayMap<ComponentName, PackageParser.Provider>();
9089        private int mFlags;
9090    };
9091
9092    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9093            new Comparator<ResolveInfo>() {
9094        public int compare(ResolveInfo r1, ResolveInfo r2) {
9095            int v1 = r1.priority;
9096            int v2 = r2.priority;
9097            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9098            if (v1 != v2) {
9099                return (v1 > v2) ? -1 : 1;
9100            }
9101            v1 = r1.preferredOrder;
9102            v2 = r2.preferredOrder;
9103            if (v1 != v2) {
9104                return (v1 > v2) ? -1 : 1;
9105            }
9106            if (r1.isDefault != r2.isDefault) {
9107                return r1.isDefault ? -1 : 1;
9108            }
9109            v1 = r1.match;
9110            v2 = r2.match;
9111            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9112            if (v1 != v2) {
9113                return (v1 > v2) ? -1 : 1;
9114            }
9115            if (r1.system != r2.system) {
9116                return r1.system ? -1 : 1;
9117            }
9118            return 0;
9119        }
9120    };
9121
9122    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9123            new Comparator<ProviderInfo>() {
9124        public int compare(ProviderInfo p1, ProviderInfo p2) {
9125            final int v1 = p1.initOrder;
9126            final int v2 = p2.initOrder;
9127            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9128        }
9129    };
9130
9131    final void sendPackageBroadcast(final String action, final String pkg,
9132            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9133            final int[] userIds) {
9134        mHandler.post(new Runnable() {
9135            @Override
9136            public void run() {
9137                try {
9138                    final IActivityManager am = ActivityManagerNative.getDefault();
9139                    if (am == null) return;
9140                    final int[] resolvedUserIds;
9141                    if (userIds == null) {
9142                        resolvedUserIds = am.getRunningUserIds();
9143                    } else {
9144                        resolvedUserIds = userIds;
9145                    }
9146                    for (int id : resolvedUserIds) {
9147                        final Intent intent = new Intent(action,
9148                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9149                        if (extras != null) {
9150                            intent.putExtras(extras);
9151                        }
9152                        if (targetPkg != null) {
9153                            intent.setPackage(targetPkg);
9154                        }
9155                        // Modify the UID when posting to other users
9156                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9157                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9158                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9159                            intent.putExtra(Intent.EXTRA_UID, uid);
9160                        }
9161                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9162                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9163                        if (DEBUG_BROADCASTS) {
9164                            RuntimeException here = new RuntimeException("here");
9165                            here.fillInStackTrace();
9166                            Slog.d(TAG, "Sending to user " + id + ": "
9167                                    + intent.toShortString(false, true, false, false)
9168                                    + " " + intent.getExtras(), here);
9169                        }
9170                        am.broadcastIntent(null, intent, null, finishedReceiver,
9171                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9172                                null, finishedReceiver != null, false, id);
9173                    }
9174                } catch (RemoteException ex) {
9175                }
9176            }
9177        });
9178    }
9179
9180    /**
9181     * Check if the external storage media is available. This is true if there
9182     * is a mounted external storage medium or if the external storage is
9183     * emulated.
9184     */
9185    private boolean isExternalMediaAvailable() {
9186        return mMediaMounted || Environment.isExternalStorageEmulated();
9187    }
9188
9189    @Override
9190    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9191        // writer
9192        synchronized (mPackages) {
9193            if (!isExternalMediaAvailable()) {
9194                // If the external storage is no longer mounted at this point,
9195                // the caller may not have been able to delete all of this
9196                // packages files and can not delete any more.  Bail.
9197                return null;
9198            }
9199            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9200            if (lastPackage != null) {
9201                pkgs.remove(lastPackage);
9202            }
9203            if (pkgs.size() > 0) {
9204                return pkgs.get(0);
9205            }
9206        }
9207        return null;
9208    }
9209
9210    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9211        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9212                userId, andCode ? 1 : 0, packageName);
9213        if (mSystemReady) {
9214            msg.sendToTarget();
9215        } else {
9216            if (mPostSystemReadyMessages == null) {
9217                mPostSystemReadyMessages = new ArrayList<>();
9218            }
9219            mPostSystemReadyMessages.add(msg);
9220        }
9221    }
9222
9223    void startCleaningPackages() {
9224        // reader
9225        synchronized (mPackages) {
9226            if (!isExternalMediaAvailable()) {
9227                return;
9228            }
9229            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9230                return;
9231            }
9232        }
9233        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9234        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9235        IActivityManager am = ActivityManagerNative.getDefault();
9236        if (am != null) {
9237            try {
9238                am.startService(null, intent, null, mContext.getOpPackageName(),
9239                        UserHandle.USER_OWNER);
9240            } catch (RemoteException e) {
9241            }
9242        }
9243    }
9244
9245    @Override
9246    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9247            int installFlags, String installerPackageName, VerificationParams verificationParams,
9248            String packageAbiOverride) {
9249        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9250                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9251    }
9252
9253    @Override
9254    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9255            int installFlags, String installerPackageName, VerificationParams verificationParams,
9256            String packageAbiOverride, int userId) {
9257        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9258
9259        final int callingUid = Binder.getCallingUid();
9260        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9261
9262        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9263            try {
9264                if (observer != null) {
9265                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9266                }
9267            } catch (RemoteException re) {
9268            }
9269            return;
9270        }
9271
9272        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9273            installFlags |= PackageManager.INSTALL_FROM_ADB;
9274
9275        } else {
9276            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9277            // about installerPackageName.
9278
9279            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9280            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9281        }
9282
9283        UserHandle user;
9284        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9285            user = UserHandle.ALL;
9286        } else {
9287            user = new UserHandle(userId);
9288        }
9289
9290        // Only system components can circumvent runtime permissions when installing.
9291        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9292                && mContext.checkCallingOrSelfPermission(Manifest.permission
9293                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9294            throw new SecurityException("You need the "
9295                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9296                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9297        }
9298
9299        verificationParams.setInstallerUid(callingUid);
9300
9301        final File originFile = new File(originPath);
9302        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9303
9304        final Message msg = mHandler.obtainMessage(INIT_COPY);
9305        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9306                null, verificationParams, user, packageAbiOverride);
9307        mHandler.sendMessage(msg);
9308    }
9309
9310    void installStage(String packageName, File stagedDir, String stagedCid,
9311            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9312            String installerPackageName, int installerUid, UserHandle user) {
9313        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9314                params.referrerUri, installerUid, null);
9315        verifParams.setInstallerUid(installerUid);
9316
9317        final OriginInfo origin;
9318        if (stagedDir != null) {
9319            origin = OriginInfo.fromStagedFile(stagedDir);
9320        } else {
9321            origin = OriginInfo.fromStagedContainer(stagedCid);
9322        }
9323
9324        final Message msg = mHandler.obtainMessage(INIT_COPY);
9325        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9326                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9327        mHandler.sendMessage(msg);
9328    }
9329
9330    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9331        Bundle extras = new Bundle(1);
9332        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9333
9334        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9335                packageName, extras, null, null, new int[] {userId});
9336        try {
9337            IActivityManager am = ActivityManagerNative.getDefault();
9338            final boolean isSystem =
9339                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9340            if (isSystem && am.isUserRunning(userId, false)) {
9341                // The just-installed/enabled app is bundled on the system, so presumed
9342                // to be able to run automatically without needing an explicit launch.
9343                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9344                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9345                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9346                        .setPackage(packageName);
9347                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9348                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9349            }
9350        } catch (RemoteException e) {
9351            // shouldn't happen
9352            Slog.w(TAG, "Unable to bootstrap installed package", e);
9353        }
9354    }
9355
9356    @Override
9357    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9358            int userId) {
9359        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9360        PackageSetting pkgSetting;
9361        final int uid = Binder.getCallingUid();
9362        enforceCrossUserPermission(uid, userId, true, true,
9363                "setApplicationHiddenSetting for user " + userId);
9364
9365        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9366            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9367            return false;
9368        }
9369
9370        long callingId = Binder.clearCallingIdentity();
9371        try {
9372            boolean sendAdded = false;
9373            boolean sendRemoved = false;
9374            // writer
9375            synchronized (mPackages) {
9376                pkgSetting = mSettings.mPackages.get(packageName);
9377                if (pkgSetting == null) {
9378                    return false;
9379                }
9380                if (pkgSetting.getHidden(userId) != hidden) {
9381                    pkgSetting.setHidden(hidden, userId);
9382                    mSettings.writePackageRestrictionsLPr(userId);
9383                    if (hidden) {
9384                        sendRemoved = true;
9385                    } else {
9386                        sendAdded = true;
9387                    }
9388                }
9389            }
9390            if (sendAdded) {
9391                sendPackageAddedForUser(packageName, pkgSetting, userId);
9392                return true;
9393            }
9394            if (sendRemoved) {
9395                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9396                        "hiding pkg");
9397                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9398            }
9399        } finally {
9400            Binder.restoreCallingIdentity(callingId);
9401        }
9402        return false;
9403    }
9404
9405    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9406            int userId) {
9407        final PackageRemovedInfo info = new PackageRemovedInfo();
9408        info.removedPackage = packageName;
9409        info.removedUsers = new int[] {userId};
9410        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9411        info.sendBroadcast(false, false, false);
9412    }
9413
9414    /**
9415     * Returns true if application is not found or there was an error. Otherwise it returns
9416     * the hidden state of the package for the given user.
9417     */
9418    @Override
9419    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9420        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9421        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9422                false, "getApplicationHidden for user " + userId);
9423        PackageSetting pkgSetting;
9424        long callingId = Binder.clearCallingIdentity();
9425        try {
9426            // writer
9427            synchronized (mPackages) {
9428                pkgSetting = mSettings.mPackages.get(packageName);
9429                if (pkgSetting == null) {
9430                    return true;
9431                }
9432                return pkgSetting.getHidden(userId);
9433            }
9434        } finally {
9435            Binder.restoreCallingIdentity(callingId);
9436        }
9437    }
9438
9439    /**
9440     * @hide
9441     */
9442    @Override
9443    public int installExistingPackageAsUser(String packageName, int userId) {
9444        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9445                null);
9446        PackageSetting pkgSetting;
9447        final int uid = Binder.getCallingUid();
9448        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9449                + userId);
9450        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9451            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9452        }
9453
9454        long callingId = Binder.clearCallingIdentity();
9455        try {
9456            boolean sendAdded = false;
9457
9458            // writer
9459            synchronized (mPackages) {
9460                pkgSetting = mSettings.mPackages.get(packageName);
9461                if (pkgSetting == null) {
9462                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9463                }
9464                if (!pkgSetting.getInstalled(userId)) {
9465                    pkgSetting.setInstalled(true, userId);
9466                    pkgSetting.setHidden(false, userId);
9467                    mSettings.writePackageRestrictionsLPr(userId);
9468                    sendAdded = true;
9469                }
9470            }
9471
9472            if (sendAdded) {
9473                sendPackageAddedForUser(packageName, pkgSetting, userId);
9474            }
9475        } finally {
9476            Binder.restoreCallingIdentity(callingId);
9477        }
9478
9479        return PackageManager.INSTALL_SUCCEEDED;
9480    }
9481
9482    boolean isUserRestricted(int userId, String restrictionKey) {
9483        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9484        if (restrictions.getBoolean(restrictionKey, false)) {
9485            Log.w(TAG, "User is restricted: " + restrictionKey);
9486            return true;
9487        }
9488        return false;
9489    }
9490
9491    @Override
9492    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9493        mContext.enforceCallingOrSelfPermission(
9494                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9495                "Only package verification agents can verify applications");
9496
9497        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9498        final PackageVerificationResponse response = new PackageVerificationResponse(
9499                verificationCode, Binder.getCallingUid());
9500        msg.arg1 = id;
9501        msg.obj = response;
9502        mHandler.sendMessage(msg);
9503    }
9504
9505    @Override
9506    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9507            long millisecondsToDelay) {
9508        mContext.enforceCallingOrSelfPermission(
9509                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9510                "Only package verification agents can extend verification timeouts");
9511
9512        final PackageVerificationState state = mPendingVerification.get(id);
9513        final PackageVerificationResponse response = new PackageVerificationResponse(
9514                verificationCodeAtTimeout, Binder.getCallingUid());
9515
9516        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9517            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9518        }
9519        if (millisecondsToDelay < 0) {
9520            millisecondsToDelay = 0;
9521        }
9522        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9523                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9524            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9525        }
9526
9527        if ((state != null) && !state.timeoutExtended()) {
9528            state.extendTimeout();
9529
9530            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9531            msg.arg1 = id;
9532            msg.obj = response;
9533            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9534        }
9535    }
9536
9537    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9538            int verificationCode, UserHandle user) {
9539        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9540        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9541        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9542        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9543        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9544
9545        mContext.sendBroadcastAsUser(intent, user,
9546                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9547    }
9548
9549    private ComponentName matchComponentForVerifier(String packageName,
9550            List<ResolveInfo> receivers) {
9551        ActivityInfo targetReceiver = null;
9552
9553        final int NR = receivers.size();
9554        for (int i = 0; i < NR; i++) {
9555            final ResolveInfo info = receivers.get(i);
9556            if (info.activityInfo == null) {
9557                continue;
9558            }
9559
9560            if (packageName.equals(info.activityInfo.packageName)) {
9561                targetReceiver = info.activityInfo;
9562                break;
9563            }
9564        }
9565
9566        if (targetReceiver == null) {
9567            return null;
9568        }
9569
9570        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9571    }
9572
9573    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9574            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9575        if (pkgInfo.verifiers.length == 0) {
9576            return null;
9577        }
9578
9579        final int N = pkgInfo.verifiers.length;
9580        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9581        for (int i = 0; i < N; i++) {
9582            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9583
9584            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9585                    receivers);
9586            if (comp == null) {
9587                continue;
9588            }
9589
9590            final int verifierUid = getUidForVerifier(verifierInfo);
9591            if (verifierUid == -1) {
9592                continue;
9593            }
9594
9595            if (DEBUG_VERIFY) {
9596                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9597                        + " with the correct signature");
9598            }
9599            sufficientVerifiers.add(comp);
9600            verificationState.addSufficientVerifier(verifierUid);
9601        }
9602
9603        return sufficientVerifiers;
9604    }
9605
9606    private int getUidForVerifier(VerifierInfo verifierInfo) {
9607        synchronized (mPackages) {
9608            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9609            if (pkg == null) {
9610                return -1;
9611            } else if (pkg.mSignatures.length != 1) {
9612                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9613                        + " has more than one signature; ignoring");
9614                return -1;
9615            }
9616
9617            /*
9618             * If the public key of the package's signature does not match
9619             * our expected public key, then this is a different package and
9620             * we should skip.
9621             */
9622
9623            final byte[] expectedPublicKey;
9624            try {
9625                final Signature verifierSig = pkg.mSignatures[0];
9626                final PublicKey publicKey = verifierSig.getPublicKey();
9627                expectedPublicKey = publicKey.getEncoded();
9628            } catch (CertificateException e) {
9629                return -1;
9630            }
9631
9632            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9633
9634            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9635                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9636                        + " does not have the expected public key; ignoring");
9637                return -1;
9638            }
9639
9640            return pkg.applicationInfo.uid;
9641        }
9642    }
9643
9644    @Override
9645    public void finishPackageInstall(int token) {
9646        enforceSystemOrRoot("Only the system is allowed to finish installs");
9647
9648        if (DEBUG_INSTALL) {
9649            Slog.v(TAG, "BM finishing package install for " + token);
9650        }
9651
9652        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9653        mHandler.sendMessage(msg);
9654    }
9655
9656    /**
9657     * Get the verification agent timeout.
9658     *
9659     * @return verification timeout in milliseconds
9660     */
9661    private long getVerificationTimeout() {
9662        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9663                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9664                DEFAULT_VERIFICATION_TIMEOUT);
9665    }
9666
9667    /**
9668     * Get the default verification agent response code.
9669     *
9670     * @return default verification response code
9671     */
9672    private int getDefaultVerificationResponse() {
9673        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9674                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9675                DEFAULT_VERIFICATION_RESPONSE);
9676    }
9677
9678    /**
9679     * Check whether or not package verification has been enabled.
9680     *
9681     * @return true if verification should be performed
9682     */
9683    private boolean isVerificationEnabled(int userId, int installFlags) {
9684        if (!DEFAULT_VERIFY_ENABLE) {
9685            return false;
9686        }
9687
9688        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9689
9690        // Check if installing from ADB
9691        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9692            // Do not run verification in a test harness environment
9693            if (ActivityManager.isRunningInTestHarness()) {
9694                return false;
9695            }
9696            if (ensureVerifyAppsEnabled) {
9697                return true;
9698            }
9699            // Check if the developer does not want package verification for ADB installs
9700            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9701                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9702                return false;
9703            }
9704        }
9705
9706        if (ensureVerifyAppsEnabled) {
9707            return true;
9708        }
9709
9710        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9711                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9712    }
9713
9714    @Override
9715    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9716            throws RemoteException {
9717        mContext.enforceCallingOrSelfPermission(
9718                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9719                "Only intentfilter verification agents can verify applications");
9720
9721        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9722        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9723                Binder.getCallingUid(), verificationCode, failedDomains);
9724        msg.arg1 = id;
9725        msg.obj = response;
9726        mHandler.sendMessage(msg);
9727    }
9728
9729    @Override
9730    public int getIntentVerificationStatus(String packageName, int userId) {
9731        synchronized (mPackages) {
9732            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9733        }
9734    }
9735
9736    @Override
9737    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9738        mContext.enforceCallingOrSelfPermission(
9739                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9740
9741        boolean result = false;
9742        synchronized (mPackages) {
9743            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9744        }
9745        if (result) {
9746            scheduleWritePackageRestrictionsLocked(userId);
9747        }
9748        return result;
9749    }
9750
9751    @Override
9752    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9753        synchronized (mPackages) {
9754            return mSettings.getIntentFilterVerificationsLPr(packageName);
9755        }
9756    }
9757
9758    @Override
9759    public List<IntentFilter> getAllIntentFilters(String packageName) {
9760        if (TextUtils.isEmpty(packageName)) {
9761            return Collections.<IntentFilter>emptyList();
9762        }
9763        synchronized (mPackages) {
9764            PackageParser.Package pkg = mPackages.get(packageName);
9765            if (pkg == null || pkg.activities == null) {
9766                return Collections.<IntentFilter>emptyList();
9767            }
9768            final int count = pkg.activities.size();
9769            ArrayList<IntentFilter> result = new ArrayList<>();
9770            for (int n=0; n<count; n++) {
9771                PackageParser.Activity activity = pkg.activities.get(n);
9772                if (activity.intents != null || activity.intents.size() > 0) {
9773                    result.addAll(activity.intents);
9774                }
9775            }
9776            return result;
9777        }
9778    }
9779
9780    @Override
9781    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9782        mContext.enforceCallingOrSelfPermission(
9783                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9784
9785        synchronized (mPackages) {
9786            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9787            if (packageName != null) {
9788                result |= updateIntentVerificationStatus(packageName,
9789                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9790                        UserHandle.myUserId());
9791                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9792                        packageName, userId);
9793            }
9794            return result;
9795        }
9796    }
9797
9798    @Override
9799    public String getDefaultBrowserPackageName(int userId) {
9800        synchronized (mPackages) {
9801            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9802        }
9803    }
9804
9805    /**
9806     * Get the "allow unknown sources" setting.
9807     *
9808     * @return the current "allow unknown sources" setting
9809     */
9810    private int getUnknownSourcesSettings() {
9811        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9812                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9813                -1);
9814    }
9815
9816    @Override
9817    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9818        final int uid = Binder.getCallingUid();
9819        // writer
9820        synchronized (mPackages) {
9821            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9822            if (targetPackageSetting == null) {
9823                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9824            }
9825
9826            PackageSetting installerPackageSetting;
9827            if (installerPackageName != null) {
9828                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9829                if (installerPackageSetting == null) {
9830                    throw new IllegalArgumentException("Unknown installer package: "
9831                            + installerPackageName);
9832                }
9833            } else {
9834                installerPackageSetting = null;
9835            }
9836
9837            Signature[] callerSignature;
9838            Object obj = mSettings.getUserIdLPr(uid);
9839            if (obj != null) {
9840                if (obj instanceof SharedUserSetting) {
9841                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9842                } else if (obj instanceof PackageSetting) {
9843                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9844                } else {
9845                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9846                }
9847            } else {
9848                throw new SecurityException("Unknown calling uid " + uid);
9849            }
9850
9851            // Verify: can't set installerPackageName to a package that is
9852            // not signed with the same cert as the caller.
9853            if (installerPackageSetting != null) {
9854                if (compareSignatures(callerSignature,
9855                        installerPackageSetting.signatures.mSignatures)
9856                        != PackageManager.SIGNATURE_MATCH) {
9857                    throw new SecurityException(
9858                            "Caller does not have same cert as new installer package "
9859                            + installerPackageName);
9860                }
9861            }
9862
9863            // Verify: if target already has an installer package, it must
9864            // be signed with the same cert as the caller.
9865            if (targetPackageSetting.installerPackageName != null) {
9866                PackageSetting setting = mSettings.mPackages.get(
9867                        targetPackageSetting.installerPackageName);
9868                // If the currently set package isn't valid, then it's always
9869                // okay to change it.
9870                if (setting != null) {
9871                    if (compareSignatures(callerSignature,
9872                            setting.signatures.mSignatures)
9873                            != PackageManager.SIGNATURE_MATCH) {
9874                        throw new SecurityException(
9875                                "Caller does not have same cert as old installer package "
9876                                + targetPackageSetting.installerPackageName);
9877                    }
9878                }
9879            }
9880
9881            // Okay!
9882            targetPackageSetting.installerPackageName = installerPackageName;
9883            scheduleWriteSettingsLocked();
9884        }
9885    }
9886
9887    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9888        // Queue up an async operation since the package installation may take a little while.
9889        mHandler.post(new Runnable() {
9890            public void run() {
9891                mHandler.removeCallbacks(this);
9892                 // Result object to be returned
9893                PackageInstalledInfo res = new PackageInstalledInfo();
9894                res.returnCode = currentStatus;
9895                res.uid = -1;
9896                res.pkg = null;
9897                res.removedInfo = new PackageRemovedInfo();
9898                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9899                    args.doPreInstall(res.returnCode);
9900                    synchronized (mInstallLock) {
9901                        installPackageLI(args, res);
9902                    }
9903                    args.doPostInstall(res.returnCode, res.uid);
9904                }
9905
9906                // A restore should be performed at this point if (a) the install
9907                // succeeded, (b) the operation is not an update, and (c) the new
9908                // package has not opted out of backup participation.
9909                final boolean update = res.removedInfo.removedPackage != null;
9910                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9911                boolean doRestore = !update
9912                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9913
9914                // Set up the post-install work request bookkeeping.  This will be used
9915                // and cleaned up by the post-install event handling regardless of whether
9916                // there's a restore pass performed.  Token values are >= 1.
9917                int token;
9918                if (mNextInstallToken < 0) mNextInstallToken = 1;
9919                token = mNextInstallToken++;
9920
9921                PostInstallData data = new PostInstallData(args, res);
9922                mRunningInstalls.put(token, data);
9923                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9924
9925                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9926                    // Pass responsibility to the Backup Manager.  It will perform a
9927                    // restore if appropriate, then pass responsibility back to the
9928                    // Package Manager to run the post-install observer callbacks
9929                    // and broadcasts.
9930                    IBackupManager bm = IBackupManager.Stub.asInterface(
9931                            ServiceManager.getService(Context.BACKUP_SERVICE));
9932                    if (bm != null) {
9933                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9934                                + " to BM for possible restore");
9935                        try {
9936                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9937                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9938                            } else {
9939                                doRestore = false;
9940                            }
9941                        } catch (RemoteException e) {
9942                            // can't happen; the backup manager is local
9943                        } catch (Exception e) {
9944                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9945                            doRestore = false;
9946                        }
9947                    } else {
9948                        Slog.e(TAG, "Backup Manager not found!");
9949                        doRestore = false;
9950                    }
9951                }
9952
9953                if (!doRestore) {
9954                    // No restore possible, or the Backup Manager was mysteriously not
9955                    // available -- just fire the post-install work request directly.
9956                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9957                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9958                    mHandler.sendMessage(msg);
9959                }
9960            }
9961        });
9962    }
9963
9964    private abstract class HandlerParams {
9965        private static final int MAX_RETRIES = 4;
9966
9967        /**
9968         * Number of times startCopy() has been attempted and had a non-fatal
9969         * error.
9970         */
9971        private int mRetries = 0;
9972
9973        /** User handle for the user requesting the information or installation. */
9974        private final UserHandle mUser;
9975
9976        HandlerParams(UserHandle user) {
9977            mUser = user;
9978        }
9979
9980        UserHandle getUser() {
9981            return mUser;
9982        }
9983
9984        final boolean startCopy() {
9985            boolean res;
9986            try {
9987                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9988
9989                if (++mRetries > MAX_RETRIES) {
9990                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9991                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9992                    handleServiceError();
9993                    return false;
9994                } else {
9995                    handleStartCopy();
9996                    res = true;
9997                }
9998            } catch (RemoteException e) {
9999                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10000                mHandler.sendEmptyMessage(MCS_RECONNECT);
10001                res = false;
10002            }
10003            handleReturnCode();
10004            return res;
10005        }
10006
10007        final void serviceError() {
10008            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10009            handleServiceError();
10010            handleReturnCode();
10011        }
10012
10013        abstract void handleStartCopy() throws RemoteException;
10014        abstract void handleServiceError();
10015        abstract void handleReturnCode();
10016    }
10017
10018    class MeasureParams extends HandlerParams {
10019        private final PackageStats mStats;
10020        private boolean mSuccess;
10021
10022        private final IPackageStatsObserver mObserver;
10023
10024        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10025            super(new UserHandle(stats.userHandle));
10026            mObserver = observer;
10027            mStats = stats;
10028        }
10029
10030        @Override
10031        public String toString() {
10032            return "MeasureParams{"
10033                + Integer.toHexString(System.identityHashCode(this))
10034                + " " + mStats.packageName + "}";
10035        }
10036
10037        @Override
10038        void handleStartCopy() throws RemoteException {
10039            synchronized (mInstallLock) {
10040                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10041            }
10042
10043            if (mSuccess) {
10044                final boolean mounted;
10045                if (Environment.isExternalStorageEmulated()) {
10046                    mounted = true;
10047                } else {
10048                    final String status = Environment.getExternalStorageState();
10049                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10050                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10051                }
10052
10053                if (mounted) {
10054                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10055
10056                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10057                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10058
10059                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10060                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10061
10062                    // Always subtract cache size, since it's a subdirectory
10063                    mStats.externalDataSize -= mStats.externalCacheSize;
10064
10065                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10066                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10067
10068                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10069                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10070                }
10071            }
10072        }
10073
10074        @Override
10075        void handleReturnCode() {
10076            if (mObserver != null) {
10077                try {
10078                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10079                } catch (RemoteException e) {
10080                    Slog.i(TAG, "Observer no longer exists.");
10081                }
10082            }
10083        }
10084
10085        @Override
10086        void handleServiceError() {
10087            Slog.e(TAG, "Could not measure application " + mStats.packageName
10088                            + " external storage");
10089        }
10090    }
10091
10092    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10093            throws RemoteException {
10094        long result = 0;
10095        for (File path : paths) {
10096            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10097        }
10098        return result;
10099    }
10100
10101    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10102        for (File path : paths) {
10103            try {
10104                mcs.clearDirectory(path.getAbsolutePath());
10105            } catch (RemoteException e) {
10106            }
10107        }
10108    }
10109
10110    static class OriginInfo {
10111        /**
10112         * Location where install is coming from, before it has been
10113         * copied/renamed into place. This could be a single monolithic APK
10114         * file, or a cluster directory. This location may be untrusted.
10115         */
10116        final File file;
10117        final String cid;
10118
10119        /**
10120         * Flag indicating that {@link #file} or {@link #cid} has already been
10121         * staged, meaning downstream users don't need to defensively copy the
10122         * contents.
10123         */
10124        final boolean staged;
10125
10126        /**
10127         * Flag indicating that {@link #file} or {@link #cid} is an already
10128         * installed app that is being moved.
10129         */
10130        final boolean existing;
10131
10132        final String resolvedPath;
10133        final File resolvedFile;
10134
10135        static OriginInfo fromNothing() {
10136            return new OriginInfo(null, null, false, false);
10137        }
10138
10139        static OriginInfo fromUntrustedFile(File file) {
10140            return new OriginInfo(file, null, false, false);
10141        }
10142
10143        static OriginInfo fromExistingFile(File file) {
10144            return new OriginInfo(file, null, false, true);
10145        }
10146
10147        static OriginInfo fromStagedFile(File file) {
10148            return new OriginInfo(file, null, true, false);
10149        }
10150
10151        static OriginInfo fromStagedContainer(String cid) {
10152            return new OriginInfo(null, cid, true, false);
10153        }
10154
10155        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10156            this.file = file;
10157            this.cid = cid;
10158            this.staged = staged;
10159            this.existing = existing;
10160
10161            if (cid != null) {
10162                resolvedPath = PackageHelper.getSdDir(cid);
10163                resolvedFile = new File(resolvedPath);
10164            } else if (file != null) {
10165                resolvedPath = file.getAbsolutePath();
10166                resolvedFile = file;
10167            } else {
10168                resolvedPath = null;
10169                resolvedFile = null;
10170            }
10171        }
10172    }
10173
10174    class MoveInfo {
10175        final int moveId;
10176        final String fromUuid;
10177        final String toUuid;
10178        final String packageName;
10179        final String dataAppName;
10180        final int appId;
10181        final String seinfo;
10182
10183        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10184                String dataAppName, int appId, String seinfo) {
10185            this.moveId = moveId;
10186            this.fromUuid = fromUuid;
10187            this.toUuid = toUuid;
10188            this.packageName = packageName;
10189            this.dataAppName = dataAppName;
10190            this.appId = appId;
10191            this.seinfo = seinfo;
10192        }
10193    }
10194
10195    class InstallParams extends HandlerParams {
10196        final OriginInfo origin;
10197        final MoveInfo move;
10198        final IPackageInstallObserver2 observer;
10199        int installFlags;
10200        final String installerPackageName;
10201        final String volumeUuid;
10202        final VerificationParams verificationParams;
10203        private InstallArgs mArgs;
10204        private int mRet;
10205        final String packageAbiOverride;
10206
10207        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10208                int installFlags, String installerPackageName, String volumeUuid,
10209                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10210            super(user);
10211            this.origin = origin;
10212            this.move = move;
10213            this.observer = observer;
10214            this.installFlags = installFlags;
10215            this.installerPackageName = installerPackageName;
10216            this.volumeUuid = volumeUuid;
10217            this.verificationParams = verificationParams;
10218            this.packageAbiOverride = packageAbiOverride;
10219        }
10220
10221        @Override
10222        public String toString() {
10223            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10224                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10225        }
10226
10227        public ManifestDigest getManifestDigest() {
10228            if (verificationParams == null) {
10229                return null;
10230            }
10231            return verificationParams.getManifestDigest();
10232        }
10233
10234        private int installLocationPolicy(PackageInfoLite pkgLite) {
10235            String packageName = pkgLite.packageName;
10236            int installLocation = pkgLite.installLocation;
10237            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10238            // reader
10239            synchronized (mPackages) {
10240                PackageParser.Package pkg = mPackages.get(packageName);
10241                if (pkg != null) {
10242                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10243                        // Check for downgrading.
10244                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10245                            try {
10246                                checkDowngrade(pkg, pkgLite);
10247                            } catch (PackageManagerException e) {
10248                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10249                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10250                            }
10251                        }
10252                        // Check for updated system application.
10253                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10254                            if (onSd) {
10255                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10256                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10257                            }
10258                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10259                        } else {
10260                            if (onSd) {
10261                                // Install flag overrides everything.
10262                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10263                            }
10264                            // If current upgrade specifies particular preference
10265                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10266                                // Application explicitly specified internal.
10267                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10268                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10269                                // App explictly prefers external. Let policy decide
10270                            } else {
10271                                // Prefer previous location
10272                                if (isExternal(pkg)) {
10273                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10274                                }
10275                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10276                            }
10277                        }
10278                    } else {
10279                        // Invalid install. Return error code
10280                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10281                    }
10282                }
10283            }
10284            // All the special cases have been taken care of.
10285            // Return result based on recommended install location.
10286            if (onSd) {
10287                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10288            }
10289            return pkgLite.recommendedInstallLocation;
10290        }
10291
10292        /*
10293         * Invoke remote method to get package information and install
10294         * location values. Override install location based on default
10295         * policy if needed and then create install arguments based
10296         * on the install location.
10297         */
10298        public void handleStartCopy() throws RemoteException {
10299            int ret = PackageManager.INSTALL_SUCCEEDED;
10300
10301            // If we're already staged, we've firmly committed to an install location
10302            if (origin.staged) {
10303                if (origin.file != null) {
10304                    installFlags |= PackageManager.INSTALL_INTERNAL;
10305                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10306                } else if (origin.cid != null) {
10307                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10308                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10309                } else {
10310                    throw new IllegalStateException("Invalid stage location");
10311                }
10312            }
10313
10314            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10315            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10316
10317            PackageInfoLite pkgLite = null;
10318
10319            if (onInt && onSd) {
10320                // Check if both bits are set.
10321                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10322                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10323            } else {
10324                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10325                        packageAbiOverride);
10326
10327                /*
10328                 * If we have too little free space, try to free cache
10329                 * before giving up.
10330                 */
10331                if (!origin.staged && pkgLite.recommendedInstallLocation
10332                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10333                    // TODO: focus freeing disk space on the target device
10334                    final StorageManager storage = StorageManager.from(mContext);
10335                    final long lowThreshold = storage.getStorageLowBytes(
10336                            Environment.getDataDirectory());
10337
10338                    final long sizeBytes = mContainerService.calculateInstalledSize(
10339                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10340
10341                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10342                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10343                                installFlags, packageAbiOverride);
10344                    }
10345
10346                    /*
10347                     * The cache free must have deleted the file we
10348                     * downloaded to install.
10349                     *
10350                     * TODO: fix the "freeCache" call to not delete
10351                     *       the file we care about.
10352                     */
10353                    if (pkgLite.recommendedInstallLocation
10354                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10355                        pkgLite.recommendedInstallLocation
10356                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10357                    }
10358                }
10359            }
10360
10361            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10362                int loc = pkgLite.recommendedInstallLocation;
10363                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10364                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10365                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10366                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10367                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10368                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10369                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10370                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10371                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10372                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10373                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10374                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10375                } else {
10376                    // Override with defaults if needed.
10377                    loc = installLocationPolicy(pkgLite);
10378                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10379                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10380                    } else if (!onSd && !onInt) {
10381                        // Override install location with flags
10382                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10383                            // Set the flag to install on external media.
10384                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10385                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10386                        } else {
10387                            // Make sure the flag for installing on external
10388                            // media is unset
10389                            installFlags |= PackageManager.INSTALL_INTERNAL;
10390                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10391                        }
10392                    }
10393                }
10394            }
10395
10396            final InstallArgs args = createInstallArgs(this);
10397            mArgs = args;
10398
10399            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10400                 /*
10401                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10402                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10403                 */
10404                int userIdentifier = getUser().getIdentifier();
10405                if (userIdentifier == UserHandle.USER_ALL
10406                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10407                    userIdentifier = UserHandle.USER_OWNER;
10408                }
10409
10410                /*
10411                 * Determine if we have any installed package verifiers. If we
10412                 * do, then we'll defer to them to verify the packages.
10413                 */
10414                final int requiredUid = mRequiredVerifierPackage == null ? -1
10415                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10416                if (!origin.existing && requiredUid != -1
10417                        && isVerificationEnabled(userIdentifier, installFlags)) {
10418                    final Intent verification = new Intent(
10419                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10420                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10421                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10422                            PACKAGE_MIME_TYPE);
10423                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10424
10425                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10426                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10427                            0 /* TODO: Which userId? */);
10428
10429                    if (DEBUG_VERIFY) {
10430                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10431                                + verification.toString() + " with " + pkgLite.verifiers.length
10432                                + " optional verifiers");
10433                    }
10434
10435                    final int verificationId = mPendingVerificationToken++;
10436
10437                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10438
10439                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10440                            installerPackageName);
10441
10442                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10443                            installFlags);
10444
10445                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10446                            pkgLite.packageName);
10447
10448                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10449                            pkgLite.versionCode);
10450
10451                    if (verificationParams != null) {
10452                        if (verificationParams.getVerificationURI() != null) {
10453                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10454                                 verificationParams.getVerificationURI());
10455                        }
10456                        if (verificationParams.getOriginatingURI() != null) {
10457                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10458                                  verificationParams.getOriginatingURI());
10459                        }
10460                        if (verificationParams.getReferrer() != null) {
10461                            verification.putExtra(Intent.EXTRA_REFERRER,
10462                                  verificationParams.getReferrer());
10463                        }
10464                        if (verificationParams.getOriginatingUid() >= 0) {
10465                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10466                                  verificationParams.getOriginatingUid());
10467                        }
10468                        if (verificationParams.getInstallerUid() >= 0) {
10469                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10470                                  verificationParams.getInstallerUid());
10471                        }
10472                    }
10473
10474                    final PackageVerificationState verificationState = new PackageVerificationState(
10475                            requiredUid, args);
10476
10477                    mPendingVerification.append(verificationId, verificationState);
10478
10479                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10480                            receivers, verificationState);
10481
10482                    /*
10483                     * If any sufficient verifiers were listed in the package
10484                     * manifest, attempt to ask them.
10485                     */
10486                    if (sufficientVerifiers != null) {
10487                        final int N = sufficientVerifiers.size();
10488                        if (N == 0) {
10489                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10490                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10491                        } else {
10492                            for (int i = 0; i < N; i++) {
10493                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10494
10495                                final Intent sufficientIntent = new Intent(verification);
10496                                sufficientIntent.setComponent(verifierComponent);
10497
10498                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10499                            }
10500                        }
10501                    }
10502
10503                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10504                            mRequiredVerifierPackage, receivers);
10505                    if (ret == PackageManager.INSTALL_SUCCEEDED
10506                            && mRequiredVerifierPackage != null) {
10507                        /*
10508                         * Send the intent to the required verification agent,
10509                         * but only start the verification timeout after the
10510                         * target BroadcastReceivers have run.
10511                         */
10512                        verification.setComponent(requiredVerifierComponent);
10513                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10514                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10515                                new BroadcastReceiver() {
10516                                    @Override
10517                                    public void onReceive(Context context, Intent intent) {
10518                                        final Message msg = mHandler
10519                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10520                                        msg.arg1 = verificationId;
10521                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10522                                    }
10523                                }, null, 0, null, null);
10524
10525                        /*
10526                         * We don't want the copy to proceed until verification
10527                         * succeeds, so null out this field.
10528                         */
10529                        mArgs = null;
10530                    }
10531                } else {
10532                    /*
10533                     * No package verification is enabled, so immediately start
10534                     * the remote call to initiate copy using temporary file.
10535                     */
10536                    ret = args.copyApk(mContainerService, true);
10537                }
10538            }
10539
10540            mRet = ret;
10541        }
10542
10543        @Override
10544        void handleReturnCode() {
10545            // If mArgs is null, then MCS couldn't be reached. When it
10546            // reconnects, it will try again to install. At that point, this
10547            // will succeed.
10548            if (mArgs != null) {
10549                processPendingInstall(mArgs, mRet);
10550            }
10551        }
10552
10553        @Override
10554        void handleServiceError() {
10555            mArgs = createInstallArgs(this);
10556            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10557        }
10558
10559        public boolean isForwardLocked() {
10560            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10561        }
10562    }
10563
10564    /**
10565     * Used during creation of InstallArgs
10566     *
10567     * @param installFlags package installation flags
10568     * @return true if should be installed on external storage
10569     */
10570    private static boolean installOnExternalAsec(int installFlags) {
10571        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10572            return false;
10573        }
10574        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10575            return true;
10576        }
10577        return false;
10578    }
10579
10580    /**
10581     * Used during creation of InstallArgs
10582     *
10583     * @param installFlags package installation flags
10584     * @return true if should be installed as forward locked
10585     */
10586    private static boolean installForwardLocked(int installFlags) {
10587        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10588    }
10589
10590    private InstallArgs createInstallArgs(InstallParams params) {
10591        if (params.move != null) {
10592            return new MoveInstallArgs(params);
10593        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10594            return new AsecInstallArgs(params);
10595        } else {
10596            return new FileInstallArgs(params);
10597        }
10598    }
10599
10600    /**
10601     * Create args that describe an existing installed package. Typically used
10602     * when cleaning up old installs, or used as a move source.
10603     */
10604    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10605            String resourcePath, String[] instructionSets) {
10606        final boolean isInAsec;
10607        if (installOnExternalAsec(installFlags)) {
10608            /* Apps on SD card are always in ASEC containers. */
10609            isInAsec = true;
10610        } else if (installForwardLocked(installFlags)
10611                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10612            /*
10613             * Forward-locked apps are only in ASEC containers if they're the
10614             * new style
10615             */
10616            isInAsec = true;
10617        } else {
10618            isInAsec = false;
10619        }
10620
10621        if (isInAsec) {
10622            return new AsecInstallArgs(codePath, instructionSets,
10623                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10624        } else {
10625            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10626        }
10627    }
10628
10629    static abstract class InstallArgs {
10630        /** @see InstallParams#origin */
10631        final OriginInfo origin;
10632        /** @see InstallParams#move */
10633        final MoveInfo move;
10634
10635        final IPackageInstallObserver2 observer;
10636        // Always refers to PackageManager flags only
10637        final int installFlags;
10638        final String installerPackageName;
10639        final String volumeUuid;
10640        final ManifestDigest manifestDigest;
10641        final UserHandle user;
10642        final String abiOverride;
10643
10644        // The list of instruction sets supported by this app. This is currently
10645        // only used during the rmdex() phase to clean up resources. We can get rid of this
10646        // if we move dex files under the common app path.
10647        /* nullable */ String[] instructionSets;
10648
10649        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10650                int installFlags, String installerPackageName, String volumeUuid,
10651                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10652                String abiOverride) {
10653            this.origin = origin;
10654            this.move = move;
10655            this.installFlags = installFlags;
10656            this.observer = observer;
10657            this.installerPackageName = installerPackageName;
10658            this.volumeUuid = volumeUuid;
10659            this.manifestDigest = manifestDigest;
10660            this.user = user;
10661            this.instructionSets = instructionSets;
10662            this.abiOverride = abiOverride;
10663        }
10664
10665        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10666        abstract int doPreInstall(int status);
10667
10668        /**
10669         * Rename package into final resting place. All paths on the given
10670         * scanned package should be updated to reflect the rename.
10671         */
10672        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10673        abstract int doPostInstall(int status, int uid);
10674
10675        /** @see PackageSettingBase#codePathString */
10676        abstract String getCodePath();
10677        /** @see PackageSettingBase#resourcePathString */
10678        abstract String getResourcePath();
10679
10680        // Need installer lock especially for dex file removal.
10681        abstract void cleanUpResourcesLI();
10682        abstract boolean doPostDeleteLI(boolean delete);
10683
10684        /**
10685         * Called before the source arguments are copied. This is used mostly
10686         * for MoveParams when it needs to read the source file to put it in the
10687         * destination.
10688         */
10689        int doPreCopy() {
10690            return PackageManager.INSTALL_SUCCEEDED;
10691        }
10692
10693        /**
10694         * Called after the source arguments are copied. This is used mostly for
10695         * MoveParams when it needs to read the source file to put it in the
10696         * destination.
10697         *
10698         * @return
10699         */
10700        int doPostCopy(int uid) {
10701            return PackageManager.INSTALL_SUCCEEDED;
10702        }
10703
10704        protected boolean isFwdLocked() {
10705            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10706        }
10707
10708        protected boolean isExternalAsec() {
10709            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10710        }
10711
10712        UserHandle getUser() {
10713            return user;
10714        }
10715    }
10716
10717    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10718        if (!allCodePaths.isEmpty()) {
10719            if (instructionSets == null) {
10720                throw new IllegalStateException("instructionSet == null");
10721            }
10722            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10723            for (String codePath : allCodePaths) {
10724                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10725                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10726                    if (retCode < 0) {
10727                        Slog.w(TAG, "Couldn't remove dex file for package: "
10728                                + " at location " + codePath + ", retcode=" + retCode);
10729                        // we don't consider this to be a failure of the core package deletion
10730                    }
10731                }
10732            }
10733        }
10734    }
10735
10736    /**
10737     * Logic to handle installation of non-ASEC applications, including copying
10738     * and renaming logic.
10739     */
10740    class FileInstallArgs extends InstallArgs {
10741        private File codeFile;
10742        private File resourceFile;
10743
10744        // Example topology:
10745        // /data/app/com.example/base.apk
10746        // /data/app/com.example/split_foo.apk
10747        // /data/app/com.example/lib/arm/libfoo.so
10748        // /data/app/com.example/lib/arm64/libfoo.so
10749        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10750
10751        /** New install */
10752        FileInstallArgs(InstallParams params) {
10753            super(params.origin, params.move, params.observer, params.installFlags,
10754                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10755                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10756            if (isFwdLocked()) {
10757                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10758            }
10759        }
10760
10761        /** Existing install */
10762        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10763            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10764                    null);
10765            this.codeFile = (codePath != null) ? new File(codePath) : null;
10766            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10767        }
10768
10769        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10770            if (origin.staged) {
10771                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10772                codeFile = origin.file;
10773                resourceFile = origin.file;
10774                return PackageManager.INSTALL_SUCCEEDED;
10775            }
10776
10777            try {
10778                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10779                codeFile = tempDir;
10780                resourceFile = tempDir;
10781            } catch (IOException e) {
10782                Slog.w(TAG, "Failed to create copy file: " + e);
10783                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10784            }
10785
10786            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10787                @Override
10788                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10789                    if (!FileUtils.isValidExtFilename(name)) {
10790                        throw new IllegalArgumentException("Invalid filename: " + name);
10791                    }
10792                    try {
10793                        final File file = new File(codeFile, name);
10794                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10795                                O_RDWR | O_CREAT, 0644);
10796                        Os.chmod(file.getAbsolutePath(), 0644);
10797                        return new ParcelFileDescriptor(fd);
10798                    } catch (ErrnoException e) {
10799                        throw new RemoteException("Failed to open: " + e.getMessage());
10800                    }
10801                }
10802            };
10803
10804            int ret = PackageManager.INSTALL_SUCCEEDED;
10805            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10806            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10807                Slog.e(TAG, "Failed to copy package");
10808                return ret;
10809            }
10810
10811            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10812            NativeLibraryHelper.Handle handle = null;
10813            try {
10814                handle = NativeLibraryHelper.Handle.create(codeFile);
10815                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10816                        abiOverride);
10817            } catch (IOException e) {
10818                Slog.e(TAG, "Copying native libraries failed", e);
10819                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10820            } finally {
10821                IoUtils.closeQuietly(handle);
10822            }
10823
10824            return ret;
10825        }
10826
10827        int doPreInstall(int status) {
10828            if (status != PackageManager.INSTALL_SUCCEEDED) {
10829                cleanUp();
10830            }
10831            return status;
10832        }
10833
10834        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10835            if (status != PackageManager.INSTALL_SUCCEEDED) {
10836                cleanUp();
10837                return false;
10838            }
10839
10840            final File targetDir = codeFile.getParentFile();
10841            final File beforeCodeFile = codeFile;
10842            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10843
10844            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10845            try {
10846                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10847            } catch (ErrnoException e) {
10848                Slog.w(TAG, "Failed to rename", e);
10849                return false;
10850            }
10851
10852            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10853                Slog.w(TAG, "Failed to restorecon");
10854                return false;
10855            }
10856
10857            // Reflect the rename internally
10858            codeFile = afterCodeFile;
10859            resourceFile = afterCodeFile;
10860
10861            // Reflect the rename in scanned details
10862            pkg.codePath = afterCodeFile.getAbsolutePath();
10863            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10864                    pkg.baseCodePath);
10865            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10866                    pkg.splitCodePaths);
10867
10868            // Reflect the rename in app info
10869            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10870            pkg.applicationInfo.setCodePath(pkg.codePath);
10871            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10872            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10873            pkg.applicationInfo.setResourcePath(pkg.codePath);
10874            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10875            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10876
10877            return true;
10878        }
10879
10880        int doPostInstall(int status, int uid) {
10881            if (status != PackageManager.INSTALL_SUCCEEDED) {
10882                cleanUp();
10883            }
10884            return status;
10885        }
10886
10887        @Override
10888        String getCodePath() {
10889            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10890        }
10891
10892        @Override
10893        String getResourcePath() {
10894            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10895        }
10896
10897        private boolean cleanUp() {
10898            if (codeFile == null || !codeFile.exists()) {
10899                return false;
10900            }
10901
10902            if (codeFile.isDirectory()) {
10903                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10904            } else {
10905                codeFile.delete();
10906            }
10907
10908            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10909                resourceFile.delete();
10910            }
10911
10912            return true;
10913        }
10914
10915        void cleanUpResourcesLI() {
10916            // Try enumerating all code paths before deleting
10917            List<String> allCodePaths = Collections.EMPTY_LIST;
10918            if (codeFile != null && codeFile.exists()) {
10919                try {
10920                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10921                    allCodePaths = pkg.getAllCodePaths();
10922                } catch (PackageParserException e) {
10923                    // Ignored; we tried our best
10924                }
10925            }
10926
10927            cleanUp();
10928            removeDexFiles(allCodePaths, instructionSets);
10929        }
10930
10931        boolean doPostDeleteLI(boolean delete) {
10932            // XXX err, shouldn't we respect the delete flag?
10933            cleanUpResourcesLI();
10934            return true;
10935        }
10936    }
10937
10938    private boolean isAsecExternal(String cid) {
10939        final String asecPath = PackageHelper.getSdFilesystem(cid);
10940        return !asecPath.startsWith(mAsecInternalPath);
10941    }
10942
10943    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10944            PackageManagerException {
10945        if (copyRet < 0) {
10946            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10947                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10948                throw new PackageManagerException(copyRet, message);
10949            }
10950        }
10951    }
10952
10953    /**
10954     * Extract the MountService "container ID" from the full code path of an
10955     * .apk.
10956     */
10957    static String cidFromCodePath(String fullCodePath) {
10958        int eidx = fullCodePath.lastIndexOf("/");
10959        String subStr1 = fullCodePath.substring(0, eidx);
10960        int sidx = subStr1.lastIndexOf("/");
10961        return subStr1.substring(sidx+1, eidx);
10962    }
10963
10964    /**
10965     * Logic to handle installation of ASEC applications, including copying and
10966     * renaming logic.
10967     */
10968    class AsecInstallArgs extends InstallArgs {
10969        static final String RES_FILE_NAME = "pkg.apk";
10970        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10971
10972        String cid;
10973        String packagePath;
10974        String resourcePath;
10975
10976        /** New install */
10977        AsecInstallArgs(InstallParams params) {
10978            super(params.origin, params.move, params.observer, params.installFlags,
10979                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10980                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10981        }
10982
10983        /** Existing install */
10984        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10985                        boolean isExternal, boolean isForwardLocked) {
10986            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10987                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10988                    instructionSets, null);
10989            // Hackily pretend we're still looking at a full code path
10990            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10991                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10992            }
10993
10994            // Extract cid from fullCodePath
10995            int eidx = fullCodePath.lastIndexOf("/");
10996            String subStr1 = fullCodePath.substring(0, eidx);
10997            int sidx = subStr1.lastIndexOf("/");
10998            cid = subStr1.substring(sidx+1, eidx);
10999            setMountPath(subStr1);
11000        }
11001
11002        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11003            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11004                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11005                    instructionSets, null);
11006            this.cid = cid;
11007            setMountPath(PackageHelper.getSdDir(cid));
11008        }
11009
11010        void createCopyFile() {
11011            cid = mInstallerService.allocateExternalStageCidLegacy();
11012        }
11013
11014        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11015            if (origin.staged) {
11016                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11017                cid = origin.cid;
11018                setMountPath(PackageHelper.getSdDir(cid));
11019                return PackageManager.INSTALL_SUCCEEDED;
11020            }
11021
11022            if (temp) {
11023                createCopyFile();
11024            } else {
11025                /*
11026                 * Pre-emptively destroy the container since it's destroyed if
11027                 * copying fails due to it existing anyway.
11028                 */
11029                PackageHelper.destroySdDir(cid);
11030            }
11031
11032            final String newMountPath = imcs.copyPackageToContainer(
11033                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11034                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11035
11036            if (newMountPath != null) {
11037                setMountPath(newMountPath);
11038                return PackageManager.INSTALL_SUCCEEDED;
11039            } else {
11040                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11041            }
11042        }
11043
11044        @Override
11045        String getCodePath() {
11046            return packagePath;
11047        }
11048
11049        @Override
11050        String getResourcePath() {
11051            return resourcePath;
11052        }
11053
11054        int doPreInstall(int status) {
11055            if (status != PackageManager.INSTALL_SUCCEEDED) {
11056                // Destroy container
11057                PackageHelper.destroySdDir(cid);
11058            } else {
11059                boolean mounted = PackageHelper.isContainerMounted(cid);
11060                if (!mounted) {
11061                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11062                            Process.SYSTEM_UID);
11063                    if (newMountPath != null) {
11064                        setMountPath(newMountPath);
11065                    } else {
11066                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11067                    }
11068                }
11069            }
11070            return status;
11071        }
11072
11073        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11074            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11075            String newMountPath = null;
11076            if (PackageHelper.isContainerMounted(cid)) {
11077                // Unmount the container
11078                if (!PackageHelper.unMountSdDir(cid)) {
11079                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11080                    return false;
11081                }
11082            }
11083            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11084                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11085                        " which might be stale. Will try to clean up.");
11086                // Clean up the stale container and proceed to recreate.
11087                if (!PackageHelper.destroySdDir(newCacheId)) {
11088                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11089                    return false;
11090                }
11091                // Successfully cleaned up stale container. Try to rename again.
11092                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11093                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11094                            + " inspite of cleaning it up.");
11095                    return false;
11096                }
11097            }
11098            if (!PackageHelper.isContainerMounted(newCacheId)) {
11099                Slog.w(TAG, "Mounting container " + newCacheId);
11100                newMountPath = PackageHelper.mountSdDir(newCacheId,
11101                        getEncryptKey(), Process.SYSTEM_UID);
11102            } else {
11103                newMountPath = PackageHelper.getSdDir(newCacheId);
11104            }
11105            if (newMountPath == null) {
11106                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11107                return false;
11108            }
11109            Log.i(TAG, "Succesfully renamed " + cid +
11110                    " to " + newCacheId +
11111                    " at new path: " + newMountPath);
11112            cid = newCacheId;
11113
11114            final File beforeCodeFile = new File(packagePath);
11115            setMountPath(newMountPath);
11116            final File afterCodeFile = new File(packagePath);
11117
11118            // Reflect the rename in scanned details
11119            pkg.codePath = afterCodeFile.getAbsolutePath();
11120            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11121                    pkg.baseCodePath);
11122            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11123                    pkg.splitCodePaths);
11124
11125            // Reflect the rename in app info
11126            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11127            pkg.applicationInfo.setCodePath(pkg.codePath);
11128            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11129            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11130            pkg.applicationInfo.setResourcePath(pkg.codePath);
11131            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11132            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11133
11134            return true;
11135        }
11136
11137        private void setMountPath(String mountPath) {
11138            final File mountFile = new File(mountPath);
11139
11140            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11141            if (monolithicFile.exists()) {
11142                packagePath = monolithicFile.getAbsolutePath();
11143                if (isFwdLocked()) {
11144                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11145                } else {
11146                    resourcePath = packagePath;
11147                }
11148            } else {
11149                packagePath = mountFile.getAbsolutePath();
11150                resourcePath = packagePath;
11151            }
11152        }
11153
11154        int doPostInstall(int status, int uid) {
11155            if (status != PackageManager.INSTALL_SUCCEEDED) {
11156                cleanUp();
11157            } else {
11158                final int groupOwner;
11159                final String protectedFile;
11160                if (isFwdLocked()) {
11161                    groupOwner = UserHandle.getSharedAppGid(uid);
11162                    protectedFile = RES_FILE_NAME;
11163                } else {
11164                    groupOwner = -1;
11165                    protectedFile = null;
11166                }
11167
11168                if (uid < Process.FIRST_APPLICATION_UID
11169                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11170                    Slog.e(TAG, "Failed to finalize " + cid);
11171                    PackageHelper.destroySdDir(cid);
11172                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11173                }
11174
11175                boolean mounted = PackageHelper.isContainerMounted(cid);
11176                if (!mounted) {
11177                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11178                }
11179            }
11180            return status;
11181        }
11182
11183        private void cleanUp() {
11184            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11185
11186            // Destroy secure container
11187            PackageHelper.destroySdDir(cid);
11188        }
11189
11190        private List<String> getAllCodePaths() {
11191            final File codeFile = new File(getCodePath());
11192            if (codeFile != null && codeFile.exists()) {
11193                try {
11194                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11195                    return pkg.getAllCodePaths();
11196                } catch (PackageParserException e) {
11197                    // Ignored; we tried our best
11198                }
11199            }
11200            return Collections.EMPTY_LIST;
11201        }
11202
11203        void cleanUpResourcesLI() {
11204            // Enumerate all code paths before deleting
11205            cleanUpResourcesLI(getAllCodePaths());
11206        }
11207
11208        private void cleanUpResourcesLI(List<String> allCodePaths) {
11209            cleanUp();
11210            removeDexFiles(allCodePaths, instructionSets);
11211        }
11212
11213        String getPackageName() {
11214            return getAsecPackageName(cid);
11215        }
11216
11217        boolean doPostDeleteLI(boolean delete) {
11218            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11219            final List<String> allCodePaths = getAllCodePaths();
11220            boolean mounted = PackageHelper.isContainerMounted(cid);
11221            if (mounted) {
11222                // Unmount first
11223                if (PackageHelper.unMountSdDir(cid)) {
11224                    mounted = false;
11225                }
11226            }
11227            if (!mounted && delete) {
11228                cleanUpResourcesLI(allCodePaths);
11229            }
11230            return !mounted;
11231        }
11232
11233        @Override
11234        int doPreCopy() {
11235            if (isFwdLocked()) {
11236                if (!PackageHelper.fixSdPermissions(cid,
11237                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11238                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11239                }
11240            }
11241
11242            return PackageManager.INSTALL_SUCCEEDED;
11243        }
11244
11245        @Override
11246        int doPostCopy(int uid) {
11247            if (isFwdLocked()) {
11248                if (uid < Process.FIRST_APPLICATION_UID
11249                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11250                                RES_FILE_NAME)) {
11251                    Slog.e(TAG, "Failed to finalize " + cid);
11252                    PackageHelper.destroySdDir(cid);
11253                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11254                }
11255            }
11256
11257            return PackageManager.INSTALL_SUCCEEDED;
11258        }
11259    }
11260
11261    /**
11262     * Logic to handle movement of existing installed applications.
11263     */
11264    class MoveInstallArgs extends InstallArgs {
11265        private File codeFile;
11266        private File resourceFile;
11267
11268        /** New install */
11269        MoveInstallArgs(InstallParams params) {
11270            super(params.origin, params.move, params.observer, params.installFlags,
11271                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11272                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11273        }
11274
11275        int copyApk(IMediaContainerService imcs, boolean temp) {
11276            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11277                    + move.fromUuid + " to " + move.toUuid);
11278            synchronized (mInstaller) {
11279                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11280                        move.dataAppName, move.appId, move.seinfo) != 0) {
11281                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11282                }
11283            }
11284
11285            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11286            resourceFile = codeFile;
11287            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11288
11289            return PackageManager.INSTALL_SUCCEEDED;
11290        }
11291
11292        int doPreInstall(int status) {
11293            if (status != PackageManager.INSTALL_SUCCEEDED) {
11294                cleanUp();
11295            }
11296            return status;
11297        }
11298
11299        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11300            if (status != PackageManager.INSTALL_SUCCEEDED) {
11301                cleanUp();
11302                return false;
11303            }
11304
11305            // Reflect the move in app info
11306            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11307            pkg.applicationInfo.setCodePath(pkg.codePath);
11308            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11309            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11310            pkg.applicationInfo.setResourcePath(pkg.codePath);
11311            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11312            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11313
11314            return true;
11315        }
11316
11317        int doPostInstall(int status, int uid) {
11318            if (status != PackageManager.INSTALL_SUCCEEDED) {
11319                cleanUp();
11320            }
11321            return status;
11322        }
11323
11324        @Override
11325        String getCodePath() {
11326            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11327        }
11328
11329        @Override
11330        String getResourcePath() {
11331            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11332        }
11333
11334        private boolean cleanUp() {
11335            if (codeFile == null || !codeFile.exists()) {
11336                return false;
11337            }
11338
11339            if (codeFile.isDirectory()) {
11340                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11341            } else {
11342                codeFile.delete();
11343            }
11344
11345            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11346                resourceFile.delete();
11347            }
11348
11349            return true;
11350        }
11351
11352        void cleanUpResourcesLI() {
11353            cleanUp();
11354        }
11355
11356        boolean doPostDeleteLI(boolean delete) {
11357            // XXX err, shouldn't we respect the delete flag?
11358            cleanUpResourcesLI();
11359            return true;
11360        }
11361    }
11362
11363    static String getAsecPackageName(String packageCid) {
11364        int idx = packageCid.lastIndexOf("-");
11365        if (idx == -1) {
11366            return packageCid;
11367        }
11368        return packageCid.substring(0, idx);
11369    }
11370
11371    // Utility method used to create code paths based on package name and available index.
11372    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11373        String idxStr = "";
11374        int idx = 1;
11375        // Fall back to default value of idx=1 if prefix is not
11376        // part of oldCodePath
11377        if (oldCodePath != null) {
11378            String subStr = oldCodePath;
11379            // Drop the suffix right away
11380            if (suffix != null && subStr.endsWith(suffix)) {
11381                subStr = subStr.substring(0, subStr.length() - suffix.length());
11382            }
11383            // If oldCodePath already contains prefix find out the
11384            // ending index to either increment or decrement.
11385            int sidx = subStr.lastIndexOf(prefix);
11386            if (sidx != -1) {
11387                subStr = subStr.substring(sidx + prefix.length());
11388                if (subStr != null) {
11389                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11390                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11391                    }
11392                    try {
11393                        idx = Integer.parseInt(subStr);
11394                        if (idx <= 1) {
11395                            idx++;
11396                        } else {
11397                            idx--;
11398                        }
11399                    } catch(NumberFormatException e) {
11400                    }
11401                }
11402            }
11403        }
11404        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11405        return prefix + idxStr;
11406    }
11407
11408    private File getNextCodePath(File targetDir, String packageName) {
11409        int suffix = 1;
11410        File result;
11411        do {
11412            result = new File(targetDir, packageName + "-" + suffix);
11413            suffix++;
11414        } while (result.exists());
11415        return result;
11416    }
11417
11418    // Utility method that returns the relative package path with respect
11419    // to the installation directory. Like say for /data/data/com.test-1.apk
11420    // string com.test-1 is returned.
11421    static String deriveCodePathName(String codePath) {
11422        if (codePath == null) {
11423            return null;
11424        }
11425        final File codeFile = new File(codePath);
11426        final String name = codeFile.getName();
11427        if (codeFile.isDirectory()) {
11428            return name;
11429        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11430            final int lastDot = name.lastIndexOf('.');
11431            return name.substring(0, lastDot);
11432        } else {
11433            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11434            return null;
11435        }
11436    }
11437
11438    class PackageInstalledInfo {
11439        String name;
11440        int uid;
11441        // The set of users that originally had this package installed.
11442        int[] origUsers;
11443        // The set of users that now have this package installed.
11444        int[] newUsers;
11445        PackageParser.Package pkg;
11446        int returnCode;
11447        String returnMsg;
11448        PackageRemovedInfo removedInfo;
11449
11450        public void setError(int code, String msg) {
11451            returnCode = code;
11452            returnMsg = msg;
11453            Slog.w(TAG, msg);
11454        }
11455
11456        public void setError(String msg, PackageParserException e) {
11457            returnCode = e.error;
11458            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11459            Slog.w(TAG, msg, e);
11460        }
11461
11462        public void setError(String msg, PackageManagerException e) {
11463            returnCode = e.error;
11464            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11465            Slog.w(TAG, msg, e);
11466        }
11467
11468        // In some error cases we want to convey more info back to the observer
11469        String origPackage;
11470        String origPermission;
11471    }
11472
11473    /*
11474     * Install a non-existing package.
11475     */
11476    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11477            UserHandle user, String installerPackageName, String volumeUuid,
11478            PackageInstalledInfo res) {
11479        // Remember this for later, in case we need to rollback this install
11480        String pkgName = pkg.packageName;
11481
11482        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11483        final boolean dataDirExists = Environment
11484                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11485        synchronized(mPackages) {
11486            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11487                // A package with the same name is already installed, though
11488                // it has been renamed to an older name.  The package we
11489                // are trying to install should be installed as an update to
11490                // the existing one, but that has not been requested, so bail.
11491                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11492                        + " without first uninstalling package running as "
11493                        + mSettings.mRenamedPackages.get(pkgName));
11494                return;
11495            }
11496            if (mPackages.containsKey(pkgName)) {
11497                // Don't allow installation over an existing package with the same name.
11498                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11499                        + " without first uninstalling.");
11500                return;
11501            }
11502        }
11503
11504        try {
11505            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11506                    System.currentTimeMillis(), user);
11507
11508            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11509            // delete the partially installed application. the data directory will have to be
11510            // restored if it was already existing
11511            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11512                // remove package from internal structures.  Note that we want deletePackageX to
11513                // delete the package data and cache directories that it created in
11514                // scanPackageLocked, unless those directories existed before we even tried to
11515                // install.
11516                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11517                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11518                                res.removedInfo, true);
11519            }
11520
11521        } catch (PackageManagerException e) {
11522            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11523        }
11524    }
11525
11526    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11527        // Can't rotate keys during boot or if sharedUser.
11528        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11529                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11530            return false;
11531        }
11532        // app is using upgradeKeySets; make sure all are valid
11533        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11534        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11535        for (int i = 0; i < upgradeKeySets.length; i++) {
11536            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11537                Slog.wtf(TAG, "Package "
11538                         + (oldPs.name != null ? oldPs.name : "<null>")
11539                         + " contains upgrade-key-set reference to unknown key-set: "
11540                         + upgradeKeySets[i]
11541                         + " reverting to signatures check.");
11542                return false;
11543            }
11544        }
11545        return true;
11546    }
11547
11548    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11549        // Upgrade keysets are being used.  Determine if new package has a superset of the
11550        // required keys.
11551        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11552        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11553        for (int i = 0; i < upgradeKeySets.length; i++) {
11554            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11555            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11556                return true;
11557            }
11558        }
11559        return false;
11560    }
11561
11562    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11563            UserHandle user, String installerPackageName, String volumeUuid,
11564            PackageInstalledInfo res) {
11565        final PackageParser.Package oldPackage;
11566        final String pkgName = pkg.packageName;
11567        final int[] allUsers;
11568        final boolean[] perUserInstalled;
11569        final boolean weFroze;
11570
11571        // First find the old package info and check signatures
11572        synchronized(mPackages) {
11573            oldPackage = mPackages.get(pkgName);
11574            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11575            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11576            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11577                if(!checkUpgradeKeySetLP(ps, pkg)) {
11578                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11579                            "New package not signed by keys specified by upgrade-keysets: "
11580                            + pkgName);
11581                    return;
11582                }
11583            } else {
11584                // default to original signature matching
11585                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11586                    != PackageManager.SIGNATURE_MATCH) {
11587                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11588                            "New package has a different signature: " + pkgName);
11589                    return;
11590                }
11591            }
11592
11593            // In case of rollback, remember per-user/profile install state
11594            allUsers = sUserManager.getUserIds();
11595            perUserInstalled = new boolean[allUsers.length];
11596            for (int i = 0; i < allUsers.length; i++) {
11597                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11598            }
11599
11600            // Mark the app as frozen to prevent launching during the upgrade
11601            // process, and then kill all running instances
11602            if (!ps.frozen) {
11603                ps.frozen = true;
11604                weFroze = true;
11605            } else {
11606                weFroze = false;
11607            }
11608        }
11609
11610        // Now that we're guarded by frozen state, kill app during upgrade
11611        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11612
11613        try {
11614            boolean sysPkg = (isSystemApp(oldPackage));
11615            if (sysPkg) {
11616                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11617                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11618            } else {
11619                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11620                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11621            }
11622        } finally {
11623            // Regardless of success or failure of upgrade steps above, always
11624            // unfreeze the package if we froze it
11625            if (weFroze) {
11626                unfreezePackage(pkgName);
11627            }
11628        }
11629    }
11630
11631    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11632            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11633            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11634            String volumeUuid, PackageInstalledInfo res) {
11635        String pkgName = deletedPackage.packageName;
11636        boolean deletedPkg = true;
11637        boolean updatedSettings = false;
11638
11639        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11640                + deletedPackage);
11641        long origUpdateTime;
11642        if (pkg.mExtras != null) {
11643            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11644        } else {
11645            origUpdateTime = 0;
11646        }
11647
11648        // First delete the existing package while retaining the data directory
11649        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11650                res.removedInfo, true)) {
11651            // If the existing package wasn't successfully deleted
11652            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11653            deletedPkg = false;
11654        } else {
11655            // Successfully deleted the old package; proceed with replace.
11656
11657            // If deleted package lived in a container, give users a chance to
11658            // relinquish resources before killing.
11659            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11660                if (DEBUG_INSTALL) {
11661                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11662                }
11663                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11664                final ArrayList<String> pkgList = new ArrayList<String>(1);
11665                pkgList.add(deletedPackage.applicationInfo.packageName);
11666                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11667            }
11668
11669            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11670            try {
11671                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11672                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11673                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11674                        perUserInstalled, res, user);
11675                updatedSettings = true;
11676            } catch (PackageManagerException e) {
11677                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11678            }
11679        }
11680
11681        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11682            // remove package from internal structures.  Note that we want deletePackageX to
11683            // delete the package data and cache directories that it created in
11684            // scanPackageLocked, unless those directories existed before we even tried to
11685            // install.
11686            if(updatedSettings) {
11687                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11688                deletePackageLI(
11689                        pkgName, null, true, allUsers, perUserInstalled,
11690                        PackageManager.DELETE_KEEP_DATA,
11691                                res.removedInfo, true);
11692            }
11693            // Since we failed to install the new package we need to restore the old
11694            // package that we deleted.
11695            if (deletedPkg) {
11696                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11697                File restoreFile = new File(deletedPackage.codePath);
11698                // Parse old package
11699                boolean oldExternal = isExternal(deletedPackage);
11700                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11701                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11702                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11703                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11704                try {
11705                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11706                } catch (PackageManagerException e) {
11707                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11708                            + e.getMessage());
11709                    return;
11710                }
11711                // Restore of old package succeeded. Update permissions.
11712                // writer
11713                synchronized (mPackages) {
11714                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11715                            UPDATE_PERMISSIONS_ALL);
11716                    // can downgrade to reader
11717                    mSettings.writeLPr();
11718                }
11719                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11720            }
11721        }
11722    }
11723
11724    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11725            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11726            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11727            String volumeUuid, PackageInstalledInfo res) {
11728        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11729                + ", old=" + deletedPackage);
11730        boolean disabledSystem = false;
11731        boolean updatedSettings = false;
11732        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11733        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11734                != 0) {
11735            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11736        }
11737        String packageName = deletedPackage.packageName;
11738        if (packageName == null) {
11739            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11740                    "Attempt to delete null packageName.");
11741            return;
11742        }
11743        PackageParser.Package oldPkg;
11744        PackageSetting oldPkgSetting;
11745        // reader
11746        synchronized (mPackages) {
11747            oldPkg = mPackages.get(packageName);
11748            oldPkgSetting = mSettings.mPackages.get(packageName);
11749            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11750                    (oldPkgSetting == null)) {
11751                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11752                        "Couldn't find package:" + packageName + " information");
11753                return;
11754            }
11755        }
11756
11757        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11758        res.removedInfo.removedPackage = packageName;
11759        // Remove existing system package
11760        removePackageLI(oldPkgSetting, true);
11761        // writer
11762        synchronized (mPackages) {
11763            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11764            if (!disabledSystem && deletedPackage != null) {
11765                // We didn't need to disable the .apk as a current system package,
11766                // which means we are replacing another update that is already
11767                // installed.  We need to make sure to delete the older one's .apk.
11768                res.removedInfo.args = createInstallArgsForExisting(0,
11769                        deletedPackage.applicationInfo.getCodePath(),
11770                        deletedPackage.applicationInfo.getResourcePath(),
11771                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11772            } else {
11773                res.removedInfo.args = null;
11774            }
11775        }
11776
11777        // Successfully disabled the old package. Now proceed with re-installation
11778        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11779
11780        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11781        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11782
11783        PackageParser.Package newPackage = null;
11784        try {
11785            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11786            if (newPackage.mExtras != null) {
11787                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11788                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11789                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11790
11791                // is the update attempting to change shared user? that isn't going to work...
11792                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11793                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11794                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11795                            + " to " + newPkgSetting.sharedUser);
11796                    updatedSettings = true;
11797                }
11798            }
11799
11800            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11801                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11802                        perUserInstalled, res, user);
11803                updatedSettings = true;
11804            }
11805
11806        } catch (PackageManagerException e) {
11807            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11808        }
11809
11810        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11811            // Re installation failed. Restore old information
11812            // Remove new pkg information
11813            if (newPackage != null) {
11814                removeInstalledPackageLI(newPackage, true);
11815            }
11816            // Add back the old system package
11817            try {
11818                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11819            } catch (PackageManagerException e) {
11820                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11821            }
11822            // Restore the old system information in Settings
11823            synchronized (mPackages) {
11824                if (disabledSystem) {
11825                    mSettings.enableSystemPackageLPw(packageName);
11826                }
11827                if (updatedSettings) {
11828                    mSettings.setInstallerPackageName(packageName,
11829                            oldPkgSetting.installerPackageName);
11830                }
11831                mSettings.writeLPr();
11832            }
11833        }
11834    }
11835
11836    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11837            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11838            UserHandle user) {
11839        String pkgName = newPackage.packageName;
11840        synchronized (mPackages) {
11841            //write settings. the installStatus will be incomplete at this stage.
11842            //note that the new package setting would have already been
11843            //added to mPackages. It hasn't been persisted yet.
11844            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11845            mSettings.writeLPr();
11846        }
11847
11848        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11849
11850        synchronized (mPackages) {
11851            updatePermissionsLPw(newPackage.packageName, newPackage,
11852                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11853                            ? UPDATE_PERMISSIONS_ALL : 0));
11854            // For system-bundled packages, we assume that installing an upgraded version
11855            // of the package implies that the user actually wants to run that new code,
11856            // so we enable the package.
11857            PackageSetting ps = mSettings.mPackages.get(pkgName);
11858            if (ps != null) {
11859                if (isSystemApp(newPackage)) {
11860                    // NB: implicit assumption that system package upgrades apply to all users
11861                    if (DEBUG_INSTALL) {
11862                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11863                    }
11864                    if (res.origUsers != null) {
11865                        for (int userHandle : res.origUsers) {
11866                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11867                                    userHandle, installerPackageName);
11868                        }
11869                    }
11870                    // Also convey the prior install/uninstall state
11871                    if (allUsers != null && perUserInstalled != null) {
11872                        for (int i = 0; i < allUsers.length; i++) {
11873                            if (DEBUG_INSTALL) {
11874                                Slog.d(TAG, "    user " + allUsers[i]
11875                                        + " => " + perUserInstalled[i]);
11876                            }
11877                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11878                        }
11879                        // these install state changes will be persisted in the
11880                        // upcoming call to mSettings.writeLPr().
11881                    }
11882                }
11883                // It's implied that when a user requests installation, they want the app to be
11884                // installed and enabled.
11885                int userId = user.getIdentifier();
11886                if (userId != UserHandle.USER_ALL) {
11887                    ps.setInstalled(true, userId);
11888                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11889                }
11890            }
11891            res.name = pkgName;
11892            res.uid = newPackage.applicationInfo.uid;
11893            res.pkg = newPackage;
11894            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11895            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11896            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11897            //to update install status
11898            mSettings.writeLPr();
11899        }
11900    }
11901
11902    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11903        final int installFlags = args.installFlags;
11904        final String installerPackageName = args.installerPackageName;
11905        final String volumeUuid = args.volumeUuid;
11906        final File tmpPackageFile = new File(args.getCodePath());
11907        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11908        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11909                || (args.volumeUuid != null));
11910        boolean replace = false;
11911        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11912        if (args.move != null) {
11913            // moving a complete application; perfom an initial scan on the new install location
11914            scanFlags |= SCAN_INITIAL;
11915        }
11916        // Result object to be returned
11917        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11918
11919        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11920        // Retrieve PackageSettings and parse package
11921        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11922                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11923                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11924        PackageParser pp = new PackageParser();
11925        pp.setSeparateProcesses(mSeparateProcesses);
11926        pp.setDisplayMetrics(mMetrics);
11927
11928        final PackageParser.Package pkg;
11929        try {
11930            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11931        } catch (PackageParserException e) {
11932            res.setError("Failed parse during installPackageLI", e);
11933            return;
11934        }
11935
11936        // Mark that we have an install time CPU ABI override.
11937        pkg.cpuAbiOverride = args.abiOverride;
11938
11939        String pkgName = res.name = pkg.packageName;
11940        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11941            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11942                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11943                return;
11944            }
11945        }
11946
11947        try {
11948            pp.collectCertificates(pkg, parseFlags);
11949            pp.collectManifestDigest(pkg);
11950        } catch (PackageParserException e) {
11951            res.setError("Failed collect during installPackageLI", e);
11952            return;
11953        }
11954
11955        /* If the installer passed in a manifest digest, compare it now. */
11956        if (args.manifestDigest != null) {
11957            if (DEBUG_INSTALL) {
11958                final String parsedManifest = pkg.manifestDigest == null ? "null"
11959                        : pkg.manifestDigest.toString();
11960                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11961                        + parsedManifest);
11962            }
11963
11964            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11965                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11966                return;
11967            }
11968        } else if (DEBUG_INSTALL) {
11969            final String parsedManifest = pkg.manifestDigest == null
11970                    ? "null" : pkg.manifestDigest.toString();
11971            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11972        }
11973
11974        // Get rid of all references to package scan path via parser.
11975        pp = null;
11976        String oldCodePath = null;
11977        boolean systemApp = false;
11978        synchronized (mPackages) {
11979            // Check if installing already existing package
11980            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11981                String oldName = mSettings.mRenamedPackages.get(pkgName);
11982                if (pkg.mOriginalPackages != null
11983                        && pkg.mOriginalPackages.contains(oldName)
11984                        && mPackages.containsKey(oldName)) {
11985                    // This package is derived from an original package,
11986                    // and this device has been updating from that original
11987                    // name.  We must continue using the original name, so
11988                    // rename the new package here.
11989                    pkg.setPackageName(oldName);
11990                    pkgName = pkg.packageName;
11991                    replace = true;
11992                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11993                            + oldName + " pkgName=" + pkgName);
11994                } else if (mPackages.containsKey(pkgName)) {
11995                    // This package, under its official name, already exists
11996                    // on the device; we should replace it.
11997                    replace = true;
11998                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11999                }
12000
12001                // Prevent apps opting out from runtime permissions
12002                if (replace) {
12003                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12004                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12005                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12006                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12007                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12008                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12009                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12010                                        + " doesn't support runtime permissions but the old"
12011                                        + " target SDK " + oldTargetSdk + " does.");
12012                        return;
12013                    }
12014                }
12015            }
12016
12017            PackageSetting ps = mSettings.mPackages.get(pkgName);
12018            if (ps != null) {
12019                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12020
12021                // Quick sanity check that we're signed correctly if updating;
12022                // we'll check this again later when scanning, but we want to
12023                // bail early here before tripping over redefined permissions.
12024                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12025                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12026                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12027                                + pkg.packageName + " upgrade keys do not match the "
12028                                + "previously installed version");
12029                        return;
12030                    }
12031                } else {
12032                    try {
12033                        verifySignaturesLP(ps, pkg);
12034                    } catch (PackageManagerException e) {
12035                        res.setError(e.error, e.getMessage());
12036                        return;
12037                    }
12038                }
12039
12040                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12041                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12042                    systemApp = (ps.pkg.applicationInfo.flags &
12043                            ApplicationInfo.FLAG_SYSTEM) != 0;
12044                }
12045                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12046            }
12047
12048            // Check whether the newly-scanned package wants to define an already-defined perm
12049            int N = pkg.permissions.size();
12050            for (int i = N-1; i >= 0; i--) {
12051                PackageParser.Permission perm = pkg.permissions.get(i);
12052                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12053                if (bp != null) {
12054                    // If the defining package is signed with our cert, it's okay.  This
12055                    // also includes the "updating the same package" case, of course.
12056                    // "updating same package" could also involve key-rotation.
12057                    final boolean sigsOk;
12058                    if (bp.sourcePackage.equals(pkg.packageName)
12059                            && (bp.packageSetting instanceof PackageSetting)
12060                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12061                                    scanFlags))) {
12062                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12063                    } else {
12064                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12065                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12066                    }
12067                    if (!sigsOk) {
12068                        // If the owning package is the system itself, we log but allow
12069                        // install to proceed; we fail the install on all other permission
12070                        // redefinitions.
12071                        if (!bp.sourcePackage.equals("android")) {
12072                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12073                                    + pkg.packageName + " attempting to redeclare permission "
12074                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12075                            res.origPermission = perm.info.name;
12076                            res.origPackage = bp.sourcePackage;
12077                            return;
12078                        } else {
12079                            Slog.w(TAG, "Package " + pkg.packageName
12080                                    + " attempting to redeclare system permission "
12081                                    + perm.info.name + "; ignoring new declaration");
12082                            pkg.permissions.remove(i);
12083                        }
12084                    }
12085                }
12086            }
12087
12088        }
12089
12090        if (systemApp && onExternal) {
12091            // Disable updates to system apps on sdcard
12092            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12093                    "Cannot install updates to system apps on sdcard");
12094            return;
12095        }
12096
12097        if (args.move != null) {
12098            // We did an in-place move, so dex is ready to roll
12099            scanFlags |= SCAN_NO_DEX;
12100            scanFlags |= SCAN_MOVE;
12101        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12102            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12103            scanFlags |= SCAN_NO_DEX;
12104
12105            try {
12106                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12107                        true /* extract libs */);
12108            } catch (PackageManagerException pme) {
12109                Slog.e(TAG, "Error deriving application ABI", pme);
12110                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12111                return;
12112            }
12113
12114            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12115            int result = mPackageDexOptimizer
12116                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12117                            false /* defer */, false /* inclDependencies */);
12118            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12119                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12120                return;
12121            }
12122        }
12123
12124        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12125            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12126            return;
12127        }
12128
12129        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12130
12131        if (replace) {
12132            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12133                    installerPackageName, volumeUuid, res);
12134        } else {
12135            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12136                    args.user, installerPackageName, volumeUuid, res);
12137        }
12138        synchronized (mPackages) {
12139            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12140            if (ps != null) {
12141                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12142            }
12143        }
12144    }
12145
12146    private void startIntentFilterVerifications(int userId, boolean replacing,
12147            PackageParser.Package pkg) {
12148        if (mIntentFilterVerifierComponent == null) {
12149            Slog.w(TAG, "No IntentFilter verification will not be done as "
12150                    + "there is no IntentFilterVerifier available!");
12151            return;
12152        }
12153
12154        final int verifierUid = getPackageUid(
12155                mIntentFilterVerifierComponent.getPackageName(),
12156                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12157
12158        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12159        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12160        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12161        mHandler.sendMessage(msg);
12162    }
12163
12164    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12165            PackageParser.Package pkg) {
12166        int size = pkg.activities.size();
12167        if (size == 0) {
12168            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12169                    "No activity, so no need to verify any IntentFilter!");
12170            return;
12171        }
12172
12173        final boolean hasDomainURLs = hasDomainURLs(pkg);
12174        if (!hasDomainURLs) {
12175            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12176                    "No domain URLs, so no need to verify any IntentFilter!");
12177            return;
12178        }
12179
12180        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12181                + " if any IntentFilter from the " + size
12182                + " Activities needs verification ...");
12183
12184        int count = 0;
12185        final String packageName = pkg.packageName;
12186
12187        synchronized (mPackages) {
12188            // If this is a new install and we see that we've already run verification for this
12189            // package, we have nothing to do: it means the state was restored from backup.
12190            if (!replacing) {
12191                IntentFilterVerificationInfo ivi =
12192                        mSettings.getIntentFilterVerificationLPr(packageName);
12193                if (ivi != null) {
12194                    if (DEBUG_DOMAIN_VERIFICATION) {
12195                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12196                                + ivi.getStatusString());
12197                    }
12198                    return;
12199                }
12200            }
12201
12202            // If any filters need to be verified, then all need to be.
12203            boolean needToVerify = false;
12204            for (PackageParser.Activity a : pkg.activities) {
12205                for (ActivityIntentInfo filter : a.intents) {
12206                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12207                        if (DEBUG_DOMAIN_VERIFICATION) {
12208                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12209                        }
12210                        needToVerify = true;
12211                        break;
12212                    }
12213                }
12214            }
12215
12216            if (needToVerify) {
12217                final int verificationId = mIntentFilterVerificationToken++;
12218                for (PackageParser.Activity a : pkg.activities) {
12219                    for (ActivityIntentInfo filter : a.intents) {
12220                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12221                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12222                                    "Verification needed for IntentFilter:" + filter.toString());
12223                            mIntentFilterVerifier.addOneIntentFilterVerification(
12224                                    verifierUid, userId, verificationId, filter, packageName);
12225                            count++;
12226                        }
12227                    }
12228                }
12229            }
12230        }
12231
12232        if (count > 0) {
12233            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12234                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12235                    +  " for userId:" + userId);
12236            mIntentFilterVerifier.startVerifications(userId);
12237        } else {
12238            if (DEBUG_DOMAIN_VERIFICATION) {
12239                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12240            }
12241        }
12242    }
12243
12244    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12245        final ComponentName cn  = filter.activity.getComponentName();
12246        final String packageName = cn.getPackageName();
12247
12248        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12249                packageName);
12250        if (ivi == null) {
12251            return true;
12252        }
12253        int status = ivi.getStatus();
12254        switch (status) {
12255            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12256            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12257                return true;
12258
12259            default:
12260                // Nothing to do
12261                return false;
12262        }
12263    }
12264
12265    private static boolean isMultiArch(PackageSetting ps) {
12266        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12267    }
12268
12269    private static boolean isMultiArch(ApplicationInfo info) {
12270        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12271    }
12272
12273    private static boolean isExternal(PackageParser.Package pkg) {
12274        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12275    }
12276
12277    private static boolean isExternal(PackageSetting ps) {
12278        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12279    }
12280
12281    private static boolean isExternal(ApplicationInfo info) {
12282        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12283    }
12284
12285    private static boolean isSystemApp(PackageParser.Package pkg) {
12286        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12287    }
12288
12289    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12290        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12291    }
12292
12293    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12294        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12295    }
12296
12297    private static boolean isSystemApp(PackageSetting ps) {
12298        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12299    }
12300
12301    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12302        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12303    }
12304
12305    private int packageFlagsToInstallFlags(PackageSetting ps) {
12306        int installFlags = 0;
12307        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12308            // This existing package was an external ASEC install when we have
12309            // the external flag without a UUID
12310            installFlags |= PackageManager.INSTALL_EXTERNAL;
12311        }
12312        if (ps.isForwardLocked()) {
12313            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12314        }
12315        return installFlags;
12316    }
12317
12318    private void deleteTempPackageFiles() {
12319        final FilenameFilter filter = new FilenameFilter() {
12320            public boolean accept(File dir, String name) {
12321                return name.startsWith("vmdl") && name.endsWith(".tmp");
12322            }
12323        };
12324        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12325            file.delete();
12326        }
12327    }
12328
12329    @Override
12330    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12331            int flags) {
12332        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12333                flags);
12334    }
12335
12336    @Override
12337    public void deletePackage(final String packageName,
12338            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12339        mContext.enforceCallingOrSelfPermission(
12340                android.Manifest.permission.DELETE_PACKAGES, null);
12341        Preconditions.checkNotNull(packageName);
12342        Preconditions.checkNotNull(observer);
12343        final int uid = Binder.getCallingUid();
12344        if (UserHandle.getUserId(uid) != userId) {
12345            mContext.enforceCallingPermission(
12346                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12347                    "deletePackage for user " + userId);
12348        }
12349        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12350            try {
12351                observer.onPackageDeleted(packageName,
12352                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12353            } catch (RemoteException re) {
12354            }
12355            return;
12356        }
12357
12358        boolean uninstallBlocked = false;
12359        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12360            int[] users = sUserManager.getUserIds();
12361            for (int i = 0; i < users.length; ++i) {
12362                if (getBlockUninstallForUser(packageName, users[i])) {
12363                    uninstallBlocked = true;
12364                    break;
12365                }
12366            }
12367        } else {
12368            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12369        }
12370        if (uninstallBlocked) {
12371            try {
12372                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12373                        null);
12374            } catch (RemoteException re) {
12375            }
12376            return;
12377        }
12378
12379        if (DEBUG_REMOVE) {
12380            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12381        }
12382        // Queue up an async operation since the package deletion may take a little while.
12383        mHandler.post(new Runnable() {
12384            public void run() {
12385                mHandler.removeCallbacks(this);
12386                final int returnCode = deletePackageX(packageName, userId, flags);
12387                if (observer != null) {
12388                    try {
12389                        observer.onPackageDeleted(packageName, returnCode, null);
12390                    } catch (RemoteException e) {
12391                        Log.i(TAG, "Observer no longer exists.");
12392                    } //end catch
12393                } //end if
12394            } //end run
12395        });
12396    }
12397
12398    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12399        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12400                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12401        try {
12402            if (dpm != null) {
12403                if (dpm.isDeviceOwner(packageName)) {
12404                    return true;
12405                }
12406                int[] users;
12407                if (userId == UserHandle.USER_ALL) {
12408                    users = sUserManager.getUserIds();
12409                } else {
12410                    users = new int[]{userId};
12411                }
12412                for (int i = 0; i < users.length; ++i) {
12413                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12414                        return true;
12415                    }
12416                }
12417            }
12418        } catch (RemoteException e) {
12419        }
12420        return false;
12421    }
12422
12423    /**
12424     *  This method is an internal method that could be get invoked either
12425     *  to delete an installed package or to clean up a failed installation.
12426     *  After deleting an installed package, a broadcast is sent to notify any
12427     *  listeners that the package has been installed. For cleaning up a failed
12428     *  installation, the broadcast is not necessary since the package's
12429     *  installation wouldn't have sent the initial broadcast either
12430     *  The key steps in deleting a package are
12431     *  deleting the package information in internal structures like mPackages,
12432     *  deleting the packages base directories through installd
12433     *  updating mSettings to reflect current status
12434     *  persisting settings for later use
12435     *  sending a broadcast if necessary
12436     */
12437    private int deletePackageX(String packageName, int userId, int flags) {
12438        final PackageRemovedInfo info = new PackageRemovedInfo();
12439        final boolean res;
12440
12441        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12442                ? UserHandle.ALL : new UserHandle(userId);
12443
12444        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12445            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12446            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12447        }
12448
12449        boolean removedForAllUsers = false;
12450        boolean systemUpdate = false;
12451
12452        // for the uninstall-updates case and restricted profiles, remember the per-
12453        // userhandle installed state
12454        int[] allUsers;
12455        boolean[] perUserInstalled;
12456        synchronized (mPackages) {
12457            PackageSetting ps = mSettings.mPackages.get(packageName);
12458            allUsers = sUserManager.getUserIds();
12459            perUserInstalled = new boolean[allUsers.length];
12460            for (int i = 0; i < allUsers.length; i++) {
12461                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12462            }
12463        }
12464
12465        synchronized (mInstallLock) {
12466            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12467            res = deletePackageLI(packageName, removeForUser,
12468                    true, allUsers, perUserInstalled,
12469                    flags | REMOVE_CHATTY, info, true);
12470            systemUpdate = info.isRemovedPackageSystemUpdate;
12471            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12472                removedForAllUsers = true;
12473            }
12474            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12475                    + " removedForAllUsers=" + removedForAllUsers);
12476        }
12477
12478        if (res) {
12479            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12480
12481            // If the removed package was a system update, the old system package
12482            // was re-enabled; we need to broadcast this information
12483            if (systemUpdate) {
12484                Bundle extras = new Bundle(1);
12485                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12486                        ? info.removedAppId : info.uid);
12487                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12488
12489                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12490                        extras, null, null, null);
12491                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12492                        extras, null, null, null);
12493                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12494                        null, packageName, null, null);
12495            }
12496        }
12497        // Force a gc here.
12498        Runtime.getRuntime().gc();
12499        // Delete the resources here after sending the broadcast to let
12500        // other processes clean up before deleting resources.
12501        if (info.args != null) {
12502            synchronized (mInstallLock) {
12503                info.args.doPostDeleteLI(true);
12504            }
12505        }
12506
12507        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12508    }
12509
12510    class PackageRemovedInfo {
12511        String removedPackage;
12512        int uid = -1;
12513        int removedAppId = -1;
12514        int[] removedUsers = null;
12515        boolean isRemovedPackageSystemUpdate = false;
12516        // Clean up resources deleted packages.
12517        InstallArgs args = null;
12518
12519        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12520            Bundle extras = new Bundle(1);
12521            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12522            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12523            if (replacing) {
12524                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12525            }
12526            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12527            if (removedPackage != null) {
12528                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12529                        extras, null, null, removedUsers);
12530                if (fullRemove && !replacing) {
12531                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12532                            extras, null, null, removedUsers);
12533                }
12534            }
12535            if (removedAppId >= 0) {
12536                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12537                        removedUsers);
12538            }
12539        }
12540    }
12541
12542    /*
12543     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12544     * flag is not set, the data directory is removed as well.
12545     * make sure this flag is set for partially installed apps. If not its meaningless to
12546     * delete a partially installed application.
12547     */
12548    private void removePackageDataLI(PackageSetting ps,
12549            int[] allUserHandles, boolean[] perUserInstalled,
12550            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12551        String packageName = ps.name;
12552        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12553        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12554        // Retrieve object to delete permissions for shared user later on
12555        final PackageSetting deletedPs;
12556        // reader
12557        synchronized (mPackages) {
12558            deletedPs = mSettings.mPackages.get(packageName);
12559            if (outInfo != null) {
12560                outInfo.removedPackage = packageName;
12561                outInfo.removedUsers = deletedPs != null
12562                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12563                        : null;
12564            }
12565        }
12566        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12567            removeDataDirsLI(ps.volumeUuid, packageName);
12568            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12569        }
12570        // writer
12571        synchronized (mPackages) {
12572            if (deletedPs != null) {
12573                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12574                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12575                    clearDefaultBrowserIfNeeded(packageName);
12576                    if (outInfo != null) {
12577                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12578                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12579                    }
12580                    updatePermissionsLPw(deletedPs.name, null, 0);
12581                    if (deletedPs.sharedUser != null) {
12582                        // Remove permissions associated with package. Since runtime
12583                        // permissions are per user we have to kill the removed package
12584                        // or packages running under the shared user of the removed
12585                        // package if revoking the permissions requested only by the removed
12586                        // package is successful and this causes a change in gids.
12587                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12588                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12589                                    userId);
12590                            if (userIdToKill == UserHandle.USER_ALL
12591                                    || userIdToKill >= UserHandle.USER_OWNER) {
12592                                // If gids changed for this user, kill all affected packages.
12593                                mHandler.post(new Runnable() {
12594                                    @Override
12595                                    public void run() {
12596                                        // This has to happen with no lock held.
12597                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12598                                                KILL_APP_REASON_GIDS_CHANGED);
12599                                    }
12600                                });
12601                            break;
12602                            }
12603                        }
12604                    }
12605                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12606                }
12607                // make sure to preserve per-user disabled state if this removal was just
12608                // a downgrade of a system app to the factory package
12609                if (allUserHandles != null && perUserInstalled != null) {
12610                    if (DEBUG_REMOVE) {
12611                        Slog.d(TAG, "Propagating install state across downgrade");
12612                    }
12613                    for (int i = 0; i < allUserHandles.length; i++) {
12614                        if (DEBUG_REMOVE) {
12615                            Slog.d(TAG, "    user " + allUserHandles[i]
12616                                    + " => " + perUserInstalled[i]);
12617                        }
12618                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12619                    }
12620                }
12621            }
12622            // can downgrade to reader
12623            if (writeSettings) {
12624                // Save settings now
12625                mSettings.writeLPr();
12626            }
12627        }
12628        if (outInfo != null) {
12629            // A user ID was deleted here. Go through all users and remove it
12630            // from KeyStore.
12631            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12632        }
12633    }
12634
12635    static boolean locationIsPrivileged(File path) {
12636        try {
12637            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12638                    .getCanonicalPath();
12639            return path.getCanonicalPath().startsWith(privilegedAppDir);
12640        } catch (IOException e) {
12641            Slog.e(TAG, "Unable to access code path " + path);
12642        }
12643        return false;
12644    }
12645
12646    /*
12647     * Tries to delete system package.
12648     */
12649    private boolean deleteSystemPackageLI(PackageSetting newPs,
12650            int[] allUserHandles, boolean[] perUserInstalled,
12651            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12652        final boolean applyUserRestrictions
12653                = (allUserHandles != null) && (perUserInstalled != null);
12654        PackageSetting disabledPs = null;
12655        // Confirm if the system package has been updated
12656        // An updated system app can be deleted. This will also have to restore
12657        // the system pkg from system partition
12658        // reader
12659        synchronized (mPackages) {
12660            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12661        }
12662        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12663                + " disabledPs=" + disabledPs);
12664        if (disabledPs == null) {
12665            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12666            return false;
12667        } else if (DEBUG_REMOVE) {
12668            Slog.d(TAG, "Deleting system pkg from data partition");
12669        }
12670        if (DEBUG_REMOVE) {
12671            if (applyUserRestrictions) {
12672                Slog.d(TAG, "Remembering install states:");
12673                for (int i = 0; i < allUserHandles.length; i++) {
12674                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12675                }
12676            }
12677        }
12678        // Delete the updated package
12679        outInfo.isRemovedPackageSystemUpdate = true;
12680        if (disabledPs.versionCode < newPs.versionCode) {
12681            // Delete data for downgrades
12682            flags &= ~PackageManager.DELETE_KEEP_DATA;
12683        } else {
12684            // Preserve data by setting flag
12685            flags |= PackageManager.DELETE_KEEP_DATA;
12686        }
12687        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12688                allUserHandles, perUserInstalled, outInfo, writeSettings);
12689        if (!ret) {
12690            return false;
12691        }
12692        // writer
12693        synchronized (mPackages) {
12694            // Reinstate the old system package
12695            mSettings.enableSystemPackageLPw(newPs.name);
12696            // Remove any native libraries from the upgraded package.
12697            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12698        }
12699        // Install the system package
12700        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12701        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12702        if (locationIsPrivileged(disabledPs.codePath)) {
12703            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12704        }
12705
12706        final PackageParser.Package newPkg;
12707        try {
12708            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12709        } catch (PackageManagerException e) {
12710            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12711            return false;
12712        }
12713
12714        // writer
12715        synchronized (mPackages) {
12716            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12717            updatePermissionsLPw(newPkg.packageName, newPkg,
12718                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12719            if (applyUserRestrictions) {
12720                if (DEBUG_REMOVE) {
12721                    Slog.d(TAG, "Propagating install state across reinstall");
12722                }
12723                for (int i = 0; i < allUserHandles.length; i++) {
12724                    if (DEBUG_REMOVE) {
12725                        Slog.d(TAG, "    user " + allUserHandles[i]
12726                                + " => " + perUserInstalled[i]);
12727                    }
12728                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12729                }
12730                // Regardless of writeSettings we need to ensure that this restriction
12731                // state propagation is persisted
12732                mSettings.writeAllUsersPackageRestrictionsLPr();
12733            }
12734            // can downgrade to reader here
12735            if (writeSettings) {
12736                mSettings.writeLPr();
12737            }
12738        }
12739        return true;
12740    }
12741
12742    private boolean deleteInstalledPackageLI(PackageSetting ps,
12743            boolean deleteCodeAndResources, int flags,
12744            int[] allUserHandles, boolean[] perUserInstalled,
12745            PackageRemovedInfo outInfo, boolean writeSettings) {
12746        if (outInfo != null) {
12747            outInfo.uid = ps.appId;
12748        }
12749
12750        // Delete package data from internal structures and also remove data if flag is set
12751        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12752
12753        // Delete application code and resources
12754        if (deleteCodeAndResources && (outInfo != null)) {
12755            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12756                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12757            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12758        }
12759        return true;
12760    }
12761
12762    @Override
12763    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12764            int userId) {
12765        mContext.enforceCallingOrSelfPermission(
12766                android.Manifest.permission.DELETE_PACKAGES, null);
12767        synchronized (mPackages) {
12768            PackageSetting ps = mSettings.mPackages.get(packageName);
12769            if (ps == null) {
12770                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12771                return false;
12772            }
12773            if (!ps.getInstalled(userId)) {
12774                // Can't block uninstall for an app that is not installed or enabled.
12775                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12776                return false;
12777            }
12778            ps.setBlockUninstall(blockUninstall, userId);
12779            mSettings.writePackageRestrictionsLPr(userId);
12780        }
12781        return true;
12782    }
12783
12784    @Override
12785    public boolean getBlockUninstallForUser(String packageName, int userId) {
12786        synchronized (mPackages) {
12787            PackageSetting ps = mSettings.mPackages.get(packageName);
12788            if (ps == null) {
12789                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12790                return false;
12791            }
12792            return ps.getBlockUninstall(userId);
12793        }
12794    }
12795
12796    /*
12797     * This method handles package deletion in general
12798     */
12799    private boolean deletePackageLI(String packageName, UserHandle user,
12800            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12801            int flags, PackageRemovedInfo outInfo,
12802            boolean writeSettings) {
12803        if (packageName == null) {
12804            Slog.w(TAG, "Attempt to delete null packageName.");
12805            return false;
12806        }
12807        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12808        PackageSetting ps;
12809        boolean dataOnly = false;
12810        int removeUser = -1;
12811        int appId = -1;
12812        synchronized (mPackages) {
12813            ps = mSettings.mPackages.get(packageName);
12814            if (ps == null) {
12815                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12816                return false;
12817            }
12818            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12819                    && user.getIdentifier() != UserHandle.USER_ALL) {
12820                // The caller is asking that the package only be deleted for a single
12821                // user.  To do this, we just mark its uninstalled state and delete
12822                // its data.  If this is a system app, we only allow this to happen if
12823                // they have set the special DELETE_SYSTEM_APP which requests different
12824                // semantics than normal for uninstalling system apps.
12825                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12826                ps.setUserState(user.getIdentifier(),
12827                        COMPONENT_ENABLED_STATE_DEFAULT,
12828                        false, //installed
12829                        true,  //stopped
12830                        true,  //notLaunched
12831                        false, //hidden
12832                        null, null, null,
12833                        false, // blockUninstall
12834                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12835                if (!isSystemApp(ps)) {
12836                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12837                        // Other user still have this package installed, so all
12838                        // we need to do is clear this user's data and save that
12839                        // it is uninstalled.
12840                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12841                        removeUser = user.getIdentifier();
12842                        appId = ps.appId;
12843                        scheduleWritePackageRestrictionsLocked(removeUser);
12844                    } else {
12845                        // We need to set it back to 'installed' so the uninstall
12846                        // broadcasts will be sent correctly.
12847                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12848                        ps.setInstalled(true, user.getIdentifier());
12849                    }
12850                } else {
12851                    // This is a system app, so we assume that the
12852                    // other users still have this package installed, so all
12853                    // we need to do is clear this user's data and save that
12854                    // it is uninstalled.
12855                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12856                    removeUser = user.getIdentifier();
12857                    appId = ps.appId;
12858                    scheduleWritePackageRestrictionsLocked(removeUser);
12859                }
12860            }
12861        }
12862
12863        if (removeUser >= 0) {
12864            // From above, we determined that we are deleting this only
12865            // for a single user.  Continue the work here.
12866            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12867            if (outInfo != null) {
12868                outInfo.removedPackage = packageName;
12869                outInfo.removedAppId = appId;
12870                outInfo.removedUsers = new int[] {removeUser};
12871            }
12872            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12873            removeKeystoreDataIfNeeded(removeUser, appId);
12874            schedulePackageCleaning(packageName, removeUser, false);
12875            synchronized (mPackages) {
12876                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12877                    scheduleWritePackageRestrictionsLocked(removeUser);
12878                }
12879                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12880                        removeUser);
12881            }
12882            return true;
12883        }
12884
12885        if (dataOnly) {
12886            // Delete application data first
12887            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12888            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12889            return true;
12890        }
12891
12892        boolean ret = false;
12893        if (isSystemApp(ps)) {
12894            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12895            // When an updated system application is deleted we delete the existing resources as well and
12896            // fall back to existing code in system partition
12897            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12898                    flags, outInfo, writeSettings);
12899        } else {
12900            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12901            // Kill application pre-emptively especially for apps on sd.
12902            killApplication(packageName, ps.appId, "uninstall pkg");
12903            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12904                    allUserHandles, perUserInstalled,
12905                    outInfo, writeSettings);
12906        }
12907
12908        return ret;
12909    }
12910
12911    private final class ClearStorageConnection implements ServiceConnection {
12912        IMediaContainerService mContainerService;
12913
12914        @Override
12915        public void onServiceConnected(ComponentName name, IBinder service) {
12916            synchronized (this) {
12917                mContainerService = IMediaContainerService.Stub.asInterface(service);
12918                notifyAll();
12919            }
12920        }
12921
12922        @Override
12923        public void onServiceDisconnected(ComponentName name) {
12924        }
12925    }
12926
12927    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12928        final boolean mounted;
12929        if (Environment.isExternalStorageEmulated()) {
12930            mounted = true;
12931        } else {
12932            final String status = Environment.getExternalStorageState();
12933
12934            mounted = status.equals(Environment.MEDIA_MOUNTED)
12935                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12936        }
12937
12938        if (!mounted) {
12939            return;
12940        }
12941
12942        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12943        int[] users;
12944        if (userId == UserHandle.USER_ALL) {
12945            users = sUserManager.getUserIds();
12946        } else {
12947            users = new int[] { userId };
12948        }
12949        final ClearStorageConnection conn = new ClearStorageConnection();
12950        if (mContext.bindServiceAsUser(
12951                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12952            try {
12953                for (int curUser : users) {
12954                    long timeout = SystemClock.uptimeMillis() + 5000;
12955                    synchronized (conn) {
12956                        long now = SystemClock.uptimeMillis();
12957                        while (conn.mContainerService == null && now < timeout) {
12958                            try {
12959                                conn.wait(timeout - now);
12960                            } catch (InterruptedException e) {
12961                            }
12962                        }
12963                    }
12964                    if (conn.mContainerService == null) {
12965                        return;
12966                    }
12967
12968                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12969                    clearDirectory(conn.mContainerService,
12970                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12971                    if (allData) {
12972                        clearDirectory(conn.mContainerService,
12973                                userEnv.buildExternalStorageAppDataDirs(packageName));
12974                        clearDirectory(conn.mContainerService,
12975                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12976                    }
12977                }
12978            } finally {
12979                mContext.unbindService(conn);
12980            }
12981        }
12982    }
12983
12984    @Override
12985    public void clearApplicationUserData(final String packageName,
12986            final IPackageDataObserver observer, final int userId) {
12987        mContext.enforceCallingOrSelfPermission(
12988                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12989        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12990        // Queue up an async operation since the package deletion may take a little while.
12991        mHandler.post(new Runnable() {
12992            public void run() {
12993                mHandler.removeCallbacks(this);
12994                final boolean succeeded;
12995                synchronized (mInstallLock) {
12996                    succeeded = clearApplicationUserDataLI(packageName, userId);
12997                }
12998                clearExternalStorageDataSync(packageName, userId, true);
12999                if (succeeded) {
13000                    // invoke DeviceStorageMonitor's update method to clear any notifications
13001                    DeviceStorageMonitorInternal
13002                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13003                    if (dsm != null) {
13004                        dsm.checkMemory();
13005                    }
13006                }
13007                if(observer != null) {
13008                    try {
13009                        observer.onRemoveCompleted(packageName, succeeded);
13010                    } catch (RemoteException e) {
13011                        Log.i(TAG, "Observer no longer exists.");
13012                    }
13013                } //end if observer
13014            } //end run
13015        });
13016    }
13017
13018    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13019        if (packageName == null) {
13020            Slog.w(TAG, "Attempt to delete null packageName.");
13021            return false;
13022        }
13023
13024        // Try finding details about the requested package
13025        PackageParser.Package pkg;
13026        synchronized (mPackages) {
13027            pkg = mPackages.get(packageName);
13028            if (pkg == null) {
13029                final PackageSetting ps = mSettings.mPackages.get(packageName);
13030                if (ps != null) {
13031                    pkg = ps.pkg;
13032                }
13033            }
13034
13035            if (pkg == null) {
13036                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13037                return false;
13038            }
13039
13040            PackageSetting ps = (PackageSetting) pkg.mExtras;
13041            PermissionsState permissionsState = ps.getPermissionsState();
13042            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13043        }
13044
13045        // Always delete data directories for package, even if we found no other
13046        // record of app. This helps users recover from UID mismatches without
13047        // resorting to a full data wipe.
13048        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13049        if (retCode < 0) {
13050            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13051            return false;
13052        }
13053
13054        final int appId = pkg.applicationInfo.uid;
13055        removeKeystoreDataIfNeeded(userId, appId);
13056
13057        // Create a native library symlink only if we have native libraries
13058        // and if the native libraries are 32 bit libraries. We do not provide
13059        // this symlink for 64 bit libraries.
13060        if (pkg.applicationInfo.primaryCpuAbi != null &&
13061                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13062            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13063            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13064                    nativeLibPath, userId) < 0) {
13065                Slog.w(TAG, "Failed linking native library dir");
13066                return false;
13067            }
13068        }
13069
13070        return true;
13071    }
13072
13073
13074    /**
13075     * Revokes granted runtime permissions and clears resettable flags
13076     * which are flags that can be set by a user interaction.
13077     *
13078     * @param permissionsState The permission state to reset.
13079     * @param userId The device user for which to do a reset.
13080     */
13081    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13082            PermissionsState permissionsState, int userId) {
13083        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13084                | PackageManager.FLAG_PERMISSION_USER_FIXED
13085                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13086
13087        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13088    }
13089
13090    /**
13091     * Revokes granted runtime permissions and clears all flags.
13092     *
13093     * @param permissionsState The permission state to reset.
13094     * @param userId The device user for which to do a reset.
13095     */
13096    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13097            PermissionsState permissionsState, int userId) {
13098        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13099                PackageManager.MASK_PERMISSION_FLAGS);
13100    }
13101
13102    /**
13103     * Revokes granted runtime permissions and clears certain flags.
13104     *
13105     * @param permissionsState The permission state to reset.
13106     * @param userId The device user for which to do a reset.
13107     * @param flags The flags that is going to be reset.
13108     */
13109    private void revokeRuntimePermissionsAndClearFlagsLocked(
13110            PermissionsState permissionsState, final int userId, int flags) {
13111        boolean needsWrite = false;
13112
13113        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13114            BasePermission bp = mSettings.mPermissions.get(state.getName());
13115            if (bp != null) {
13116                permissionsState.revokeRuntimePermission(bp, userId);
13117                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13118                needsWrite = true;
13119            }
13120        }
13121
13122        // Ensure default permissions are never cleared.
13123        mHandler.post(new Runnable() {
13124            @Override
13125            public void run() {
13126                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13127            }
13128        });
13129
13130        if (needsWrite) {
13131            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13132        }
13133    }
13134
13135    /**
13136     * Remove entries from the keystore daemon. Will only remove it if the
13137     * {@code appId} is valid.
13138     */
13139    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13140        if (appId < 0) {
13141            return;
13142        }
13143
13144        final KeyStore keyStore = KeyStore.getInstance();
13145        if (keyStore != null) {
13146            if (userId == UserHandle.USER_ALL) {
13147                for (final int individual : sUserManager.getUserIds()) {
13148                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13149                }
13150            } else {
13151                keyStore.clearUid(UserHandle.getUid(userId, appId));
13152            }
13153        } else {
13154            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13155        }
13156    }
13157
13158    @Override
13159    public void deleteApplicationCacheFiles(final String packageName,
13160            final IPackageDataObserver observer) {
13161        mContext.enforceCallingOrSelfPermission(
13162                android.Manifest.permission.DELETE_CACHE_FILES, null);
13163        // Queue up an async operation since the package deletion may take a little while.
13164        final int userId = UserHandle.getCallingUserId();
13165        mHandler.post(new Runnable() {
13166            public void run() {
13167                mHandler.removeCallbacks(this);
13168                final boolean succeded;
13169                synchronized (mInstallLock) {
13170                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13171                }
13172                clearExternalStorageDataSync(packageName, userId, false);
13173                if (observer != null) {
13174                    try {
13175                        observer.onRemoveCompleted(packageName, succeded);
13176                    } catch (RemoteException e) {
13177                        Log.i(TAG, "Observer no longer exists.");
13178                    }
13179                } //end if observer
13180            } //end run
13181        });
13182    }
13183
13184    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13185        if (packageName == null) {
13186            Slog.w(TAG, "Attempt to delete null packageName.");
13187            return false;
13188        }
13189        PackageParser.Package p;
13190        synchronized (mPackages) {
13191            p = mPackages.get(packageName);
13192        }
13193        if (p == null) {
13194            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13195            return false;
13196        }
13197        final ApplicationInfo applicationInfo = p.applicationInfo;
13198        if (applicationInfo == null) {
13199            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13200            return false;
13201        }
13202        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13203        if (retCode < 0) {
13204            Slog.w(TAG, "Couldn't remove cache files for package: "
13205                       + packageName + " u" + userId);
13206            return false;
13207        }
13208        return true;
13209    }
13210
13211    @Override
13212    public void getPackageSizeInfo(final String packageName, int userHandle,
13213            final IPackageStatsObserver observer) {
13214        mContext.enforceCallingOrSelfPermission(
13215                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13216        if (packageName == null) {
13217            throw new IllegalArgumentException("Attempt to get size of null packageName");
13218        }
13219
13220        PackageStats stats = new PackageStats(packageName, userHandle);
13221
13222        /*
13223         * Queue up an async operation since the package measurement may take a
13224         * little while.
13225         */
13226        Message msg = mHandler.obtainMessage(INIT_COPY);
13227        msg.obj = new MeasureParams(stats, observer);
13228        mHandler.sendMessage(msg);
13229    }
13230
13231    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13232            PackageStats pStats) {
13233        if (packageName == null) {
13234            Slog.w(TAG, "Attempt to get size of null packageName.");
13235            return false;
13236        }
13237        PackageParser.Package p;
13238        boolean dataOnly = false;
13239        String libDirRoot = null;
13240        String asecPath = null;
13241        PackageSetting ps = null;
13242        synchronized (mPackages) {
13243            p = mPackages.get(packageName);
13244            ps = mSettings.mPackages.get(packageName);
13245            if(p == null) {
13246                dataOnly = true;
13247                if((ps == null) || (ps.pkg == null)) {
13248                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13249                    return false;
13250                }
13251                p = ps.pkg;
13252            }
13253            if (ps != null) {
13254                libDirRoot = ps.legacyNativeLibraryPathString;
13255            }
13256            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13257                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13258                if (secureContainerId != null) {
13259                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13260                }
13261            }
13262        }
13263        String publicSrcDir = null;
13264        if(!dataOnly) {
13265            final ApplicationInfo applicationInfo = p.applicationInfo;
13266            if (applicationInfo == null) {
13267                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13268                return false;
13269            }
13270            if (p.isForwardLocked()) {
13271                publicSrcDir = applicationInfo.getBaseResourcePath();
13272            }
13273        }
13274        // TODO: extend to measure size of split APKs
13275        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13276        // not just the first level.
13277        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13278        // just the primary.
13279        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13280        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13281                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13282        if (res < 0) {
13283            return false;
13284        }
13285
13286        // Fix-up for forward-locked applications in ASEC containers.
13287        if (!isExternal(p)) {
13288            pStats.codeSize += pStats.externalCodeSize;
13289            pStats.externalCodeSize = 0L;
13290        }
13291
13292        return true;
13293    }
13294
13295
13296    @Override
13297    public void addPackageToPreferred(String packageName) {
13298        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13299    }
13300
13301    @Override
13302    public void removePackageFromPreferred(String packageName) {
13303        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13304    }
13305
13306    @Override
13307    public List<PackageInfo> getPreferredPackages(int flags) {
13308        return new ArrayList<PackageInfo>();
13309    }
13310
13311    private int getUidTargetSdkVersionLockedLPr(int uid) {
13312        Object obj = mSettings.getUserIdLPr(uid);
13313        if (obj instanceof SharedUserSetting) {
13314            final SharedUserSetting sus = (SharedUserSetting) obj;
13315            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13316            final Iterator<PackageSetting> it = sus.packages.iterator();
13317            while (it.hasNext()) {
13318                final PackageSetting ps = it.next();
13319                if (ps.pkg != null) {
13320                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13321                    if (v < vers) vers = v;
13322                }
13323            }
13324            return vers;
13325        } else if (obj instanceof PackageSetting) {
13326            final PackageSetting ps = (PackageSetting) obj;
13327            if (ps.pkg != null) {
13328                return ps.pkg.applicationInfo.targetSdkVersion;
13329            }
13330        }
13331        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13332    }
13333
13334    @Override
13335    public void addPreferredActivity(IntentFilter filter, int match,
13336            ComponentName[] set, ComponentName activity, int userId) {
13337        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13338                "Adding preferred");
13339    }
13340
13341    private void addPreferredActivityInternal(IntentFilter filter, int match,
13342            ComponentName[] set, ComponentName activity, boolean always, int userId,
13343            String opname) {
13344        // writer
13345        int callingUid = Binder.getCallingUid();
13346        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13347        if (filter.countActions() == 0) {
13348            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13349            return;
13350        }
13351        synchronized (mPackages) {
13352            if (mContext.checkCallingOrSelfPermission(
13353                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13354                    != PackageManager.PERMISSION_GRANTED) {
13355                if (getUidTargetSdkVersionLockedLPr(callingUid)
13356                        < Build.VERSION_CODES.FROYO) {
13357                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13358                            + callingUid);
13359                    return;
13360                }
13361                mContext.enforceCallingOrSelfPermission(
13362                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13363            }
13364
13365            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13366            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13367                    + userId + ":");
13368            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13369            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13370            scheduleWritePackageRestrictionsLocked(userId);
13371        }
13372    }
13373
13374    @Override
13375    public void replacePreferredActivity(IntentFilter filter, int match,
13376            ComponentName[] set, ComponentName activity, int userId) {
13377        if (filter.countActions() != 1) {
13378            throw new IllegalArgumentException(
13379                    "replacePreferredActivity expects filter to have only 1 action.");
13380        }
13381        if (filter.countDataAuthorities() != 0
13382                || filter.countDataPaths() != 0
13383                || filter.countDataSchemes() > 1
13384                || filter.countDataTypes() != 0) {
13385            throw new IllegalArgumentException(
13386                    "replacePreferredActivity expects filter to have no data authorities, " +
13387                    "paths, or types; and at most one scheme.");
13388        }
13389
13390        final int callingUid = Binder.getCallingUid();
13391        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13392        synchronized (mPackages) {
13393            if (mContext.checkCallingOrSelfPermission(
13394                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13395                    != PackageManager.PERMISSION_GRANTED) {
13396                if (getUidTargetSdkVersionLockedLPr(callingUid)
13397                        < Build.VERSION_CODES.FROYO) {
13398                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13399                            + Binder.getCallingUid());
13400                    return;
13401                }
13402                mContext.enforceCallingOrSelfPermission(
13403                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13404            }
13405
13406            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13407            if (pir != null) {
13408                // Get all of the existing entries that exactly match this filter.
13409                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13410                if (existing != null && existing.size() == 1) {
13411                    PreferredActivity cur = existing.get(0);
13412                    if (DEBUG_PREFERRED) {
13413                        Slog.i(TAG, "Checking replace of preferred:");
13414                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13415                        if (!cur.mPref.mAlways) {
13416                            Slog.i(TAG, "  -- CUR; not mAlways!");
13417                        } else {
13418                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13419                            Slog.i(TAG, "  -- CUR: mSet="
13420                                    + Arrays.toString(cur.mPref.mSetComponents));
13421                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13422                            Slog.i(TAG, "  -- NEW: mMatch="
13423                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13424                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13425                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13426                        }
13427                    }
13428                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13429                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13430                            && cur.mPref.sameSet(set)) {
13431                        // Setting the preferred activity to what it happens to be already
13432                        if (DEBUG_PREFERRED) {
13433                            Slog.i(TAG, "Replacing with same preferred activity "
13434                                    + cur.mPref.mShortComponent + " for user "
13435                                    + userId + ":");
13436                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13437                        }
13438                        return;
13439                    }
13440                }
13441
13442                if (existing != null) {
13443                    if (DEBUG_PREFERRED) {
13444                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13445                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13446                    }
13447                    for (int i = 0; i < existing.size(); i++) {
13448                        PreferredActivity pa = existing.get(i);
13449                        if (DEBUG_PREFERRED) {
13450                            Slog.i(TAG, "Removing existing preferred activity "
13451                                    + pa.mPref.mComponent + ":");
13452                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13453                        }
13454                        pir.removeFilter(pa);
13455                    }
13456                }
13457            }
13458            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13459                    "Replacing preferred");
13460        }
13461    }
13462
13463    @Override
13464    public void clearPackagePreferredActivities(String packageName) {
13465        final int uid = Binder.getCallingUid();
13466        // writer
13467        synchronized (mPackages) {
13468            PackageParser.Package pkg = mPackages.get(packageName);
13469            if (pkg == null || pkg.applicationInfo.uid != uid) {
13470                if (mContext.checkCallingOrSelfPermission(
13471                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13472                        != PackageManager.PERMISSION_GRANTED) {
13473                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13474                            < Build.VERSION_CODES.FROYO) {
13475                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13476                                + Binder.getCallingUid());
13477                        return;
13478                    }
13479                    mContext.enforceCallingOrSelfPermission(
13480                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13481                }
13482            }
13483
13484            int user = UserHandle.getCallingUserId();
13485            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13486                scheduleWritePackageRestrictionsLocked(user);
13487            }
13488        }
13489    }
13490
13491    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13492    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13493        ArrayList<PreferredActivity> removed = null;
13494        boolean changed = false;
13495        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13496            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13497            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13498            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13499                continue;
13500            }
13501            Iterator<PreferredActivity> it = pir.filterIterator();
13502            while (it.hasNext()) {
13503                PreferredActivity pa = it.next();
13504                // Mark entry for removal only if it matches the package name
13505                // and the entry is of type "always".
13506                if (packageName == null ||
13507                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13508                                && pa.mPref.mAlways)) {
13509                    if (removed == null) {
13510                        removed = new ArrayList<PreferredActivity>();
13511                    }
13512                    removed.add(pa);
13513                }
13514            }
13515            if (removed != null) {
13516                for (int j=0; j<removed.size(); j++) {
13517                    PreferredActivity pa = removed.get(j);
13518                    pir.removeFilter(pa);
13519                }
13520                changed = true;
13521            }
13522        }
13523        return changed;
13524    }
13525
13526    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13527    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13528        if (userId == UserHandle.USER_ALL) {
13529            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13530                    sUserManager.getUserIds())) {
13531                for (int oneUserId : sUserManager.getUserIds()) {
13532                    scheduleWritePackageRestrictionsLocked(oneUserId);
13533                }
13534            }
13535        } else {
13536            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13537                scheduleWritePackageRestrictionsLocked(userId);
13538            }
13539        }
13540    }
13541
13542
13543    void clearDefaultBrowserIfNeeded(String packageName) {
13544        for (int oneUserId : sUserManager.getUserIds()) {
13545            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13546            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13547            if (packageName.equals(defaultBrowserPackageName)) {
13548                setDefaultBrowserPackageName(null, oneUserId);
13549            }
13550        }
13551    }
13552
13553    @Override
13554    public void resetPreferredActivities(int userId) {
13555        mContext.enforceCallingOrSelfPermission(
13556                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13557        // writer
13558        synchronized (mPackages) {
13559            clearPackagePreferredActivitiesLPw(null, userId);
13560            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13561            applyFactoryDefaultBrowserLPw(userId);
13562
13563            scheduleWritePackageRestrictionsLocked(userId);
13564        }
13565    }
13566
13567    @Override
13568    public int getPreferredActivities(List<IntentFilter> outFilters,
13569            List<ComponentName> outActivities, String packageName) {
13570
13571        int num = 0;
13572        final int userId = UserHandle.getCallingUserId();
13573        // reader
13574        synchronized (mPackages) {
13575            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13576            if (pir != null) {
13577                final Iterator<PreferredActivity> it = pir.filterIterator();
13578                while (it.hasNext()) {
13579                    final PreferredActivity pa = it.next();
13580                    if (packageName == null
13581                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13582                                    && pa.mPref.mAlways)) {
13583                        if (outFilters != null) {
13584                            outFilters.add(new IntentFilter(pa));
13585                        }
13586                        if (outActivities != null) {
13587                            outActivities.add(pa.mPref.mComponent);
13588                        }
13589                    }
13590                }
13591            }
13592        }
13593
13594        return num;
13595    }
13596
13597    @Override
13598    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13599            int userId) {
13600        int callingUid = Binder.getCallingUid();
13601        if (callingUid != Process.SYSTEM_UID) {
13602            throw new SecurityException(
13603                    "addPersistentPreferredActivity can only be run by the system");
13604        }
13605        if (filter.countActions() == 0) {
13606            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13607            return;
13608        }
13609        synchronized (mPackages) {
13610            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13611                    " :");
13612            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13613            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13614                    new PersistentPreferredActivity(filter, activity));
13615            scheduleWritePackageRestrictionsLocked(userId);
13616        }
13617    }
13618
13619    @Override
13620    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13621        int callingUid = Binder.getCallingUid();
13622        if (callingUid != Process.SYSTEM_UID) {
13623            throw new SecurityException(
13624                    "clearPackagePersistentPreferredActivities can only be run by the system");
13625        }
13626        ArrayList<PersistentPreferredActivity> removed = null;
13627        boolean changed = false;
13628        synchronized (mPackages) {
13629            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13630                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13631                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13632                        .valueAt(i);
13633                if (userId != thisUserId) {
13634                    continue;
13635                }
13636                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13637                while (it.hasNext()) {
13638                    PersistentPreferredActivity ppa = it.next();
13639                    // Mark entry for removal only if it matches the package name.
13640                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13641                        if (removed == null) {
13642                            removed = new ArrayList<PersistentPreferredActivity>();
13643                        }
13644                        removed.add(ppa);
13645                    }
13646                }
13647                if (removed != null) {
13648                    for (int j=0; j<removed.size(); j++) {
13649                        PersistentPreferredActivity ppa = removed.get(j);
13650                        ppir.removeFilter(ppa);
13651                    }
13652                    changed = true;
13653                }
13654            }
13655
13656            if (changed) {
13657                scheduleWritePackageRestrictionsLocked(userId);
13658            }
13659        }
13660    }
13661
13662    /**
13663     * Common machinery for picking apart a restored XML blob and passing
13664     * it to a caller-supplied functor to be applied to the running system.
13665     */
13666    private void restoreFromXml(XmlPullParser parser, int userId,
13667            String expectedStartTag, BlobXmlRestorer functor)
13668            throws IOException, XmlPullParserException {
13669        int type;
13670        while ((type = parser.next()) != XmlPullParser.START_TAG
13671                && type != XmlPullParser.END_DOCUMENT) {
13672        }
13673        if (type != XmlPullParser.START_TAG) {
13674            // oops didn't find a start tag?!
13675            if (DEBUG_BACKUP) {
13676                Slog.e(TAG, "Didn't find start tag during restore");
13677            }
13678            return;
13679        }
13680
13681        // this is supposed to be TAG_PREFERRED_BACKUP
13682        if (!expectedStartTag.equals(parser.getName())) {
13683            if (DEBUG_BACKUP) {
13684                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13685            }
13686            return;
13687        }
13688
13689        // skip interfering stuff, then we're aligned with the backing implementation
13690        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13691        functor.apply(parser, userId);
13692    }
13693
13694    private interface BlobXmlRestorer {
13695        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13696    }
13697
13698    /**
13699     * Non-Binder method, support for the backup/restore mechanism: write the
13700     * full set of preferred activities in its canonical XML format.  Returns the
13701     * XML output as a byte array, or null if there is none.
13702     */
13703    @Override
13704    public byte[] getPreferredActivityBackup(int userId) {
13705        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13706            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13707        }
13708
13709        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13710        try {
13711            final XmlSerializer serializer = new FastXmlSerializer();
13712            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13713            serializer.startDocument(null, true);
13714            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13715
13716            synchronized (mPackages) {
13717                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13718            }
13719
13720            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13721            serializer.endDocument();
13722            serializer.flush();
13723        } catch (Exception e) {
13724            if (DEBUG_BACKUP) {
13725                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13726            }
13727            return null;
13728        }
13729
13730        return dataStream.toByteArray();
13731    }
13732
13733    @Override
13734    public void restorePreferredActivities(byte[] backup, int userId) {
13735        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13736            throw new SecurityException("Only the system may call restorePreferredActivities()");
13737        }
13738
13739        try {
13740            final XmlPullParser parser = Xml.newPullParser();
13741            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13742            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13743                    new BlobXmlRestorer() {
13744                        @Override
13745                        public void apply(XmlPullParser parser, int userId)
13746                                throws XmlPullParserException, IOException {
13747                            synchronized (mPackages) {
13748                                mSettings.readPreferredActivitiesLPw(parser, userId);
13749                            }
13750                        }
13751                    } );
13752        } catch (Exception e) {
13753            if (DEBUG_BACKUP) {
13754                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13755            }
13756        }
13757    }
13758
13759    /**
13760     * Non-Binder method, support for the backup/restore mechanism: write the
13761     * default browser (etc) settings in its canonical XML format.  Returns the default
13762     * browser XML representation as a byte array, or null if there is none.
13763     */
13764    @Override
13765    public byte[] getDefaultAppsBackup(int userId) {
13766        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13767            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13768        }
13769
13770        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13771        try {
13772            final XmlSerializer serializer = new FastXmlSerializer();
13773            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13774            serializer.startDocument(null, true);
13775            serializer.startTag(null, TAG_DEFAULT_APPS);
13776
13777            synchronized (mPackages) {
13778                mSettings.writeDefaultAppsLPr(serializer, userId);
13779            }
13780
13781            serializer.endTag(null, TAG_DEFAULT_APPS);
13782            serializer.endDocument();
13783            serializer.flush();
13784        } catch (Exception e) {
13785            if (DEBUG_BACKUP) {
13786                Slog.e(TAG, "Unable to write default apps for backup", e);
13787            }
13788            return null;
13789        }
13790
13791        return dataStream.toByteArray();
13792    }
13793
13794    @Override
13795    public void restoreDefaultApps(byte[] backup, int userId) {
13796        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13797            throw new SecurityException("Only the system may call restoreDefaultApps()");
13798        }
13799
13800        try {
13801            final XmlPullParser parser = Xml.newPullParser();
13802            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13803            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13804                    new BlobXmlRestorer() {
13805                        @Override
13806                        public void apply(XmlPullParser parser, int userId)
13807                                throws XmlPullParserException, IOException {
13808                            synchronized (mPackages) {
13809                                mSettings.readDefaultAppsLPw(parser, userId);
13810                            }
13811                        }
13812                    } );
13813        } catch (Exception e) {
13814            if (DEBUG_BACKUP) {
13815                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13816            }
13817        }
13818    }
13819
13820    @Override
13821    public byte[] getIntentFilterVerificationBackup(int userId) {
13822        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13823            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13824        }
13825
13826        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13827        try {
13828            final XmlSerializer serializer = new FastXmlSerializer();
13829            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13830            serializer.startDocument(null, true);
13831            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13832
13833            synchronized (mPackages) {
13834                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13835            }
13836
13837            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13838            serializer.endDocument();
13839            serializer.flush();
13840        } catch (Exception e) {
13841            if (DEBUG_BACKUP) {
13842                Slog.e(TAG, "Unable to write default apps for backup", e);
13843            }
13844            return null;
13845        }
13846
13847        return dataStream.toByteArray();
13848    }
13849
13850    @Override
13851    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13852        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13853            throw new SecurityException("Only the system may call restorePreferredActivities()");
13854        }
13855
13856        try {
13857            final XmlPullParser parser = Xml.newPullParser();
13858            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13859            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13860                    new BlobXmlRestorer() {
13861                        @Override
13862                        public void apply(XmlPullParser parser, int userId)
13863                                throws XmlPullParserException, IOException {
13864                            synchronized (mPackages) {
13865                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13866                                mSettings.writeLPr();
13867                            }
13868                        }
13869                    } );
13870        } catch (Exception e) {
13871            if (DEBUG_BACKUP) {
13872                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13873            }
13874        }
13875    }
13876
13877    @Override
13878    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13879            int sourceUserId, int targetUserId, int flags) {
13880        mContext.enforceCallingOrSelfPermission(
13881                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13882        int callingUid = Binder.getCallingUid();
13883        enforceOwnerRights(ownerPackage, callingUid);
13884        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13885        if (intentFilter.countActions() == 0) {
13886            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13887            return;
13888        }
13889        synchronized (mPackages) {
13890            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13891                    ownerPackage, targetUserId, flags);
13892            CrossProfileIntentResolver resolver =
13893                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13894            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13895            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13896            if (existing != null) {
13897                int size = existing.size();
13898                for (int i = 0; i < size; i++) {
13899                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13900                        return;
13901                    }
13902                }
13903            }
13904            resolver.addFilter(newFilter);
13905            scheduleWritePackageRestrictionsLocked(sourceUserId);
13906        }
13907    }
13908
13909    @Override
13910    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13911        mContext.enforceCallingOrSelfPermission(
13912                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13913        int callingUid = Binder.getCallingUid();
13914        enforceOwnerRights(ownerPackage, callingUid);
13915        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13916        synchronized (mPackages) {
13917            CrossProfileIntentResolver resolver =
13918                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13919            ArraySet<CrossProfileIntentFilter> set =
13920                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13921            for (CrossProfileIntentFilter filter : set) {
13922                if (filter.getOwnerPackage().equals(ownerPackage)) {
13923                    resolver.removeFilter(filter);
13924                }
13925            }
13926            scheduleWritePackageRestrictionsLocked(sourceUserId);
13927        }
13928    }
13929
13930    // Enforcing that callingUid is owning pkg on userId
13931    private void enforceOwnerRights(String pkg, int callingUid) {
13932        // The system owns everything.
13933        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13934            return;
13935        }
13936        int callingUserId = UserHandle.getUserId(callingUid);
13937        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13938        if (pi == null) {
13939            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13940                    + callingUserId);
13941        }
13942        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13943            throw new SecurityException("Calling uid " + callingUid
13944                    + " does not own package " + pkg);
13945        }
13946    }
13947
13948    @Override
13949    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13950        Intent intent = new Intent(Intent.ACTION_MAIN);
13951        intent.addCategory(Intent.CATEGORY_HOME);
13952
13953        final int callingUserId = UserHandle.getCallingUserId();
13954        List<ResolveInfo> list = queryIntentActivities(intent, null,
13955                PackageManager.GET_META_DATA, callingUserId);
13956        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13957                true, false, false, callingUserId);
13958
13959        allHomeCandidates.clear();
13960        if (list != null) {
13961            for (ResolveInfo ri : list) {
13962                allHomeCandidates.add(ri);
13963            }
13964        }
13965        return (preferred == null || preferred.activityInfo == null)
13966                ? null
13967                : new ComponentName(preferred.activityInfo.packageName,
13968                        preferred.activityInfo.name);
13969    }
13970
13971    @Override
13972    public void setApplicationEnabledSetting(String appPackageName,
13973            int newState, int flags, int userId, String callingPackage) {
13974        if (!sUserManager.exists(userId)) return;
13975        if (callingPackage == null) {
13976            callingPackage = Integer.toString(Binder.getCallingUid());
13977        }
13978        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13979    }
13980
13981    @Override
13982    public void setComponentEnabledSetting(ComponentName componentName,
13983            int newState, int flags, int userId) {
13984        if (!sUserManager.exists(userId)) return;
13985        setEnabledSetting(componentName.getPackageName(),
13986                componentName.getClassName(), newState, flags, userId, null);
13987    }
13988
13989    private void setEnabledSetting(final String packageName, String className, int newState,
13990            final int flags, int userId, String callingPackage) {
13991        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13992              || newState == COMPONENT_ENABLED_STATE_ENABLED
13993              || newState == COMPONENT_ENABLED_STATE_DISABLED
13994              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13995              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13996            throw new IllegalArgumentException("Invalid new component state: "
13997                    + newState);
13998        }
13999        PackageSetting pkgSetting;
14000        final int uid = Binder.getCallingUid();
14001        final int permission = mContext.checkCallingOrSelfPermission(
14002                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14003        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14004        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14005        boolean sendNow = false;
14006        boolean isApp = (className == null);
14007        String componentName = isApp ? packageName : className;
14008        int packageUid = -1;
14009        ArrayList<String> components;
14010
14011        // writer
14012        synchronized (mPackages) {
14013            pkgSetting = mSettings.mPackages.get(packageName);
14014            if (pkgSetting == null) {
14015                if (className == null) {
14016                    throw new IllegalArgumentException(
14017                            "Unknown package: " + packageName);
14018                }
14019                throw new IllegalArgumentException(
14020                        "Unknown component: " + packageName
14021                        + "/" + className);
14022            }
14023            // Allow root and verify that userId is not being specified by a different user
14024            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14025                throw new SecurityException(
14026                        "Permission Denial: attempt to change component state from pid="
14027                        + Binder.getCallingPid()
14028                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14029            }
14030            if (className == null) {
14031                // We're dealing with an application/package level state change
14032                if (pkgSetting.getEnabled(userId) == newState) {
14033                    // Nothing to do
14034                    return;
14035                }
14036                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14037                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14038                    // Don't care about who enables an app.
14039                    callingPackage = null;
14040                }
14041                pkgSetting.setEnabled(newState, userId, callingPackage);
14042                // pkgSetting.pkg.mSetEnabled = newState;
14043            } else {
14044                // We're dealing with a component level state change
14045                // First, verify that this is a valid class name.
14046                PackageParser.Package pkg = pkgSetting.pkg;
14047                if (pkg == null || !pkg.hasComponentClassName(className)) {
14048                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14049                        throw new IllegalArgumentException("Component class " + className
14050                                + " does not exist in " + packageName);
14051                    } else {
14052                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14053                                + className + " does not exist in " + packageName);
14054                    }
14055                }
14056                switch (newState) {
14057                case COMPONENT_ENABLED_STATE_ENABLED:
14058                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14059                        return;
14060                    }
14061                    break;
14062                case COMPONENT_ENABLED_STATE_DISABLED:
14063                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14064                        return;
14065                    }
14066                    break;
14067                case COMPONENT_ENABLED_STATE_DEFAULT:
14068                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14069                        return;
14070                    }
14071                    break;
14072                default:
14073                    Slog.e(TAG, "Invalid new component state: " + newState);
14074                    return;
14075                }
14076            }
14077            scheduleWritePackageRestrictionsLocked(userId);
14078            components = mPendingBroadcasts.get(userId, packageName);
14079            final boolean newPackage = components == null;
14080            if (newPackage) {
14081                components = new ArrayList<String>();
14082            }
14083            if (!components.contains(componentName)) {
14084                components.add(componentName);
14085            }
14086            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14087                sendNow = true;
14088                // Purge entry from pending broadcast list if another one exists already
14089                // since we are sending one right away.
14090                mPendingBroadcasts.remove(userId, packageName);
14091            } else {
14092                if (newPackage) {
14093                    mPendingBroadcasts.put(userId, packageName, components);
14094                }
14095                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14096                    // Schedule a message
14097                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14098                }
14099            }
14100        }
14101
14102        long callingId = Binder.clearCallingIdentity();
14103        try {
14104            if (sendNow) {
14105                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14106                sendPackageChangedBroadcast(packageName,
14107                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14108            }
14109        } finally {
14110            Binder.restoreCallingIdentity(callingId);
14111        }
14112    }
14113
14114    private void sendPackageChangedBroadcast(String packageName,
14115            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14116        if (DEBUG_INSTALL)
14117            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14118                    + componentNames);
14119        Bundle extras = new Bundle(4);
14120        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14121        String nameList[] = new String[componentNames.size()];
14122        componentNames.toArray(nameList);
14123        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14124        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14125        extras.putInt(Intent.EXTRA_UID, packageUid);
14126        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14127                new int[] {UserHandle.getUserId(packageUid)});
14128    }
14129
14130    @Override
14131    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14132        if (!sUserManager.exists(userId)) return;
14133        final int uid = Binder.getCallingUid();
14134        final int permission = mContext.checkCallingOrSelfPermission(
14135                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14136        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14137        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14138        // writer
14139        synchronized (mPackages) {
14140            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14141                    allowedByPermission, uid, userId)) {
14142                scheduleWritePackageRestrictionsLocked(userId);
14143            }
14144        }
14145    }
14146
14147    @Override
14148    public String getInstallerPackageName(String packageName) {
14149        // reader
14150        synchronized (mPackages) {
14151            return mSettings.getInstallerPackageNameLPr(packageName);
14152        }
14153    }
14154
14155    @Override
14156    public int getApplicationEnabledSetting(String packageName, int userId) {
14157        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14158        int uid = Binder.getCallingUid();
14159        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14160        // reader
14161        synchronized (mPackages) {
14162            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14163        }
14164    }
14165
14166    @Override
14167    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14168        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14169        int uid = Binder.getCallingUid();
14170        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14171        // reader
14172        synchronized (mPackages) {
14173            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14174        }
14175    }
14176
14177    @Override
14178    public void enterSafeMode() {
14179        enforceSystemOrRoot("Only the system can request entering safe mode");
14180
14181        if (!mSystemReady) {
14182            mSafeMode = true;
14183        }
14184    }
14185
14186    @Override
14187    public void systemReady() {
14188        mSystemReady = true;
14189
14190        // Read the compatibilty setting when the system is ready.
14191        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14192                mContext.getContentResolver(),
14193                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14194        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14195        if (DEBUG_SETTINGS) {
14196            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14197        }
14198
14199        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14200
14201        synchronized (mPackages) {
14202            // Verify that all of the preferred activity components actually
14203            // exist.  It is possible for applications to be updated and at
14204            // that point remove a previously declared activity component that
14205            // had been set as a preferred activity.  We try to clean this up
14206            // the next time we encounter that preferred activity, but it is
14207            // possible for the user flow to never be able to return to that
14208            // situation so here we do a sanity check to make sure we haven't
14209            // left any junk around.
14210            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14211            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14212                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14213                removed.clear();
14214                for (PreferredActivity pa : pir.filterSet()) {
14215                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14216                        removed.add(pa);
14217                    }
14218                }
14219                if (removed.size() > 0) {
14220                    for (int r=0; r<removed.size(); r++) {
14221                        PreferredActivity pa = removed.get(r);
14222                        Slog.w(TAG, "Removing dangling preferred activity: "
14223                                + pa.mPref.mComponent);
14224                        pir.removeFilter(pa);
14225                    }
14226                    mSettings.writePackageRestrictionsLPr(
14227                            mSettings.mPreferredActivities.keyAt(i));
14228                }
14229            }
14230
14231            for (int userId : UserManagerService.getInstance().getUserIds()) {
14232                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14233                    grantPermissionsUserIds = ArrayUtils.appendInt(
14234                            grantPermissionsUserIds, userId);
14235                }
14236            }
14237        }
14238        sUserManager.systemReady();
14239
14240        // If we upgraded grant all default permissions before kicking off.
14241        for (int userId : grantPermissionsUserIds) {
14242            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14243        }
14244
14245        // Kick off any messages waiting for system ready
14246        if (mPostSystemReadyMessages != null) {
14247            for (Message msg : mPostSystemReadyMessages) {
14248                msg.sendToTarget();
14249            }
14250            mPostSystemReadyMessages = null;
14251        }
14252
14253        // Watch for external volumes that come and go over time
14254        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14255        storage.registerListener(mStorageListener);
14256
14257        mInstallerService.systemReady();
14258        mPackageDexOptimizer.systemReady();
14259    }
14260
14261    @Override
14262    public boolean isSafeMode() {
14263        return mSafeMode;
14264    }
14265
14266    @Override
14267    public boolean hasSystemUidErrors() {
14268        return mHasSystemUidErrors;
14269    }
14270
14271    static String arrayToString(int[] array) {
14272        StringBuffer buf = new StringBuffer(128);
14273        buf.append('[');
14274        if (array != null) {
14275            for (int i=0; i<array.length; i++) {
14276                if (i > 0) buf.append(", ");
14277                buf.append(array[i]);
14278            }
14279        }
14280        buf.append(']');
14281        return buf.toString();
14282    }
14283
14284    static class DumpState {
14285        public static final int DUMP_LIBS = 1 << 0;
14286        public static final int DUMP_FEATURES = 1 << 1;
14287        public static final int DUMP_RESOLVERS = 1 << 2;
14288        public static final int DUMP_PERMISSIONS = 1 << 3;
14289        public static final int DUMP_PACKAGES = 1 << 4;
14290        public static final int DUMP_SHARED_USERS = 1 << 5;
14291        public static final int DUMP_MESSAGES = 1 << 6;
14292        public static final int DUMP_PROVIDERS = 1 << 7;
14293        public static final int DUMP_VERIFIERS = 1 << 8;
14294        public static final int DUMP_PREFERRED = 1 << 9;
14295        public static final int DUMP_PREFERRED_XML = 1 << 10;
14296        public static final int DUMP_KEYSETS = 1 << 11;
14297        public static final int DUMP_VERSION = 1 << 12;
14298        public static final int DUMP_INSTALLS = 1 << 13;
14299        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14300        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14301
14302        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14303
14304        private int mTypes;
14305
14306        private int mOptions;
14307
14308        private boolean mTitlePrinted;
14309
14310        private SharedUserSetting mSharedUser;
14311
14312        public boolean isDumping(int type) {
14313            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14314                return true;
14315            }
14316
14317            return (mTypes & type) != 0;
14318        }
14319
14320        public void setDump(int type) {
14321            mTypes |= type;
14322        }
14323
14324        public boolean isOptionEnabled(int option) {
14325            return (mOptions & option) != 0;
14326        }
14327
14328        public void setOptionEnabled(int option) {
14329            mOptions |= option;
14330        }
14331
14332        public boolean onTitlePrinted() {
14333            final boolean printed = mTitlePrinted;
14334            mTitlePrinted = true;
14335            return printed;
14336        }
14337
14338        public boolean getTitlePrinted() {
14339            return mTitlePrinted;
14340        }
14341
14342        public void setTitlePrinted(boolean enabled) {
14343            mTitlePrinted = enabled;
14344        }
14345
14346        public SharedUserSetting getSharedUser() {
14347            return mSharedUser;
14348        }
14349
14350        public void setSharedUser(SharedUserSetting user) {
14351            mSharedUser = user;
14352        }
14353    }
14354
14355    @Override
14356    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14357        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14358                != PackageManager.PERMISSION_GRANTED) {
14359            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14360                    + Binder.getCallingPid()
14361                    + ", uid=" + Binder.getCallingUid()
14362                    + " without permission "
14363                    + android.Manifest.permission.DUMP);
14364            return;
14365        }
14366
14367        DumpState dumpState = new DumpState();
14368        boolean fullPreferred = false;
14369        boolean checkin = false;
14370
14371        String packageName = null;
14372        ArraySet<String> permissionNames = null;
14373
14374        int opti = 0;
14375        while (opti < args.length) {
14376            String opt = args[opti];
14377            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14378                break;
14379            }
14380            opti++;
14381
14382            if ("-a".equals(opt)) {
14383                // Right now we only know how to print all.
14384            } else if ("-h".equals(opt)) {
14385                pw.println("Package manager dump options:");
14386                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14387                pw.println("    --checkin: dump for a checkin");
14388                pw.println("    -f: print details of intent filters");
14389                pw.println("    -h: print this help");
14390                pw.println("  cmd may be one of:");
14391                pw.println("    l[ibraries]: list known shared libraries");
14392                pw.println("    f[ibraries]: list device features");
14393                pw.println("    k[eysets]: print known keysets");
14394                pw.println("    r[esolvers]: dump intent resolvers");
14395                pw.println("    perm[issions]: dump permissions");
14396                pw.println("    permission [name ...]: dump declaration and use of given permission");
14397                pw.println("    pref[erred]: print preferred package settings");
14398                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14399                pw.println("    prov[iders]: dump content providers");
14400                pw.println("    p[ackages]: dump installed packages");
14401                pw.println("    s[hared-users]: dump shared user IDs");
14402                pw.println("    m[essages]: print collected runtime messages");
14403                pw.println("    v[erifiers]: print package verifier info");
14404                pw.println("    version: print database version info");
14405                pw.println("    write: write current settings now");
14406                pw.println("    <package.name>: info about given package");
14407                pw.println("    installs: details about install sessions");
14408                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14409                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14410                return;
14411            } else if ("--checkin".equals(opt)) {
14412                checkin = true;
14413            } else if ("-f".equals(opt)) {
14414                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14415            } else {
14416                pw.println("Unknown argument: " + opt + "; use -h for help");
14417            }
14418        }
14419
14420        // Is the caller requesting to dump a particular piece of data?
14421        if (opti < args.length) {
14422            String cmd = args[opti];
14423            opti++;
14424            // Is this a package name?
14425            if ("android".equals(cmd) || cmd.contains(".")) {
14426                packageName = cmd;
14427                // When dumping a single package, we always dump all of its
14428                // filter information since the amount of data will be reasonable.
14429                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14430            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14431                dumpState.setDump(DumpState.DUMP_LIBS);
14432            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14433                dumpState.setDump(DumpState.DUMP_FEATURES);
14434            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14435                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14436            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14437                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14438            } else if ("permission".equals(cmd)) {
14439                if (opti >= args.length) {
14440                    pw.println("Error: permission requires permission name");
14441                    return;
14442                }
14443                permissionNames = new ArraySet<>();
14444                while (opti < args.length) {
14445                    permissionNames.add(args[opti]);
14446                    opti++;
14447                }
14448                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14449                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14450            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14451                dumpState.setDump(DumpState.DUMP_PREFERRED);
14452            } else if ("preferred-xml".equals(cmd)) {
14453                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14454                if (opti < args.length && "--full".equals(args[opti])) {
14455                    fullPreferred = true;
14456                    opti++;
14457                }
14458            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14459                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14460            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14461                dumpState.setDump(DumpState.DUMP_PACKAGES);
14462            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14463                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14464            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14465                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14466            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14467                dumpState.setDump(DumpState.DUMP_MESSAGES);
14468            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14469                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14470            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14471                    || "intent-filter-verifiers".equals(cmd)) {
14472                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14473            } else if ("version".equals(cmd)) {
14474                dumpState.setDump(DumpState.DUMP_VERSION);
14475            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14476                dumpState.setDump(DumpState.DUMP_KEYSETS);
14477            } else if ("installs".equals(cmd)) {
14478                dumpState.setDump(DumpState.DUMP_INSTALLS);
14479            } else if ("write".equals(cmd)) {
14480                synchronized (mPackages) {
14481                    mSettings.writeLPr();
14482                    pw.println("Settings written.");
14483                    return;
14484                }
14485            }
14486        }
14487
14488        if (checkin) {
14489            pw.println("vers,1");
14490        }
14491
14492        // reader
14493        synchronized (mPackages) {
14494            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14495                if (!checkin) {
14496                    if (dumpState.onTitlePrinted())
14497                        pw.println();
14498                    pw.println("Database versions:");
14499                    pw.print("  SDK Version:");
14500                    pw.print(" internal=");
14501                    pw.print(mSettings.mInternalSdkPlatform);
14502                    pw.print(" external=");
14503                    pw.println(mSettings.mExternalSdkPlatform);
14504                    pw.print("  DB Version:");
14505                    pw.print(" internal=");
14506                    pw.print(mSettings.mInternalDatabaseVersion);
14507                    pw.print(" external=");
14508                    pw.println(mSettings.mExternalDatabaseVersion);
14509                }
14510            }
14511
14512            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14513                if (!checkin) {
14514                    if (dumpState.onTitlePrinted())
14515                        pw.println();
14516                    pw.println("Verifiers:");
14517                    pw.print("  Required: ");
14518                    pw.print(mRequiredVerifierPackage);
14519                    pw.print(" (uid=");
14520                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14521                    pw.println(")");
14522                } else if (mRequiredVerifierPackage != null) {
14523                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14524                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14525                }
14526            }
14527
14528            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14529                    packageName == null) {
14530                if (mIntentFilterVerifierComponent != null) {
14531                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14532                    if (!checkin) {
14533                        if (dumpState.onTitlePrinted())
14534                            pw.println();
14535                        pw.println("Intent Filter Verifier:");
14536                        pw.print("  Using: ");
14537                        pw.print(verifierPackageName);
14538                        pw.print(" (uid=");
14539                        pw.print(getPackageUid(verifierPackageName, 0));
14540                        pw.println(")");
14541                    } else if (verifierPackageName != null) {
14542                        pw.print("ifv,"); pw.print(verifierPackageName);
14543                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14544                    }
14545                } else {
14546                    pw.println();
14547                    pw.println("No Intent Filter Verifier available!");
14548                }
14549            }
14550
14551            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14552                boolean printedHeader = false;
14553                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14554                while (it.hasNext()) {
14555                    String name = it.next();
14556                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14557                    if (!checkin) {
14558                        if (!printedHeader) {
14559                            if (dumpState.onTitlePrinted())
14560                                pw.println();
14561                            pw.println("Libraries:");
14562                            printedHeader = true;
14563                        }
14564                        pw.print("  ");
14565                    } else {
14566                        pw.print("lib,");
14567                    }
14568                    pw.print(name);
14569                    if (!checkin) {
14570                        pw.print(" -> ");
14571                    }
14572                    if (ent.path != null) {
14573                        if (!checkin) {
14574                            pw.print("(jar) ");
14575                            pw.print(ent.path);
14576                        } else {
14577                            pw.print(",jar,");
14578                            pw.print(ent.path);
14579                        }
14580                    } else {
14581                        if (!checkin) {
14582                            pw.print("(apk) ");
14583                            pw.print(ent.apk);
14584                        } else {
14585                            pw.print(",apk,");
14586                            pw.print(ent.apk);
14587                        }
14588                    }
14589                    pw.println();
14590                }
14591            }
14592
14593            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14594                if (dumpState.onTitlePrinted())
14595                    pw.println();
14596                if (!checkin) {
14597                    pw.println("Features:");
14598                }
14599                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14600                while (it.hasNext()) {
14601                    String name = it.next();
14602                    if (!checkin) {
14603                        pw.print("  ");
14604                    } else {
14605                        pw.print("feat,");
14606                    }
14607                    pw.println(name);
14608                }
14609            }
14610
14611            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14612                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14613                        : "Activity Resolver Table:", "  ", packageName,
14614                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14615                    dumpState.setTitlePrinted(true);
14616                }
14617                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14618                        : "Receiver Resolver Table:", "  ", packageName,
14619                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14620                    dumpState.setTitlePrinted(true);
14621                }
14622                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14623                        : "Service Resolver Table:", "  ", packageName,
14624                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14625                    dumpState.setTitlePrinted(true);
14626                }
14627                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14628                        : "Provider Resolver Table:", "  ", packageName,
14629                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14630                    dumpState.setTitlePrinted(true);
14631                }
14632            }
14633
14634            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14635                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14636                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14637                    int user = mSettings.mPreferredActivities.keyAt(i);
14638                    if (pir.dump(pw,
14639                            dumpState.getTitlePrinted()
14640                                ? "\nPreferred Activities User " + user + ":"
14641                                : "Preferred Activities User " + user + ":", "  ",
14642                            packageName, true, false)) {
14643                        dumpState.setTitlePrinted(true);
14644                    }
14645                }
14646            }
14647
14648            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14649                pw.flush();
14650                FileOutputStream fout = new FileOutputStream(fd);
14651                BufferedOutputStream str = new BufferedOutputStream(fout);
14652                XmlSerializer serializer = new FastXmlSerializer();
14653                try {
14654                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14655                    serializer.startDocument(null, true);
14656                    serializer.setFeature(
14657                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14658                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14659                    serializer.endDocument();
14660                    serializer.flush();
14661                } catch (IllegalArgumentException e) {
14662                    pw.println("Failed writing: " + e);
14663                } catch (IllegalStateException e) {
14664                    pw.println("Failed writing: " + e);
14665                } catch (IOException e) {
14666                    pw.println("Failed writing: " + e);
14667                }
14668            }
14669
14670            if (!checkin
14671                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14672                    && packageName == null) {
14673                pw.println();
14674                int count = mSettings.mPackages.size();
14675                if (count == 0) {
14676                    pw.println("No domain preferred apps!");
14677                    pw.println();
14678                } else {
14679                    final String prefix = "  ";
14680                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14681                    if (allPackageSettings.size() == 0) {
14682                        pw.println("No domain preferred apps!");
14683                        pw.println();
14684                    } else {
14685                        pw.println("Domain preferred apps status:");
14686                        pw.println();
14687                        count = 0;
14688                        for (PackageSetting ps : allPackageSettings) {
14689                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14690                            if (ivi == null || ivi.getPackageName() == null) continue;
14691                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14692                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14693                            pw.println(prefix + "Status: " + ivi.getStatusString());
14694                            pw.println();
14695                            count++;
14696                        }
14697                        if (count == 0) {
14698                            pw.println(prefix + "No domain preferred app status!");
14699                            pw.println();
14700                        }
14701                        for (int userId : sUserManager.getUserIds()) {
14702                            pw.println("Domain preferred apps for User " + userId + ":");
14703                            pw.println();
14704                            count = 0;
14705                            for (PackageSetting ps : allPackageSettings) {
14706                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14707                                if (ivi == null || ivi.getPackageName() == null) {
14708                                    continue;
14709                                }
14710                                final int status = ps.getDomainVerificationStatusForUser(userId);
14711                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14712                                    continue;
14713                                }
14714                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14715                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14716                                String statusStr = IntentFilterVerificationInfo.
14717                                        getStatusStringFromValue(status);
14718                                pw.println(prefix + "Status: " + statusStr);
14719                                pw.println();
14720                                count++;
14721                            }
14722                            if (count == 0) {
14723                                pw.println(prefix + "No domain preferred apps!");
14724                                pw.println();
14725                            }
14726                        }
14727                    }
14728                }
14729            }
14730
14731            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14732                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14733                if (packageName == null && permissionNames == null) {
14734                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14735                        if (iperm == 0) {
14736                            if (dumpState.onTitlePrinted())
14737                                pw.println();
14738                            pw.println("AppOp Permissions:");
14739                        }
14740                        pw.print("  AppOp Permission ");
14741                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14742                        pw.println(":");
14743                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14744                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14745                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14746                        }
14747                    }
14748                }
14749            }
14750
14751            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14752                boolean printedSomething = false;
14753                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14754                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14755                        continue;
14756                    }
14757                    if (!printedSomething) {
14758                        if (dumpState.onTitlePrinted())
14759                            pw.println();
14760                        pw.println("Registered ContentProviders:");
14761                        printedSomething = true;
14762                    }
14763                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14764                    pw.print("    "); pw.println(p.toString());
14765                }
14766                printedSomething = false;
14767                for (Map.Entry<String, PackageParser.Provider> entry :
14768                        mProvidersByAuthority.entrySet()) {
14769                    PackageParser.Provider p = entry.getValue();
14770                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14771                        continue;
14772                    }
14773                    if (!printedSomething) {
14774                        if (dumpState.onTitlePrinted())
14775                            pw.println();
14776                        pw.println("ContentProvider Authorities:");
14777                        printedSomething = true;
14778                    }
14779                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14780                    pw.print("    "); pw.println(p.toString());
14781                    if (p.info != null && p.info.applicationInfo != null) {
14782                        final String appInfo = p.info.applicationInfo.toString();
14783                        pw.print("      applicationInfo="); pw.println(appInfo);
14784                    }
14785                }
14786            }
14787
14788            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14789                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14790            }
14791
14792            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14793                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14794            }
14795
14796            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14797                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14798            }
14799
14800            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14801                // XXX should handle packageName != null by dumping only install data that
14802                // the given package is involved with.
14803                if (dumpState.onTitlePrinted()) pw.println();
14804                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14805            }
14806
14807            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14808                if (dumpState.onTitlePrinted()) pw.println();
14809                mSettings.dumpReadMessagesLPr(pw, dumpState);
14810
14811                pw.println();
14812                pw.println("Package warning messages:");
14813                BufferedReader in = null;
14814                String line = null;
14815                try {
14816                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14817                    while ((line = in.readLine()) != null) {
14818                        if (line.contains("ignored: updated version")) continue;
14819                        pw.println(line);
14820                    }
14821                } catch (IOException ignored) {
14822                } finally {
14823                    IoUtils.closeQuietly(in);
14824                }
14825            }
14826
14827            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14828                BufferedReader in = null;
14829                String line = null;
14830                try {
14831                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14832                    while ((line = in.readLine()) != null) {
14833                        if (line.contains("ignored: updated version")) continue;
14834                        pw.print("msg,");
14835                        pw.println(line);
14836                    }
14837                } catch (IOException ignored) {
14838                } finally {
14839                    IoUtils.closeQuietly(in);
14840                }
14841            }
14842        }
14843    }
14844
14845    // ------- apps on sdcard specific code -------
14846    static final boolean DEBUG_SD_INSTALL = false;
14847
14848    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14849
14850    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14851
14852    private boolean mMediaMounted = false;
14853
14854    static String getEncryptKey() {
14855        try {
14856            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14857                    SD_ENCRYPTION_KEYSTORE_NAME);
14858            if (sdEncKey == null) {
14859                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14860                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14861                if (sdEncKey == null) {
14862                    Slog.e(TAG, "Failed to create encryption keys");
14863                    return null;
14864                }
14865            }
14866            return sdEncKey;
14867        } catch (NoSuchAlgorithmException nsae) {
14868            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14869            return null;
14870        } catch (IOException ioe) {
14871            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14872            return null;
14873        }
14874    }
14875
14876    /*
14877     * Update media status on PackageManager.
14878     */
14879    @Override
14880    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14881        int callingUid = Binder.getCallingUid();
14882        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14883            throw new SecurityException("Media status can only be updated by the system");
14884        }
14885        // reader; this apparently protects mMediaMounted, but should probably
14886        // be a different lock in that case.
14887        synchronized (mPackages) {
14888            Log.i(TAG, "Updating external media status from "
14889                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14890                    + (mediaStatus ? "mounted" : "unmounted"));
14891            if (DEBUG_SD_INSTALL)
14892                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14893                        + ", mMediaMounted=" + mMediaMounted);
14894            if (mediaStatus == mMediaMounted) {
14895                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14896                        : 0, -1);
14897                mHandler.sendMessage(msg);
14898                return;
14899            }
14900            mMediaMounted = mediaStatus;
14901        }
14902        // Queue up an async operation since the package installation may take a
14903        // little while.
14904        mHandler.post(new Runnable() {
14905            public void run() {
14906                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14907            }
14908        });
14909    }
14910
14911    /**
14912     * Called by MountService when the initial ASECs to scan are available.
14913     * Should block until all the ASEC containers are finished being scanned.
14914     */
14915    public void scanAvailableAsecs() {
14916        updateExternalMediaStatusInner(true, false, false);
14917        if (mShouldRestoreconData) {
14918            SELinuxMMAC.setRestoreconDone();
14919            mShouldRestoreconData = false;
14920        }
14921    }
14922
14923    /*
14924     * Collect information of applications on external media, map them against
14925     * existing containers and update information based on current mount status.
14926     * Please note that we always have to report status if reportStatus has been
14927     * set to true especially when unloading packages.
14928     */
14929    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14930            boolean externalStorage) {
14931        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14932        int[] uidArr = EmptyArray.INT;
14933
14934        final String[] list = PackageHelper.getSecureContainerList();
14935        if (ArrayUtils.isEmpty(list)) {
14936            Log.i(TAG, "No secure containers found");
14937        } else {
14938            // Process list of secure containers and categorize them
14939            // as active or stale based on their package internal state.
14940
14941            // reader
14942            synchronized (mPackages) {
14943                for (String cid : list) {
14944                    // Leave stages untouched for now; installer service owns them
14945                    if (PackageInstallerService.isStageName(cid)) continue;
14946
14947                    if (DEBUG_SD_INSTALL)
14948                        Log.i(TAG, "Processing container " + cid);
14949                    String pkgName = getAsecPackageName(cid);
14950                    if (pkgName == null) {
14951                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14952                        continue;
14953                    }
14954                    if (DEBUG_SD_INSTALL)
14955                        Log.i(TAG, "Looking for pkg : " + pkgName);
14956
14957                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14958                    if (ps == null) {
14959                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14960                        continue;
14961                    }
14962
14963                    /*
14964                     * Skip packages that are not external if we're unmounting
14965                     * external storage.
14966                     */
14967                    if (externalStorage && !isMounted && !isExternal(ps)) {
14968                        continue;
14969                    }
14970
14971                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14972                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14973                    // The package status is changed only if the code path
14974                    // matches between settings and the container id.
14975                    if (ps.codePathString != null
14976                            && ps.codePathString.startsWith(args.getCodePath())) {
14977                        if (DEBUG_SD_INSTALL) {
14978                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14979                                    + " at code path: " + ps.codePathString);
14980                        }
14981
14982                        // We do have a valid package installed on sdcard
14983                        processCids.put(args, ps.codePathString);
14984                        final int uid = ps.appId;
14985                        if (uid != -1) {
14986                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14987                        }
14988                    } else {
14989                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14990                                + ps.codePathString);
14991                    }
14992                }
14993            }
14994
14995            Arrays.sort(uidArr);
14996        }
14997
14998        // Process packages with valid entries.
14999        if (isMounted) {
15000            if (DEBUG_SD_INSTALL)
15001                Log.i(TAG, "Loading packages");
15002            loadMediaPackages(processCids, uidArr);
15003            startCleaningPackages();
15004            mInstallerService.onSecureContainersAvailable();
15005        } else {
15006            if (DEBUG_SD_INSTALL)
15007                Log.i(TAG, "Unloading packages");
15008            unloadMediaPackages(processCids, uidArr, reportStatus);
15009        }
15010    }
15011
15012    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15013            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15014        final int size = infos.size();
15015        final String[] packageNames = new String[size];
15016        final int[] packageUids = new int[size];
15017        for (int i = 0; i < size; i++) {
15018            final ApplicationInfo info = infos.get(i);
15019            packageNames[i] = info.packageName;
15020            packageUids[i] = info.uid;
15021        }
15022        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15023                finishedReceiver);
15024    }
15025
15026    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15027            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15028        sendResourcesChangedBroadcast(mediaStatus, replacing,
15029                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15030    }
15031
15032    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15033            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15034        int size = pkgList.length;
15035        if (size > 0) {
15036            // Send broadcasts here
15037            Bundle extras = new Bundle();
15038            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15039            if (uidArr != null) {
15040                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15041            }
15042            if (replacing) {
15043                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15044            }
15045            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15046                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15047            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15048        }
15049    }
15050
15051   /*
15052     * Look at potentially valid container ids from processCids If package
15053     * information doesn't match the one on record or package scanning fails,
15054     * the cid is added to list of removeCids. We currently don't delete stale
15055     * containers.
15056     */
15057    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15058        ArrayList<String> pkgList = new ArrayList<String>();
15059        Set<AsecInstallArgs> keys = processCids.keySet();
15060
15061        for (AsecInstallArgs args : keys) {
15062            String codePath = processCids.get(args);
15063            if (DEBUG_SD_INSTALL)
15064                Log.i(TAG, "Loading container : " + args.cid);
15065            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15066            try {
15067                // Make sure there are no container errors first.
15068                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15069                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15070                            + " when installing from sdcard");
15071                    continue;
15072                }
15073                // Check code path here.
15074                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15075                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15076                            + " does not match one in settings " + codePath);
15077                    continue;
15078                }
15079                // Parse package
15080                int parseFlags = mDefParseFlags;
15081                if (args.isExternalAsec()) {
15082                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15083                }
15084                if (args.isFwdLocked()) {
15085                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15086                }
15087
15088                synchronized (mInstallLock) {
15089                    PackageParser.Package pkg = null;
15090                    try {
15091                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15092                    } catch (PackageManagerException e) {
15093                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15094                    }
15095                    // Scan the package
15096                    if (pkg != null) {
15097                        /*
15098                         * TODO why is the lock being held? doPostInstall is
15099                         * called in other places without the lock. This needs
15100                         * to be straightened out.
15101                         */
15102                        // writer
15103                        synchronized (mPackages) {
15104                            retCode = PackageManager.INSTALL_SUCCEEDED;
15105                            pkgList.add(pkg.packageName);
15106                            // Post process args
15107                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15108                                    pkg.applicationInfo.uid);
15109                        }
15110                    } else {
15111                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15112                    }
15113                }
15114
15115            } finally {
15116                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15117                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15118                }
15119            }
15120        }
15121        // writer
15122        synchronized (mPackages) {
15123            // If the platform SDK has changed since the last time we booted,
15124            // we need to re-grant app permission to catch any new ones that
15125            // appear. This is really a hack, and means that apps can in some
15126            // cases get permissions that the user didn't initially explicitly
15127            // allow... it would be nice to have some better way to handle
15128            // this situation.
15129            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15130            if (regrantPermissions)
15131                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15132                        + mSdkVersion + "; regranting permissions for external storage");
15133            mSettings.mExternalSdkPlatform = mSdkVersion;
15134
15135            // Make sure group IDs have been assigned, and any permission
15136            // changes in other apps are accounted for
15137            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15138                    | (regrantPermissions
15139                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15140                            : 0));
15141
15142            mSettings.updateExternalDatabaseVersion();
15143
15144            // can downgrade to reader
15145            // Persist settings
15146            mSettings.writeLPr();
15147        }
15148        // Send a broadcast to let everyone know we are done processing
15149        if (pkgList.size() > 0) {
15150            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15151        }
15152    }
15153
15154   /*
15155     * Utility method to unload a list of specified containers
15156     */
15157    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15158        // Just unmount all valid containers.
15159        for (AsecInstallArgs arg : cidArgs) {
15160            synchronized (mInstallLock) {
15161                arg.doPostDeleteLI(false);
15162           }
15163       }
15164   }
15165
15166    /*
15167     * Unload packages mounted on external media. This involves deleting package
15168     * data from internal structures, sending broadcasts about diabled packages,
15169     * gc'ing to free up references, unmounting all secure containers
15170     * corresponding to packages on external media, and posting a
15171     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15172     * that we always have to post this message if status has been requested no
15173     * matter what.
15174     */
15175    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15176            final boolean reportStatus) {
15177        if (DEBUG_SD_INSTALL)
15178            Log.i(TAG, "unloading media packages");
15179        ArrayList<String> pkgList = new ArrayList<String>();
15180        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15181        final Set<AsecInstallArgs> keys = processCids.keySet();
15182        for (AsecInstallArgs args : keys) {
15183            String pkgName = args.getPackageName();
15184            if (DEBUG_SD_INSTALL)
15185                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15186            // Delete package internally
15187            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15188            synchronized (mInstallLock) {
15189                boolean res = deletePackageLI(pkgName, null, false, null, null,
15190                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15191                if (res) {
15192                    pkgList.add(pkgName);
15193                } else {
15194                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15195                    failedList.add(args);
15196                }
15197            }
15198        }
15199
15200        // reader
15201        synchronized (mPackages) {
15202            // We didn't update the settings after removing each package;
15203            // write them now for all packages.
15204            mSettings.writeLPr();
15205        }
15206
15207        // We have to absolutely send UPDATED_MEDIA_STATUS only
15208        // after confirming that all the receivers processed the ordered
15209        // broadcast when packages get disabled, force a gc to clean things up.
15210        // and unload all the containers.
15211        if (pkgList.size() > 0) {
15212            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15213                    new IIntentReceiver.Stub() {
15214                public void performReceive(Intent intent, int resultCode, String data,
15215                        Bundle extras, boolean ordered, boolean sticky,
15216                        int sendingUser) throws RemoteException {
15217                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15218                            reportStatus ? 1 : 0, 1, keys);
15219                    mHandler.sendMessage(msg);
15220                }
15221            });
15222        } else {
15223            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15224                    keys);
15225            mHandler.sendMessage(msg);
15226        }
15227    }
15228
15229    private void loadPrivatePackages(VolumeInfo vol) {
15230        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15231        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15232        synchronized (mInstallLock) {
15233        synchronized (mPackages) {
15234            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15235            for (PackageSetting ps : packages) {
15236                final PackageParser.Package pkg;
15237                try {
15238                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15239                    loaded.add(pkg.applicationInfo);
15240                } catch (PackageManagerException e) {
15241                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15242                }
15243            }
15244
15245            // TODO: regrant any permissions that changed based since original install
15246
15247            mSettings.writeLPr();
15248        }
15249        }
15250
15251        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15252        sendResourcesChangedBroadcast(true, false, loaded, null);
15253    }
15254
15255    private void unloadPrivatePackages(VolumeInfo vol) {
15256        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15257        synchronized (mInstallLock) {
15258        synchronized (mPackages) {
15259            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15260            for (PackageSetting ps : packages) {
15261                if (ps.pkg == null) continue;
15262
15263                final ApplicationInfo info = ps.pkg.applicationInfo;
15264                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15265                if (deletePackageLI(ps.name, null, false, null, null,
15266                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15267                    unloaded.add(info);
15268                } else {
15269                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15270                }
15271            }
15272
15273            mSettings.writeLPr();
15274        }
15275        }
15276
15277        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15278        sendResourcesChangedBroadcast(false, false, unloaded, null);
15279    }
15280
15281    /**
15282     * Examine all users present on given mounted volume, and destroy data
15283     * belonging to users that are no longer valid, or whose user ID has been
15284     * recycled.
15285     */
15286    private void reconcileUsers(String volumeUuid) {
15287        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15288        if (ArrayUtils.isEmpty(files)) {
15289            Slog.d(TAG, "No users found on " + volumeUuid);
15290            return;
15291        }
15292
15293        for (File file : files) {
15294            if (!file.isDirectory()) continue;
15295
15296            final int userId;
15297            final UserInfo info;
15298            try {
15299                userId = Integer.parseInt(file.getName());
15300                info = sUserManager.getUserInfo(userId);
15301            } catch (NumberFormatException e) {
15302                Slog.w(TAG, "Invalid user directory " + file);
15303                continue;
15304            }
15305
15306            boolean destroyUser = false;
15307            if (info == null) {
15308                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15309                        + " because no matching user was found");
15310                destroyUser = true;
15311            } else {
15312                try {
15313                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15314                } catch (IOException e) {
15315                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15316                            + " because we failed to enforce serial number: " + e);
15317                    destroyUser = true;
15318                }
15319            }
15320
15321            if (destroyUser) {
15322                synchronized (mInstallLock) {
15323                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15324                }
15325            }
15326        }
15327
15328        final UserManager um = mContext.getSystemService(UserManager.class);
15329        for (UserInfo user : um.getUsers()) {
15330            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15331            if (userDir.exists()) continue;
15332
15333            try {
15334                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15335                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15336            } catch (IOException e) {
15337                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15338            }
15339        }
15340    }
15341
15342    /**
15343     * Examine all apps present on given mounted volume, and destroy apps that
15344     * aren't expected, either due to uninstallation or reinstallation on
15345     * another volume.
15346     */
15347    private void reconcileApps(String volumeUuid) {
15348        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15349        if (ArrayUtils.isEmpty(files)) {
15350            Slog.d(TAG, "No apps found on " + volumeUuid);
15351            return;
15352        }
15353
15354        for (File file : files) {
15355            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15356                    && !PackageInstallerService.isStageName(file.getName());
15357            if (!isPackage) {
15358                // Ignore entries which are not packages
15359                continue;
15360            }
15361
15362            boolean destroyApp = false;
15363            String packageName = null;
15364            try {
15365                final PackageLite pkg = PackageParser.parsePackageLite(file,
15366                        PackageParser.PARSE_MUST_BE_APK);
15367                packageName = pkg.packageName;
15368
15369                synchronized (mPackages) {
15370                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15371                    if (ps == null) {
15372                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15373                                + volumeUuid + " because we found no install record");
15374                        destroyApp = true;
15375                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15376                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15377                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15378                        destroyApp = true;
15379                    }
15380                }
15381
15382            } catch (PackageParserException e) {
15383                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15384                destroyApp = true;
15385            }
15386
15387            if (destroyApp) {
15388                synchronized (mInstallLock) {
15389                    if (packageName != null) {
15390                        removeDataDirsLI(volumeUuid, packageName);
15391                    }
15392                    if (file.isDirectory()) {
15393                        mInstaller.rmPackageDir(file.getAbsolutePath());
15394                    } else {
15395                        file.delete();
15396                    }
15397                }
15398            }
15399        }
15400    }
15401
15402    private void unfreezePackage(String packageName) {
15403        synchronized (mPackages) {
15404            final PackageSetting ps = mSettings.mPackages.get(packageName);
15405            if (ps != null) {
15406                ps.frozen = false;
15407            }
15408        }
15409    }
15410
15411    @Override
15412    public int movePackage(final String packageName, final String volumeUuid) {
15413        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15414
15415        final int moveId = mNextMoveId.getAndIncrement();
15416        try {
15417            movePackageInternal(packageName, volumeUuid, moveId);
15418        } catch (PackageManagerException e) {
15419            Slog.w(TAG, "Failed to move " + packageName, e);
15420            mMoveCallbacks.notifyStatusChanged(moveId,
15421                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15422        }
15423        return moveId;
15424    }
15425
15426    private void movePackageInternal(final String packageName, final String volumeUuid,
15427            final int moveId) throws PackageManagerException {
15428        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15429        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15430        final PackageManager pm = mContext.getPackageManager();
15431
15432        final boolean currentAsec;
15433        final String currentVolumeUuid;
15434        final File codeFile;
15435        final String installerPackageName;
15436        final String packageAbiOverride;
15437        final int appId;
15438        final String seinfo;
15439        final String label;
15440
15441        // reader
15442        synchronized (mPackages) {
15443            final PackageParser.Package pkg = mPackages.get(packageName);
15444            final PackageSetting ps = mSettings.mPackages.get(packageName);
15445            if (pkg == null || ps == null) {
15446                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15447            }
15448
15449            if (pkg.applicationInfo.isSystemApp()) {
15450                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15451                        "Cannot move system application");
15452            }
15453
15454            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15455                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15456                        "Package already moved to " + volumeUuid);
15457            }
15458
15459            final File probe = new File(pkg.codePath);
15460            final File probeOat = new File(probe, "oat");
15461            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15462                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15463                        "Move only supported for modern cluster style installs");
15464            }
15465
15466            if (ps.frozen) {
15467                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15468                        "Failed to move already frozen package");
15469            }
15470            ps.frozen = true;
15471
15472            currentAsec = pkg.applicationInfo.isForwardLocked()
15473                    || pkg.applicationInfo.isExternalAsec();
15474            currentVolumeUuid = ps.volumeUuid;
15475            codeFile = new File(pkg.codePath);
15476            installerPackageName = ps.installerPackageName;
15477            packageAbiOverride = ps.cpuAbiOverrideString;
15478            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15479            seinfo = pkg.applicationInfo.seinfo;
15480            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15481        }
15482
15483        // Now that we're guarded by frozen state, kill app during move
15484        killApplication(packageName, appId, "move pkg");
15485
15486        final Bundle extras = new Bundle();
15487        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15488        extras.putString(Intent.EXTRA_TITLE, label);
15489        mMoveCallbacks.notifyCreated(moveId, extras);
15490
15491        int installFlags;
15492        final boolean moveCompleteApp;
15493        final File measurePath;
15494
15495        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15496            installFlags = INSTALL_INTERNAL;
15497            moveCompleteApp = !currentAsec;
15498            measurePath = Environment.getDataAppDirectory(volumeUuid);
15499        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15500            installFlags = INSTALL_EXTERNAL;
15501            moveCompleteApp = false;
15502            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15503        } else {
15504            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15505            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15506                    || !volume.isMountedWritable()) {
15507                unfreezePackage(packageName);
15508                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15509                        "Move location not mounted private volume");
15510            }
15511
15512            Preconditions.checkState(!currentAsec);
15513
15514            installFlags = INSTALL_INTERNAL;
15515            moveCompleteApp = true;
15516            measurePath = Environment.getDataAppDirectory(volumeUuid);
15517        }
15518
15519        final PackageStats stats = new PackageStats(null, -1);
15520        synchronized (mInstaller) {
15521            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15522                unfreezePackage(packageName);
15523                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15524                        "Failed to measure package size");
15525            }
15526        }
15527
15528        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15529                + stats.dataSize);
15530
15531        final long startFreeBytes = measurePath.getFreeSpace();
15532        final long sizeBytes;
15533        if (moveCompleteApp) {
15534            sizeBytes = stats.codeSize + stats.dataSize;
15535        } else {
15536            sizeBytes = stats.codeSize;
15537        }
15538
15539        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15540            unfreezePackage(packageName);
15541            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15542                    "Not enough free space to move");
15543        }
15544
15545        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15546
15547        final CountDownLatch installedLatch = new CountDownLatch(1);
15548        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15549            @Override
15550            public void onUserActionRequired(Intent intent) throws RemoteException {
15551                throw new IllegalStateException();
15552            }
15553
15554            @Override
15555            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15556                    Bundle extras) throws RemoteException {
15557                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15558                        + PackageManager.installStatusToString(returnCode, msg));
15559
15560                installedLatch.countDown();
15561
15562                // Regardless of success or failure of the move operation,
15563                // always unfreeze the package
15564                unfreezePackage(packageName);
15565
15566                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15567                switch (status) {
15568                    case PackageInstaller.STATUS_SUCCESS:
15569                        mMoveCallbacks.notifyStatusChanged(moveId,
15570                                PackageManager.MOVE_SUCCEEDED);
15571                        break;
15572                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15573                        mMoveCallbacks.notifyStatusChanged(moveId,
15574                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15575                        break;
15576                    default:
15577                        mMoveCallbacks.notifyStatusChanged(moveId,
15578                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15579                        break;
15580                }
15581            }
15582        };
15583
15584        final MoveInfo move;
15585        if (moveCompleteApp) {
15586            // Kick off a thread to report progress estimates
15587            new Thread() {
15588                @Override
15589                public void run() {
15590                    while (true) {
15591                        try {
15592                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15593                                break;
15594                            }
15595                        } catch (InterruptedException ignored) {
15596                        }
15597
15598                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15599                        final int progress = 10 + (int) MathUtils.constrain(
15600                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15601                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15602                    }
15603                }
15604            }.start();
15605
15606            final String dataAppName = codeFile.getName();
15607            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15608                    dataAppName, appId, seinfo);
15609        } else {
15610            move = null;
15611        }
15612
15613        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15614
15615        final Message msg = mHandler.obtainMessage(INIT_COPY);
15616        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15617        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15618                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15619        mHandler.sendMessage(msg);
15620    }
15621
15622    @Override
15623    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15624        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15625
15626        final int realMoveId = mNextMoveId.getAndIncrement();
15627        final Bundle extras = new Bundle();
15628        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15629        mMoveCallbacks.notifyCreated(realMoveId, extras);
15630
15631        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15632            @Override
15633            public void onCreated(int moveId, Bundle extras) {
15634                // Ignored
15635            }
15636
15637            @Override
15638            public void onStatusChanged(int moveId, int status, long estMillis) {
15639                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15640            }
15641        };
15642
15643        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15644        storage.setPrimaryStorageUuid(volumeUuid, callback);
15645        return realMoveId;
15646    }
15647
15648    @Override
15649    public int getMoveStatus(int moveId) {
15650        mContext.enforceCallingOrSelfPermission(
15651                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15652        return mMoveCallbacks.mLastStatus.get(moveId);
15653    }
15654
15655    @Override
15656    public void registerMoveCallback(IPackageMoveObserver callback) {
15657        mContext.enforceCallingOrSelfPermission(
15658                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15659        mMoveCallbacks.register(callback);
15660    }
15661
15662    @Override
15663    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15664        mContext.enforceCallingOrSelfPermission(
15665                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15666        mMoveCallbacks.unregister(callback);
15667    }
15668
15669    @Override
15670    public boolean setInstallLocation(int loc) {
15671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15672                null);
15673        if (getInstallLocation() == loc) {
15674            return true;
15675        }
15676        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15677                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15678            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15679                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15680            return true;
15681        }
15682        return false;
15683   }
15684
15685    @Override
15686    public int getInstallLocation() {
15687        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15688                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15689                PackageHelper.APP_INSTALL_AUTO);
15690    }
15691
15692    /** Called by UserManagerService */
15693    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15694        mDirtyUsers.remove(userHandle);
15695        mSettings.removeUserLPw(userHandle);
15696        mPendingBroadcasts.remove(userHandle);
15697        if (mInstaller != null) {
15698            // Technically, we shouldn't be doing this with the package lock
15699            // held.  However, this is very rare, and there is already so much
15700            // other disk I/O going on, that we'll let it slide for now.
15701            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15702            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15703                final String volumeUuid = vol.getFsUuid();
15704                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15705                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15706            }
15707        }
15708        mUserNeedsBadging.delete(userHandle);
15709        removeUnusedPackagesLILPw(userManager, userHandle);
15710    }
15711
15712    /**
15713     * We're removing userHandle and would like to remove any downloaded packages
15714     * that are no longer in use by any other user.
15715     * @param userHandle the user being removed
15716     */
15717    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15718        final boolean DEBUG_CLEAN_APKS = false;
15719        int [] users = userManager.getUserIdsLPr();
15720        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15721        while (psit.hasNext()) {
15722            PackageSetting ps = psit.next();
15723            if (ps.pkg == null) {
15724                continue;
15725            }
15726            final String packageName = ps.pkg.packageName;
15727            // Skip over if system app
15728            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15729                continue;
15730            }
15731            if (DEBUG_CLEAN_APKS) {
15732                Slog.i(TAG, "Checking package " + packageName);
15733            }
15734            boolean keep = false;
15735            for (int i = 0; i < users.length; i++) {
15736                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15737                    keep = true;
15738                    if (DEBUG_CLEAN_APKS) {
15739                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15740                                + users[i]);
15741                    }
15742                    break;
15743                }
15744            }
15745            if (!keep) {
15746                if (DEBUG_CLEAN_APKS) {
15747                    Slog.i(TAG, "  Removing package " + packageName);
15748                }
15749                mHandler.post(new Runnable() {
15750                    public void run() {
15751                        deletePackageX(packageName, userHandle, 0);
15752                    } //end run
15753                });
15754            }
15755        }
15756    }
15757
15758    /** Called by UserManagerService */
15759    void createNewUserLILPw(int userHandle) {
15760        if (mInstaller != null) {
15761            mInstaller.createUserConfig(userHandle);
15762            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15763            applyFactoryDefaultBrowserLPw(userHandle);
15764        }
15765    }
15766
15767    void newUserCreatedLILPw(final int userHandle) {
15768        // We cannot grant the default permissions with a lock held as
15769        // we query providers from other components for default handlers
15770        // such as enabled IMEs, etc.
15771        mHandler.post(new Runnable() {
15772            @Override
15773            public void run() {
15774                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15775            }
15776        });
15777    }
15778
15779    @Override
15780    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15781        mContext.enforceCallingOrSelfPermission(
15782                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15783                "Only package verification agents can read the verifier device identity");
15784
15785        synchronized (mPackages) {
15786            return mSettings.getVerifierDeviceIdentityLPw();
15787        }
15788    }
15789
15790    @Override
15791    public void setPermissionEnforced(String permission, boolean enforced) {
15792        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15793        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15794            synchronized (mPackages) {
15795                if (mSettings.mReadExternalStorageEnforced == null
15796                        || mSettings.mReadExternalStorageEnforced != enforced) {
15797                    mSettings.mReadExternalStorageEnforced = enforced;
15798                    mSettings.writeLPr();
15799                }
15800            }
15801            // kill any non-foreground processes so we restart them and
15802            // grant/revoke the GID.
15803            final IActivityManager am = ActivityManagerNative.getDefault();
15804            if (am != null) {
15805                final long token = Binder.clearCallingIdentity();
15806                try {
15807                    am.killProcessesBelowForeground("setPermissionEnforcement");
15808                } catch (RemoteException e) {
15809                } finally {
15810                    Binder.restoreCallingIdentity(token);
15811                }
15812            }
15813        } else {
15814            throw new IllegalArgumentException("No selective enforcement for " + permission);
15815        }
15816    }
15817
15818    @Override
15819    @Deprecated
15820    public boolean isPermissionEnforced(String permission) {
15821        return true;
15822    }
15823
15824    @Override
15825    public boolean isStorageLow() {
15826        final long token = Binder.clearCallingIdentity();
15827        try {
15828            final DeviceStorageMonitorInternal
15829                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15830            if (dsm != null) {
15831                return dsm.isMemoryLow();
15832            } else {
15833                return false;
15834            }
15835        } finally {
15836            Binder.restoreCallingIdentity(token);
15837        }
15838    }
15839
15840    @Override
15841    public IPackageInstaller getPackageInstaller() {
15842        return mInstallerService;
15843    }
15844
15845    private boolean userNeedsBadging(int userId) {
15846        int index = mUserNeedsBadging.indexOfKey(userId);
15847        if (index < 0) {
15848            final UserInfo userInfo;
15849            final long token = Binder.clearCallingIdentity();
15850            try {
15851                userInfo = sUserManager.getUserInfo(userId);
15852            } finally {
15853                Binder.restoreCallingIdentity(token);
15854            }
15855            final boolean b;
15856            if (userInfo != null && userInfo.isManagedProfile()) {
15857                b = true;
15858            } else {
15859                b = false;
15860            }
15861            mUserNeedsBadging.put(userId, b);
15862            return b;
15863        }
15864        return mUserNeedsBadging.valueAt(index);
15865    }
15866
15867    @Override
15868    public KeySet getKeySetByAlias(String packageName, String alias) {
15869        if (packageName == null || alias == null) {
15870            return null;
15871        }
15872        synchronized(mPackages) {
15873            final PackageParser.Package pkg = mPackages.get(packageName);
15874            if (pkg == null) {
15875                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15876                throw new IllegalArgumentException("Unknown package: " + packageName);
15877            }
15878            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15879            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15880        }
15881    }
15882
15883    @Override
15884    public KeySet getSigningKeySet(String packageName) {
15885        if (packageName == null) {
15886            return null;
15887        }
15888        synchronized(mPackages) {
15889            final PackageParser.Package pkg = mPackages.get(packageName);
15890            if (pkg == null) {
15891                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15892                throw new IllegalArgumentException("Unknown package: " + packageName);
15893            }
15894            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15895                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15896                throw new SecurityException("May not access signing KeySet of other apps.");
15897            }
15898            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15899            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15900        }
15901    }
15902
15903    @Override
15904    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15905        if (packageName == null || ks == null) {
15906            return false;
15907        }
15908        synchronized(mPackages) {
15909            final PackageParser.Package pkg = mPackages.get(packageName);
15910            if (pkg == null) {
15911                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15912                throw new IllegalArgumentException("Unknown package: " + packageName);
15913            }
15914            IBinder ksh = ks.getToken();
15915            if (ksh instanceof KeySetHandle) {
15916                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15917                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15918            }
15919            return false;
15920        }
15921    }
15922
15923    @Override
15924    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15925        if (packageName == null || ks == null) {
15926            return false;
15927        }
15928        synchronized(mPackages) {
15929            final PackageParser.Package pkg = mPackages.get(packageName);
15930            if (pkg == null) {
15931                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15932                throw new IllegalArgumentException("Unknown package: " + packageName);
15933            }
15934            IBinder ksh = ks.getToken();
15935            if (ksh instanceof KeySetHandle) {
15936                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15937                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15938            }
15939            return false;
15940        }
15941    }
15942
15943    public void getUsageStatsIfNoPackageUsageInfo() {
15944        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15945            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15946            if (usm == null) {
15947                throw new IllegalStateException("UsageStatsManager must be initialized");
15948            }
15949            long now = System.currentTimeMillis();
15950            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15951            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15952                String packageName = entry.getKey();
15953                PackageParser.Package pkg = mPackages.get(packageName);
15954                if (pkg == null) {
15955                    continue;
15956                }
15957                UsageStats usage = entry.getValue();
15958                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15959                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15960            }
15961        }
15962    }
15963
15964    /**
15965     * Check and throw if the given before/after packages would be considered a
15966     * downgrade.
15967     */
15968    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15969            throws PackageManagerException {
15970        if (after.versionCode < before.mVersionCode) {
15971            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15972                    "Update version code " + after.versionCode + " is older than current "
15973                    + before.mVersionCode);
15974        } else if (after.versionCode == before.mVersionCode) {
15975            if (after.baseRevisionCode < before.baseRevisionCode) {
15976                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15977                        "Update base revision code " + after.baseRevisionCode
15978                        + " is older than current " + before.baseRevisionCode);
15979            }
15980
15981            if (!ArrayUtils.isEmpty(after.splitNames)) {
15982                for (int i = 0; i < after.splitNames.length; i++) {
15983                    final String splitName = after.splitNames[i];
15984                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15985                    if (j != -1) {
15986                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15987                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15988                                    "Update split " + splitName + " revision code "
15989                                    + after.splitRevisionCodes[i] + " is older than current "
15990                                    + before.splitRevisionCodes[j]);
15991                        }
15992                    }
15993                }
15994            }
15995        }
15996    }
15997
15998    private static class MoveCallbacks extends Handler {
15999        private static final int MSG_CREATED = 1;
16000        private static final int MSG_STATUS_CHANGED = 2;
16001
16002        private final RemoteCallbackList<IPackageMoveObserver>
16003                mCallbacks = new RemoteCallbackList<>();
16004
16005        private final SparseIntArray mLastStatus = new SparseIntArray();
16006
16007        public MoveCallbacks(Looper looper) {
16008            super(looper);
16009        }
16010
16011        public void register(IPackageMoveObserver callback) {
16012            mCallbacks.register(callback);
16013        }
16014
16015        public void unregister(IPackageMoveObserver callback) {
16016            mCallbacks.unregister(callback);
16017        }
16018
16019        @Override
16020        public void handleMessage(Message msg) {
16021            final SomeArgs args = (SomeArgs) msg.obj;
16022            final int n = mCallbacks.beginBroadcast();
16023            for (int i = 0; i < n; i++) {
16024                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16025                try {
16026                    invokeCallback(callback, msg.what, args);
16027                } catch (RemoteException ignored) {
16028                }
16029            }
16030            mCallbacks.finishBroadcast();
16031            args.recycle();
16032        }
16033
16034        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16035                throws RemoteException {
16036            switch (what) {
16037                case MSG_CREATED: {
16038                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16039                    break;
16040                }
16041                case MSG_STATUS_CHANGED: {
16042                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16043                    break;
16044                }
16045            }
16046        }
16047
16048        private void notifyCreated(int moveId, Bundle extras) {
16049            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16050
16051            final SomeArgs args = SomeArgs.obtain();
16052            args.argi1 = moveId;
16053            args.arg2 = extras;
16054            obtainMessage(MSG_CREATED, args).sendToTarget();
16055        }
16056
16057        private void notifyStatusChanged(int moveId, int status) {
16058            notifyStatusChanged(moveId, status, -1);
16059        }
16060
16061        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16062            Slog.v(TAG, "Move " + moveId + " status " + status);
16063
16064            final SomeArgs args = SomeArgs.obtain();
16065            args.argi1 = moveId;
16066            args.argi2 = status;
16067            args.arg3 = estMillis;
16068            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16069
16070            synchronized (mLastStatus) {
16071                mLastStatus.put(moveId, status);
16072            }
16073        }
16074    }
16075
16076    private final class OnPermissionChangeListeners extends Handler {
16077        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16078
16079        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16080                new RemoteCallbackList<>();
16081
16082        public OnPermissionChangeListeners(Looper looper) {
16083            super(looper);
16084        }
16085
16086        @Override
16087        public void handleMessage(Message msg) {
16088            switch (msg.what) {
16089                case MSG_ON_PERMISSIONS_CHANGED: {
16090                    final int uid = msg.arg1;
16091                    handleOnPermissionsChanged(uid);
16092                } break;
16093            }
16094        }
16095
16096        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16097            mPermissionListeners.register(listener);
16098
16099        }
16100
16101        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16102            mPermissionListeners.unregister(listener);
16103        }
16104
16105        public void onPermissionsChanged(int uid) {
16106            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16107                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16108            }
16109        }
16110
16111        private void handleOnPermissionsChanged(int uid) {
16112            final int count = mPermissionListeners.beginBroadcast();
16113            try {
16114                for (int i = 0; i < count; i++) {
16115                    IOnPermissionsChangeListener callback = mPermissionListeners
16116                            .getBroadcastItem(i);
16117                    try {
16118                        callback.onPermissionsChanged(uid);
16119                    } catch (RemoteException e) {
16120                        Log.e(TAG, "Permission listener is dead", e);
16121                    }
16122                }
16123            } finally {
16124                mPermissionListeners.finishBroadcast();
16125            }
16126        }
16127    }
16128
16129    private class PackageManagerInternalImpl extends PackageManagerInternal {
16130        @Override
16131        public void setLocationPackagesProvider(PackagesProvider provider) {
16132            synchronized (mPackages) {
16133                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16134            }
16135        }
16136
16137        @Override
16138        public void setImePackagesProvider(PackagesProvider provider) {
16139            synchronized (mPackages) {
16140                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16141            }
16142        }
16143
16144        @Override
16145        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16146            synchronized (mPackages) {
16147                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16148            }
16149        }
16150
16151        @Override
16152        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16153            synchronized (mPackages) {
16154                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16155            }
16156        }
16157
16158        @Override
16159        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16160            synchronized (mPackages) {
16161                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16162            }
16163        }
16164
16165        @Override
16166        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16167            synchronized (mPackages) {
16168                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16169            }
16170        }
16171
16172        @Override
16173        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16174            synchronized (mPackages) {
16175                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16176                        packageName, userId);
16177            }
16178        }
16179
16180        @Override
16181        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16182            synchronized (mPackages) {
16183                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16184                        packageName, userId);
16185            }
16186        }
16187    }
16188
16189    @Override
16190    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16191        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16192        synchronized (mPackages) {
16193            final long identity = Binder.clearCallingIdentity();
16194            try {
16195                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16196                        packageNames, userId);
16197            } finally {
16198                Binder.restoreCallingIdentity(identity);
16199            }
16200        }
16201    }
16202
16203    private static void enforceSystemOrPhoneCaller(String tag) {
16204        int callingUid = Binder.getCallingUid();
16205        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16206            throw new SecurityException(
16207                    "Cannot call " + tag + " from UID " + callingUid);
16208        }
16209    }
16210}
16211