PackageManagerService.java revision 4e5dac3d6ef6f28aecb116b8dfd92ff31d49c926
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    final String mRequiredVerifierPackage;
930    final String mRequiredInstallerPackage;
931
932    private final PackageUsage mPackageUsage = new PackageUsage();
933
934    private class PackageUsage {
935        private static final int WRITE_INTERVAL
936            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
937
938        private final Object mFileLock = new Object();
939        private final AtomicLong mLastWritten = new AtomicLong(0);
940        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
941
942        private boolean mIsHistoricalPackageUsageAvailable = true;
943
944        boolean isHistoricalPackageUsageAvailable() {
945            return mIsHistoricalPackageUsageAvailable;
946        }
947
948        void write(boolean force) {
949            if (force) {
950                writeInternal();
951                return;
952            }
953            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
954                && !DEBUG_DEXOPT) {
955                return;
956            }
957            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
958                new Thread("PackageUsage_DiskWriter") {
959                    @Override
960                    public void run() {
961                        try {
962                            writeInternal();
963                        } finally {
964                            mBackgroundWriteRunning.set(false);
965                        }
966                    }
967                }.start();
968            }
969        }
970
971        private void writeInternal() {
972            synchronized (mPackages) {
973                synchronized (mFileLock) {
974                    AtomicFile file = getFile();
975                    FileOutputStream f = null;
976                    try {
977                        f = file.startWrite();
978                        BufferedOutputStream out = new BufferedOutputStream(f);
979                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
980                        StringBuilder sb = new StringBuilder();
981                        for (PackageParser.Package pkg : mPackages.values()) {
982                            if (pkg.mLastPackageUsageTimeInMills == 0) {
983                                continue;
984                            }
985                            sb.setLength(0);
986                            sb.append(pkg.packageName);
987                            sb.append(' ');
988                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
989                            sb.append('\n');
990                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
991                        }
992                        out.flush();
993                        file.finishWrite(f);
994                    } catch (IOException e) {
995                        if (f != null) {
996                            file.failWrite(f);
997                        }
998                        Log.e(TAG, "Failed to write package usage times", e);
999                    }
1000                }
1001            }
1002            mLastWritten.set(SystemClock.elapsedRealtime());
1003        }
1004
1005        void readLP() {
1006            synchronized (mFileLock) {
1007                AtomicFile file = getFile();
1008                BufferedInputStream in = null;
1009                try {
1010                    in = new BufferedInputStream(file.openRead());
1011                    StringBuffer sb = new StringBuffer();
1012                    while (true) {
1013                        String packageName = readToken(in, sb, ' ');
1014                        if (packageName == null) {
1015                            break;
1016                        }
1017                        String timeInMillisString = readToken(in, sb, '\n');
1018                        if (timeInMillisString == null) {
1019                            throw new IOException("Failed to find last usage time for package "
1020                                                  + packageName);
1021                        }
1022                        PackageParser.Package pkg = mPackages.get(packageName);
1023                        if (pkg == null) {
1024                            continue;
1025                        }
1026                        long timeInMillis;
1027                        try {
1028                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1029                        } catch (NumberFormatException e) {
1030                            throw new IOException("Failed to parse " + timeInMillisString
1031                                                  + " as a long.", e);
1032                        }
1033                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1034                    }
1035                } catch (FileNotFoundException expected) {
1036                    mIsHistoricalPackageUsageAvailable = false;
1037                } catch (IOException e) {
1038                    Log.w(TAG, "Failed to read package usage times", e);
1039                } finally {
1040                    IoUtils.closeQuietly(in);
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1047                throws IOException {
1048            sb.setLength(0);
1049            while (true) {
1050                int ch = in.read();
1051                if (ch == -1) {
1052                    if (sb.length() == 0) {
1053                        return null;
1054                    }
1055                    throw new IOException("Unexpected EOF");
1056                }
1057                if (ch == endOfToken) {
1058                    return sb.toString();
1059                }
1060                sb.append((char)ch);
1061            }
1062        }
1063
1064        private AtomicFile getFile() {
1065            File dataDir = Environment.getDataDirectory();
1066            File systemDir = new File(dataDir, "system");
1067            File fname = new File(systemDir, "package-usage.list");
1068            return new AtomicFile(fname);
1069        }
1070    }
1071
1072    class PackageHandler extends Handler {
1073        private boolean mBound = false;
1074        final ArrayList<HandlerParams> mPendingInstalls =
1075            new ArrayList<HandlerParams>();
1076
1077        private boolean connectToService() {
1078            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1079                    " DefaultContainerService");
1080            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1081            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1082            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1083                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1084                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1085                mBound = true;
1086                return true;
1087            }
1088            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1089            return false;
1090        }
1091
1092        private void disconnectService() {
1093            mContainerService = null;
1094            mBound = false;
1095            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1096            mContext.unbindService(mDefContainerConn);
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1098        }
1099
1100        PackageHandler(Looper looper) {
1101            super(looper);
1102        }
1103
1104        public void handleMessage(Message msg) {
1105            try {
1106                doHandleMessage(msg);
1107            } finally {
1108                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1109            }
1110        }
1111
1112        void doHandleMessage(Message msg) {
1113            switch (msg.what) {
1114                case INIT_COPY: {
1115                    HandlerParams params = (HandlerParams) msg.obj;
1116                    int idx = mPendingInstalls.size();
1117                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1118                    // If a bind was already initiated we dont really
1119                    // need to do anything. The pending install
1120                    // will be processed later on.
1121                    if (!mBound) {
1122                        // If this is the only one pending we might
1123                        // have to bind to the service again.
1124                        if (!connectToService()) {
1125                            Slog.e(TAG, "Failed to bind to media container service");
1126                            params.serviceError();
1127                            return;
1128                        } else {
1129                            // Once we bind to the service, the first
1130                            // pending request will be processed.
1131                            mPendingInstalls.add(idx, params);
1132                        }
1133                    } else {
1134                        mPendingInstalls.add(idx, params);
1135                        // Already bound to the service. Just make
1136                        // sure we trigger off processing the first request.
1137                        if (idx == 0) {
1138                            mHandler.sendEmptyMessage(MCS_BOUND);
1139                        }
1140                    }
1141                    break;
1142                }
1143                case MCS_BOUND: {
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1145                    if (msg.obj != null) {
1146                        mContainerService = (IMediaContainerService) msg.obj;
1147                    }
1148                    if (mContainerService == null) {
1149                        if (!mBound) {
1150                            // Something seriously wrong since we are not bound and we are not
1151                            // waiting for connection. Bail out.
1152                            Slog.e(TAG, "Cannot bind to media container service");
1153                            for (HandlerParams params : mPendingInstalls) {
1154                                // Indicate service bind error
1155                                params.serviceError();
1156                            }
1157                            mPendingInstalls.clear();
1158                        } else {
1159                            Slog.w(TAG, "Waiting to connect to media container service");
1160                        }
1161                    } else if (mPendingInstalls.size() > 0) {
1162                        HandlerParams params = mPendingInstalls.get(0);
1163                        if (params != null) {
1164                            if (params.startCopy()) {
1165                                // We are done...  look for more work or to
1166                                // go idle.
1167                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1168                                        "Checking for more work or unbind...");
1169                                // Delete pending install
1170                                if (mPendingInstalls.size() > 0) {
1171                                    mPendingInstalls.remove(0);
1172                                }
1173                                if (mPendingInstalls.size() == 0) {
1174                                    if (mBound) {
1175                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1176                                                "Posting delayed MCS_UNBIND");
1177                                        removeMessages(MCS_UNBIND);
1178                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1179                                        // Unbind after a little delay, to avoid
1180                                        // continual thrashing.
1181                                        sendMessageDelayed(ubmsg, 10000);
1182                                    }
1183                                } else {
1184                                    // There are more pending requests in queue.
1185                                    // Just post MCS_BOUND message to trigger processing
1186                                    // of next pending install.
1187                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1188                                            "Posting MCS_BOUND for next work");
1189                                    mHandler.sendEmptyMessage(MCS_BOUND);
1190                                }
1191                            }
1192                        }
1193                    } else {
1194                        // Should never happen ideally.
1195                        Slog.w(TAG, "Empty queue");
1196                    }
1197                    break;
1198                }
1199                case MCS_RECONNECT: {
1200                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1201                    if (mPendingInstalls.size() > 0) {
1202                        if (mBound) {
1203                            disconnectService();
1204                        }
1205                        if (!connectToService()) {
1206                            Slog.e(TAG, "Failed to bind to media container service");
1207                            for (HandlerParams params : mPendingInstalls) {
1208                                // Indicate service bind error
1209                                params.serviceError();
1210                            }
1211                            mPendingInstalls.clear();
1212                        }
1213                    }
1214                    break;
1215                }
1216                case MCS_UNBIND: {
1217                    // If there is no actual work left, then time to unbind.
1218                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1219
1220                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1221                        if (mBound) {
1222                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1223
1224                            disconnectService();
1225                        }
1226                    } else if (mPendingInstalls.size() > 0) {
1227                        // There are more pending requests in queue.
1228                        // Just post MCS_BOUND message to trigger processing
1229                        // of next pending install.
1230                        mHandler.sendEmptyMessage(MCS_BOUND);
1231                    }
1232
1233                    break;
1234                }
1235                case MCS_GIVE_UP: {
1236                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1237                    mPendingInstalls.remove(0);
1238                    break;
1239                }
1240                case SEND_PENDING_BROADCAST: {
1241                    String packages[];
1242                    ArrayList<String> components[];
1243                    int size = 0;
1244                    int uids[];
1245                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1246                    synchronized (mPackages) {
1247                        if (mPendingBroadcasts == null) {
1248                            return;
1249                        }
1250                        size = mPendingBroadcasts.size();
1251                        if (size <= 0) {
1252                            // Nothing to be done. Just return
1253                            return;
1254                        }
1255                        packages = new String[size];
1256                        components = new ArrayList[size];
1257                        uids = new int[size];
1258                        int i = 0;  // filling out the above arrays
1259
1260                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1261                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1262                            Iterator<Map.Entry<String, ArrayList<String>>> it
1263                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1264                                            .entrySet().iterator();
1265                            while (it.hasNext() && i < size) {
1266                                Map.Entry<String, ArrayList<String>> ent = it.next();
1267                                packages[i] = ent.getKey();
1268                                components[i] = ent.getValue();
1269                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1270                                uids[i] = (ps != null)
1271                                        ? UserHandle.getUid(packageUserId, ps.appId)
1272                                        : -1;
1273                                i++;
1274                            }
1275                        }
1276                        size = i;
1277                        mPendingBroadcasts.clear();
1278                    }
1279                    // Send broadcasts
1280                    for (int i = 0; i < size; i++) {
1281                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1282                    }
1283                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1284                    break;
1285                }
1286                case START_CLEANING_PACKAGE: {
1287                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1288                    final String packageName = (String)msg.obj;
1289                    final int userId = msg.arg1;
1290                    final boolean andCode = msg.arg2 != 0;
1291                    synchronized (mPackages) {
1292                        if (userId == UserHandle.USER_ALL) {
1293                            int[] users = sUserManager.getUserIds();
1294                            for (int user : users) {
1295                                mSettings.addPackageToCleanLPw(
1296                                        new PackageCleanItem(user, packageName, andCode));
1297                            }
1298                        } else {
1299                            mSettings.addPackageToCleanLPw(
1300                                    new PackageCleanItem(userId, packageName, andCode));
1301                        }
1302                    }
1303                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1304                    startCleaningPackages();
1305                } break;
1306                case POST_INSTALL: {
1307                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1308                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1309                    mRunningInstalls.delete(msg.arg1);
1310                    boolean deleteOld = false;
1311
1312                    if (data != null) {
1313                        InstallArgs args = data.args;
1314                        PackageInstalledInfo res = data.res;
1315
1316                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1317                            final String packageName = res.pkg.applicationInfo.packageName;
1318                            res.removedInfo.sendBroadcast(false, true, false);
1319                            Bundle extras = new Bundle(1);
1320                            extras.putInt(Intent.EXTRA_UID, res.uid);
1321
1322                            // Now that we successfully installed the package, grant runtime
1323                            // permissions if requested before broadcasting the install.
1324                            if ((args.installFlags
1325                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1326                                grantRequestedRuntimePermissions(res.pkg,
1327                                        args.user.getIdentifier());
1328                            }
1329
1330                            // Determine the set of users who are adding this
1331                            // package for the first time vs. those who are seeing
1332                            // an update.
1333                            int[] firstUsers;
1334                            int[] updateUsers = new int[0];
1335                            if (res.origUsers == null || res.origUsers.length == 0) {
1336                                firstUsers = res.newUsers;
1337                            } else {
1338                                firstUsers = new int[0];
1339                                for (int i=0; i<res.newUsers.length; i++) {
1340                                    int user = res.newUsers[i];
1341                                    boolean isNew = true;
1342                                    for (int j=0; j<res.origUsers.length; j++) {
1343                                        if (res.origUsers[j] == user) {
1344                                            isNew = false;
1345                                            break;
1346                                        }
1347                                    }
1348                                    if (isNew) {
1349                                        int[] newFirst = new int[firstUsers.length+1];
1350                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1351                                                firstUsers.length);
1352                                        newFirst[firstUsers.length] = user;
1353                                        firstUsers = newFirst;
1354                                    } else {
1355                                        int[] newUpdate = new int[updateUsers.length+1];
1356                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1357                                                updateUsers.length);
1358                                        newUpdate[updateUsers.length] = user;
1359                                        updateUsers = newUpdate;
1360                                    }
1361                                }
1362                            }
1363                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1364                                    packageName, extras, null, null, firstUsers);
1365                            final boolean update = res.removedInfo.removedPackage != null;
1366                            if (update) {
1367                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1368                            }
1369                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1370                                    packageName, extras, null, null, updateUsers);
1371                            if (update) {
1372                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1373                                        packageName, extras, null, null, updateUsers);
1374                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1375                                        null, null, packageName, null, updateUsers);
1376
1377                                // treat asec-hosted packages like removable media on upgrade
1378                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1379                                    if (DEBUG_INSTALL) {
1380                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1381                                                + " is ASEC-hosted -> AVAILABLE");
1382                                    }
1383                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1384                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1385                                    pkgList.add(packageName);
1386                                    sendResourcesChangedBroadcast(true, true,
1387                                            pkgList,uidArray, null);
1388                                }
1389                            }
1390                            if (res.removedInfo.args != null) {
1391                                // Remove the replaced package's older resources safely now
1392                                deleteOld = true;
1393                            }
1394
1395                            // If this app is a browser and it's newly-installed for some
1396                            // users, clear any default-browser state in those users
1397                            if (firstUsers.length > 0) {
1398                                // the app's nature doesn't depend on the user, so we can just
1399                                // check its browser nature in any user and generalize.
1400                                if (packageIsBrowser(packageName, firstUsers[0])) {
1401                                    synchronized (mPackages) {
1402                                        for (int userId : firstUsers) {
1403                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1404                                        }
1405                                    }
1406                                }
1407                            }
1408                            // Log current value of "unknown sources" setting
1409                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1410                                getUnknownSourcesSettings());
1411                        }
1412                        // Force a gc to clear up things
1413                        Runtime.getRuntime().gc();
1414                        // We delete after a gc for applications  on sdcard.
1415                        if (deleteOld) {
1416                            synchronized (mInstallLock) {
1417                                res.removedInfo.args.doPostDeleteLI(true);
1418                            }
1419                        }
1420                        if (args.observer != null) {
1421                            try {
1422                                Bundle extras = extrasForInstallResult(res);
1423                                args.observer.onPackageInstalled(res.name, res.returnCode,
1424                                        res.returnMsg, extras);
1425                            } catch (RemoteException e) {
1426                                Slog.i(TAG, "Observer no longer exists.");
1427                            }
1428                        }
1429                    } else {
1430                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1431                    }
1432                } break;
1433                case UPDATED_MEDIA_STATUS: {
1434                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1435                    boolean reportStatus = msg.arg1 == 1;
1436                    boolean doGc = msg.arg2 == 1;
1437                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1438                    if (doGc) {
1439                        // Force a gc to clear up stale containers.
1440                        Runtime.getRuntime().gc();
1441                    }
1442                    if (msg.obj != null) {
1443                        @SuppressWarnings("unchecked")
1444                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1445                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1446                        // Unload containers
1447                        unloadAllContainers(args);
1448                    }
1449                    if (reportStatus) {
1450                        try {
1451                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1452                            PackageHelper.getMountService().finishMediaUpdate();
1453                        } catch (RemoteException e) {
1454                            Log.e(TAG, "MountService not running?");
1455                        }
1456                    }
1457                } break;
1458                case WRITE_SETTINGS: {
1459                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1460                    synchronized (mPackages) {
1461                        removeMessages(WRITE_SETTINGS);
1462                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1463                        mSettings.writeLPr();
1464                        mDirtyUsers.clear();
1465                    }
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1467                } break;
1468                case WRITE_PACKAGE_RESTRICTIONS: {
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470                    synchronized (mPackages) {
1471                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1472                        for (int userId : mDirtyUsers) {
1473                            mSettings.writePackageRestrictionsLPr(userId);
1474                        }
1475                        mDirtyUsers.clear();
1476                    }
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478                } break;
1479                case CHECK_PENDING_VERIFICATION: {
1480                    final int verificationId = msg.arg1;
1481                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1482
1483                    if ((state != null) && !state.timeoutExtended()) {
1484                        final InstallArgs args = state.getInstallArgs();
1485                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1486
1487                        Slog.i(TAG, "Verification timed out for " + originUri);
1488                        mPendingVerification.remove(verificationId);
1489
1490                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1491
1492                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1493                            Slog.i(TAG, "Continuing with installation of " + originUri);
1494                            state.setVerifierResponse(Binder.getCallingUid(),
1495                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1496                            broadcastPackageVerified(verificationId, originUri,
1497                                    PackageManager.VERIFICATION_ALLOW,
1498                                    state.getInstallArgs().getUser());
1499                            try {
1500                                ret = args.copyApk(mContainerService, true);
1501                            } catch (RemoteException e) {
1502                                Slog.e(TAG, "Could not contact the ContainerService");
1503                            }
1504                        } else {
1505                            broadcastPackageVerified(verificationId, originUri,
1506                                    PackageManager.VERIFICATION_REJECT,
1507                                    state.getInstallArgs().getUser());
1508                        }
1509
1510                        processPendingInstall(args, ret);
1511                        mHandler.sendEmptyMessage(MCS_UNBIND);
1512                    }
1513                    break;
1514                }
1515                case PACKAGE_VERIFIED: {
1516                    final int verificationId = msg.arg1;
1517
1518                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1519                    if (state == null) {
1520                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1521                        break;
1522                    }
1523
1524                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1525
1526                    state.setVerifierResponse(response.callerUid, response.code);
1527
1528                    if (state.isVerificationComplete()) {
1529                        mPendingVerification.remove(verificationId);
1530
1531                        final InstallArgs args = state.getInstallArgs();
1532                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1533
1534                        int ret;
1535                        if (state.isInstallAllowed()) {
1536                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1537                            broadcastPackageVerified(verificationId, originUri,
1538                                    response.code, state.getInstallArgs().getUser());
1539                            try {
1540                                ret = args.copyApk(mContainerService, true);
1541                            } catch (RemoteException e) {
1542                                Slog.e(TAG, "Could not contact the ContainerService");
1543                            }
1544                        } else {
1545                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1546                        }
1547
1548                        processPendingInstall(args, ret);
1549
1550                        mHandler.sendEmptyMessage(MCS_UNBIND);
1551                    }
1552
1553                    break;
1554                }
1555                case START_INTENT_FILTER_VERIFICATIONS: {
1556                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1557                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1558                            params.replacing, params.pkg);
1559                    break;
1560                }
1561                case INTENT_FILTER_VERIFIED: {
1562                    final int verificationId = msg.arg1;
1563
1564                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1565                            verificationId);
1566                    if (state == null) {
1567                        Slog.w(TAG, "Invalid IntentFilter verification token "
1568                                + verificationId + " received");
1569                        break;
1570                    }
1571
1572                    final int userId = state.getUserId();
1573
1574                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1575                            "Processing IntentFilter verification with token:"
1576                            + verificationId + " and userId:" + userId);
1577
1578                    final IntentFilterVerificationResponse response =
1579                            (IntentFilterVerificationResponse) msg.obj;
1580
1581                    state.setVerifierResponse(response.callerUid, response.code);
1582
1583                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1584                            "IntentFilter verification with token:" + verificationId
1585                            + " and userId:" + userId
1586                            + " is settings verifier response with response code:"
1587                            + response.code);
1588
1589                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1590                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1591                                + response.getFailedDomainsString());
1592                    }
1593
1594                    if (state.isVerificationComplete()) {
1595                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1596                    } else {
1597                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598                                "IntentFilter verification with token:" + verificationId
1599                                + " was not said to be complete");
1600                    }
1601
1602                    break;
1603                }
1604            }
1605        }
1606    }
1607
1608    private StorageEventListener mStorageListener = new StorageEventListener() {
1609        @Override
1610        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1611            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1612                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1613                    final String volumeUuid = vol.getFsUuid();
1614
1615                    // Clean up any users or apps that were removed or recreated
1616                    // while this volume was missing
1617                    reconcileUsers(volumeUuid);
1618                    reconcileApps(volumeUuid);
1619
1620                    // Clean up any install sessions that expired or were
1621                    // cancelled while this volume was missing
1622                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1623
1624                    loadPrivatePackages(vol);
1625
1626                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1627                    unloadPrivatePackages(vol);
1628                }
1629            }
1630
1631            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1632                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1633                    updateExternalMediaStatus(true, false);
1634                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1635                    updateExternalMediaStatus(false, false);
1636                }
1637            }
1638        }
1639
1640        @Override
1641        public void onVolumeForgotten(String fsUuid) {
1642            // Remove any apps installed on the forgotten volume
1643            synchronized (mPackages) {
1644                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1645                for (PackageSetting ps : packages) {
1646                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1647                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1648                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1649                }
1650
1651                mSettings.writeLPr();
1652            }
1653        }
1654    };
1655
1656    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1657        if (userId >= UserHandle.USER_OWNER) {
1658            grantRequestedRuntimePermissionsForUser(pkg, userId);
1659        } else if (userId == UserHandle.USER_ALL) {
1660            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1661                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1662            }
1663        }
1664
1665        // We could have touched GID membership, so flush out packages.list
1666        synchronized (mPackages) {
1667            mSettings.writePackageListLPr();
1668        }
1669    }
1670
1671    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1672        SettingBase sb = (SettingBase) pkg.mExtras;
1673        if (sb == null) {
1674            return;
1675        }
1676
1677        PermissionsState permissionsState = sb.getPermissionsState();
1678
1679        for (String permission : pkg.requestedPermissions) {
1680            BasePermission bp = mSettings.mPermissions.get(permission);
1681            if (bp != null && bp.isRuntime()) {
1682                permissionsState.grantRuntimePermission(bp, userId);
1683            }
1684        }
1685    }
1686
1687    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1688        Bundle extras = null;
1689        switch (res.returnCode) {
1690            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1691                extras = new Bundle();
1692                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1693                        res.origPermission);
1694                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1695                        res.origPackage);
1696                break;
1697            }
1698            case PackageManager.INSTALL_SUCCEEDED: {
1699                extras = new Bundle();
1700                extras.putBoolean(Intent.EXTRA_REPLACING,
1701                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1702                break;
1703            }
1704        }
1705        return extras;
1706    }
1707
1708    void scheduleWriteSettingsLocked() {
1709        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1710            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1711        }
1712    }
1713
1714    void scheduleWritePackageRestrictionsLocked(int userId) {
1715        if (!sUserManager.exists(userId)) return;
1716        mDirtyUsers.add(userId);
1717        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1718            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1719        }
1720    }
1721
1722    public static PackageManagerService main(Context context, Installer installer,
1723            boolean factoryTest, boolean onlyCore) {
1724        PackageManagerService m = new PackageManagerService(context, installer,
1725                factoryTest, onlyCore);
1726        ServiceManager.addService("package", m);
1727        return m;
1728    }
1729
1730    static String[] splitString(String str, char sep) {
1731        int count = 1;
1732        int i = 0;
1733        while ((i=str.indexOf(sep, i)) >= 0) {
1734            count++;
1735            i++;
1736        }
1737
1738        String[] res = new String[count];
1739        i=0;
1740        count = 0;
1741        int lastI=0;
1742        while ((i=str.indexOf(sep, i)) >= 0) {
1743            res[count] = str.substring(lastI, i);
1744            count++;
1745            i++;
1746            lastI = i;
1747        }
1748        res[count] = str.substring(lastI, str.length());
1749        return res;
1750    }
1751
1752    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1753        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1754                Context.DISPLAY_SERVICE);
1755        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1756    }
1757
1758    public PackageManagerService(Context context, Installer installer,
1759            boolean factoryTest, boolean onlyCore) {
1760        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1761                SystemClock.uptimeMillis());
1762
1763        if (mSdkVersion <= 0) {
1764            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1765        }
1766
1767        mContext = context;
1768        mFactoryTest = factoryTest;
1769        mOnlyCore = onlyCore;
1770        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1771        mMetrics = new DisplayMetrics();
1772        mSettings = new Settings(mPackages);
1773        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1774                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1775        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1776                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1777        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1778                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1779        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1780                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1781        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1782                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1783        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1784                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1785
1786        // TODO: add a property to control this?
1787        long dexOptLRUThresholdInMinutes;
1788        if (mLazyDexOpt) {
1789            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1790        } else {
1791            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1792        }
1793        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1794
1795        String separateProcesses = SystemProperties.get("debug.separate_processes");
1796        if (separateProcesses != null && separateProcesses.length() > 0) {
1797            if ("*".equals(separateProcesses)) {
1798                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1799                mSeparateProcesses = null;
1800                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1801            } else {
1802                mDefParseFlags = 0;
1803                mSeparateProcesses = separateProcesses.split(",");
1804                Slog.w(TAG, "Running with debug.separate_processes: "
1805                        + separateProcesses);
1806            }
1807        } else {
1808            mDefParseFlags = 0;
1809            mSeparateProcesses = null;
1810        }
1811
1812        mInstaller = installer;
1813        mPackageDexOptimizer = new PackageDexOptimizer(this);
1814        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1815
1816        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1817                FgThread.get().getLooper());
1818
1819        getDefaultDisplayMetrics(context, mMetrics);
1820
1821        SystemConfig systemConfig = SystemConfig.getInstance();
1822        mGlobalGids = systemConfig.getGlobalGids();
1823        mSystemPermissions = systemConfig.getSystemPermissions();
1824        mAvailableFeatures = systemConfig.getAvailableFeatures();
1825
1826        synchronized (mInstallLock) {
1827        // writer
1828        synchronized (mPackages) {
1829            mHandlerThread = new ServiceThread(TAG,
1830                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1831            mHandlerThread.start();
1832            mHandler = new PackageHandler(mHandlerThread.getLooper());
1833            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1834
1835            File dataDir = Environment.getDataDirectory();
1836            mAppDataDir = new File(dataDir, "data");
1837            mAppInstallDir = new File(dataDir, "app");
1838            mAppLib32InstallDir = new File(dataDir, "app-lib");
1839            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1840            mUserAppDataDir = new File(dataDir, "user");
1841            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1842
1843            sUserManager = new UserManagerService(context, this,
1844                    mInstallLock, mPackages);
1845
1846            // Propagate permission configuration in to package manager.
1847            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1848                    = systemConfig.getPermissions();
1849            for (int i=0; i<permConfig.size(); i++) {
1850                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1851                BasePermission bp = mSettings.mPermissions.get(perm.name);
1852                if (bp == null) {
1853                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1854                    mSettings.mPermissions.put(perm.name, bp);
1855                }
1856                if (perm.gids != null) {
1857                    bp.setGids(perm.gids, perm.perUser);
1858                }
1859            }
1860
1861            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1862            for (int i=0; i<libConfig.size(); i++) {
1863                mSharedLibraries.put(libConfig.keyAt(i),
1864                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1865            }
1866
1867            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1868
1869            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1870                    mSdkVersion, mOnlyCore);
1871
1872            String customResolverActivity = Resources.getSystem().getString(
1873                    R.string.config_customResolverActivity);
1874            if (TextUtils.isEmpty(customResolverActivity)) {
1875                customResolverActivity = null;
1876            } else {
1877                mCustomResolverComponentName = ComponentName.unflattenFromString(
1878                        customResolverActivity);
1879            }
1880
1881            long startTime = SystemClock.uptimeMillis();
1882
1883            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1884                    startTime);
1885
1886            // Set flag to monitor and not change apk file paths when
1887            // scanning install directories.
1888            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1889
1890            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1891
1892            /**
1893             * Add everything in the in the boot class path to the
1894             * list of process files because dexopt will have been run
1895             * if necessary during zygote startup.
1896             */
1897            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1898            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1899
1900            if (bootClassPath != null) {
1901                String[] bootClassPathElements = splitString(bootClassPath, ':');
1902                for (String element : bootClassPathElements) {
1903                    alreadyDexOpted.add(element);
1904                }
1905            } else {
1906                Slog.w(TAG, "No BOOTCLASSPATH found!");
1907            }
1908
1909            if (systemServerClassPath != null) {
1910                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1911                for (String element : systemServerClassPathElements) {
1912                    alreadyDexOpted.add(element);
1913                }
1914            } else {
1915                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1916            }
1917
1918            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1919            final String[] dexCodeInstructionSets =
1920                    getDexCodeInstructionSets(
1921                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1922
1923            /**
1924             * Ensure all external libraries have had dexopt run on them.
1925             */
1926            if (mSharedLibraries.size() > 0) {
1927                // NOTE: For now, we're compiling these system "shared libraries"
1928                // (and framework jars) into all available architectures. It's possible
1929                // to compile them only when we come across an app that uses them (there's
1930                // already logic for that in scanPackageLI) but that adds some complexity.
1931                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1932                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1933                        final String lib = libEntry.path;
1934                        if (lib == null) {
1935                            continue;
1936                        }
1937
1938                        try {
1939                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1940                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1941                                alreadyDexOpted.add(lib);
1942                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1943                            }
1944                        } catch (FileNotFoundException e) {
1945                            Slog.w(TAG, "Library not found: " + lib);
1946                        } catch (IOException e) {
1947                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1948                                    + e.getMessage());
1949                        }
1950                    }
1951                }
1952            }
1953
1954            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1955
1956            // Gross hack for now: we know this file doesn't contain any
1957            // code, so don't dexopt it to avoid the resulting log spew.
1958            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1959
1960            // Gross hack for now: we know this file is only part of
1961            // the boot class path for art, so don't dexopt it to
1962            // avoid the resulting log spew.
1963            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1964
1965            /**
1966             * There are a number of commands implemented in Java, which
1967             * we currently need to do the dexopt on so that they can be
1968             * run from a non-root shell.
1969             */
1970            String[] frameworkFiles = frameworkDir.list();
1971            if (frameworkFiles != null) {
1972                // TODO: We could compile these only for the most preferred ABI. We should
1973                // first double check that the dex files for these commands are not referenced
1974                // by other system apps.
1975                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1976                    for (int i=0; i<frameworkFiles.length; i++) {
1977                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1978                        String path = libPath.getPath();
1979                        // Skip the file if we already did it.
1980                        if (alreadyDexOpted.contains(path)) {
1981                            continue;
1982                        }
1983                        // Skip the file if it is not a type we want to dexopt.
1984                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1985                            continue;
1986                        }
1987                        try {
1988                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1989                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1990                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1991                            }
1992                        } catch (FileNotFoundException e) {
1993                            Slog.w(TAG, "Jar not found: " + path);
1994                        } catch (IOException e) {
1995                            Slog.w(TAG, "Exception reading jar: " + path, e);
1996                        }
1997                    }
1998                }
1999            }
2000
2001            // Collect vendor overlay packages.
2002            // (Do this before scanning any apps.)
2003            // For security and version matching reason, only consider
2004            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2005            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2006            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2007                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2008
2009            // Find base frameworks (resource packages without code).
2010            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2011                    | PackageParser.PARSE_IS_SYSTEM_DIR
2012                    | PackageParser.PARSE_IS_PRIVILEGED,
2013                    scanFlags | SCAN_NO_DEX, 0);
2014
2015            // Collected privileged system packages.
2016            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2017            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2018                    | PackageParser.PARSE_IS_SYSTEM_DIR
2019                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2020
2021            // Collect ordinary system packages.
2022            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2023            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2024                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2025
2026            // Collect all vendor packages.
2027            File vendorAppDir = new File("/vendor/app");
2028            try {
2029                vendorAppDir = vendorAppDir.getCanonicalFile();
2030            } catch (IOException e) {
2031                // failed to look up canonical path, continue with original one
2032            }
2033            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2034                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2035
2036            // Collect all OEM packages.
2037            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2038            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2039                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2040
2041            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2042            mInstaller.moveFiles();
2043
2044            // Prune any system packages that no longer exist.
2045            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2046            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2047            if (!mOnlyCore) {
2048                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2049                while (psit.hasNext()) {
2050                    PackageSetting ps = psit.next();
2051
2052                    /*
2053                     * If this is not a system app, it can't be a
2054                     * disable system app.
2055                     */
2056                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2057                        continue;
2058                    }
2059
2060                    /*
2061                     * If the package is scanned, it's not erased.
2062                     */
2063                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2064                    if (scannedPkg != null) {
2065                        /*
2066                         * If the system app is both scanned and in the
2067                         * disabled packages list, then it must have been
2068                         * added via OTA. Remove it from the currently
2069                         * scanned package so the previously user-installed
2070                         * application can be scanned.
2071                         */
2072                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2073                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2074                                    + ps.name + "; removing system app.  Last known codePath="
2075                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2076                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2077                                    + scannedPkg.mVersionCode);
2078                            removePackageLI(ps, true);
2079                            expectingBetter.put(ps.name, ps.codePath);
2080                        }
2081
2082                        continue;
2083                    }
2084
2085                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2086                        psit.remove();
2087                        logCriticalInfo(Log.WARN, "System package " + ps.name
2088                                + " no longer exists; wiping its data");
2089                        removeDataDirsLI(null, ps.name);
2090                    } else {
2091                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2092                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2093                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2094                        }
2095                    }
2096                }
2097            }
2098
2099            //look for any incomplete package installations
2100            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2101            //clean up list
2102            for(int i = 0; i < deletePkgsList.size(); i++) {
2103                //clean up here
2104                cleanupInstallFailedPackage(deletePkgsList.get(i));
2105            }
2106            //delete tmp files
2107            deleteTempPackageFiles();
2108
2109            // Remove any shared userIDs that have no associated packages
2110            mSettings.pruneSharedUsersLPw();
2111
2112            if (!mOnlyCore) {
2113                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2114                        SystemClock.uptimeMillis());
2115                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2116
2117                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2118                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2119
2120                /**
2121                 * Remove disable package settings for any updated system
2122                 * apps that were removed via an OTA. If they're not a
2123                 * previously-updated app, remove them completely.
2124                 * Otherwise, just revoke their system-level permissions.
2125                 */
2126                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2127                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2128                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2129
2130                    String msg;
2131                    if (deletedPkg == null) {
2132                        msg = "Updated system package " + deletedAppName
2133                                + " no longer exists; wiping its data";
2134                        removeDataDirsLI(null, deletedAppName);
2135                    } else {
2136                        msg = "Updated system app + " + deletedAppName
2137                                + " no longer present; removing system privileges for "
2138                                + deletedAppName;
2139
2140                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2141
2142                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2143                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2144                    }
2145                    logCriticalInfo(Log.WARN, msg);
2146                }
2147
2148                /**
2149                 * Make sure all system apps that we expected to appear on
2150                 * the userdata partition actually showed up. If they never
2151                 * appeared, crawl back and revive the system version.
2152                 */
2153                for (int i = 0; i < expectingBetter.size(); i++) {
2154                    final String packageName = expectingBetter.keyAt(i);
2155                    if (!mPackages.containsKey(packageName)) {
2156                        final File scanFile = expectingBetter.valueAt(i);
2157
2158                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2159                                + " but never showed up; reverting to system");
2160
2161                        final int reparseFlags;
2162                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2163                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2164                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2165                                    | PackageParser.PARSE_IS_PRIVILEGED;
2166                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2167                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2168                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2169                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2170                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2171                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2172                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2173                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2174                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2175                        } else {
2176                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2177                            continue;
2178                        }
2179
2180                        mSettings.enableSystemPackageLPw(packageName);
2181
2182                        try {
2183                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2184                        } catch (PackageManagerException e) {
2185                            Slog.e(TAG, "Failed to parse original system package: "
2186                                    + e.getMessage());
2187                        }
2188                    }
2189                }
2190            }
2191
2192            // Now that we know all of the shared libraries, update all clients to have
2193            // the correct library paths.
2194            updateAllSharedLibrariesLPw();
2195
2196            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2197                // NOTE: We ignore potential failures here during a system scan (like
2198                // the rest of the commands above) because there's precious little we
2199                // can do about it. A settings error is reported, though.
2200                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2201                        false /* force dexopt */, false /* defer dexopt */);
2202            }
2203
2204            // Now that we know all the packages we are keeping,
2205            // read and update their last usage times.
2206            mPackageUsage.readLP();
2207
2208            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2209                    SystemClock.uptimeMillis());
2210            Slog.i(TAG, "Time to scan packages: "
2211                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2212                    + " seconds");
2213
2214            // If the platform SDK has changed since the last time we booted,
2215            // we need to re-grant app permission to catch any new ones that
2216            // appear.  This is really a hack, and means that apps can in some
2217            // cases get permissions that the user didn't initially explicitly
2218            // allow...  it would be nice to have some better way to handle
2219            // this situation.
2220            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2221                    != mSdkVersion;
2222            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2223                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2224                    + "; regranting permissions for internal storage");
2225            mSettings.mInternalSdkPlatform = mSdkVersion;
2226
2227            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2228                    | (regrantPermissions
2229                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2230                            : 0));
2231
2232            // If this is the first boot, and it is a normal boot, then
2233            // we need to initialize the default preferred apps.
2234            if (!mRestoredSettings && !onlyCore) {
2235                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2236                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2237            }
2238
2239            // If this is first boot after an OTA, and a normal boot, then
2240            // we need to clear code cache directories.
2241            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2242            if (mIsUpgrade && !onlyCore) {
2243                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2244                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2245                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2246                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2247                }
2248                mSettings.mFingerprint = Build.FINGERPRINT;
2249            }
2250
2251            primeDomainVerificationsLPw();
2252            checkDefaultBrowser();
2253
2254            // All the changes are done during package scanning.
2255            mSettings.updateInternalDatabaseVersion();
2256
2257            // can downgrade to reader
2258            mSettings.writeLPr();
2259
2260            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2261                    SystemClock.uptimeMillis());
2262
2263            mRequiredVerifierPackage = getRequiredVerifierLPr();
2264            mRequiredInstallerPackage = getRequiredInstallerLPr();
2265
2266            mInstallerService = new PackageInstallerService(context, this);
2267
2268            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2269            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2270                    mIntentFilterVerifierComponent);
2271
2272        } // synchronized (mPackages)
2273        } // synchronized (mInstallLock)
2274
2275        // Now after opening every single application zip, make sure they
2276        // are all flushed.  Not really needed, but keeps things nice and
2277        // tidy.
2278        Runtime.getRuntime().gc();
2279
2280        // Expose private service for system components to use.
2281        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2282    }
2283
2284    @Override
2285    public boolean isFirstBoot() {
2286        return !mRestoredSettings;
2287    }
2288
2289    @Override
2290    public boolean isOnlyCoreApps() {
2291        return mOnlyCore;
2292    }
2293
2294    @Override
2295    public boolean isUpgrade() {
2296        return mIsUpgrade;
2297    }
2298
2299    private String getRequiredVerifierLPr() {
2300        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2301        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2302                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2303
2304        String requiredVerifier = null;
2305
2306        final int N = receivers.size();
2307        for (int i = 0; i < N; i++) {
2308            final ResolveInfo info = receivers.get(i);
2309
2310            if (info.activityInfo == null) {
2311                continue;
2312            }
2313
2314            final String packageName = info.activityInfo.packageName;
2315
2316            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2317                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2318                continue;
2319            }
2320
2321            if (requiredVerifier != null) {
2322                throw new RuntimeException("There can be only one required verifier");
2323            }
2324
2325            requiredVerifier = packageName;
2326        }
2327
2328        return requiredVerifier;
2329    }
2330
2331    private String getRequiredInstallerLPr() {
2332        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2333        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2334        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2335
2336        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2337                PACKAGE_MIME_TYPE, 0, 0);
2338
2339        String requiredInstaller = null;
2340
2341        final int N = installers.size();
2342        for (int i = 0; i < N; i++) {
2343            final ResolveInfo info = installers.get(i);
2344            final String packageName = info.activityInfo.packageName;
2345
2346            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2347                continue;
2348            }
2349
2350            if (requiredInstaller != null) {
2351                throw new RuntimeException("There must be one required installer");
2352            }
2353
2354            requiredInstaller = packageName;
2355        }
2356
2357        if (requiredInstaller == null) {
2358            throw new RuntimeException("There must be one required installer");
2359        }
2360
2361        return requiredInstaller;
2362    }
2363
2364    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2365        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2366        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2367                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2368
2369        ComponentName verifierComponentName = null;
2370
2371        int priority = -1000;
2372        final int N = receivers.size();
2373        for (int i = 0; i < N; i++) {
2374            final ResolveInfo info = receivers.get(i);
2375
2376            if (info.activityInfo == null) {
2377                continue;
2378            }
2379
2380            final String packageName = info.activityInfo.packageName;
2381
2382            final PackageSetting ps = mSettings.mPackages.get(packageName);
2383            if (ps == null) {
2384                continue;
2385            }
2386
2387            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2388                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2389                continue;
2390            }
2391
2392            // Select the IntentFilterVerifier with the highest priority
2393            if (priority < info.priority) {
2394                priority = info.priority;
2395                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2396                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2397                        + verifierComponentName + " with priority: " + info.priority);
2398            }
2399        }
2400
2401        return verifierComponentName;
2402    }
2403
2404    private void primeDomainVerificationsLPw() {
2405        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2406        boolean updated = false;
2407        ArraySet<String> allHostsSet = new ArraySet<>();
2408        for (PackageParser.Package pkg : mPackages.values()) {
2409            final String packageName = pkg.packageName;
2410            if (!hasDomainURLs(pkg)) {
2411                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2412                            "package with no domain URLs: " + packageName);
2413                continue;
2414            }
2415            if (!pkg.isSystemApp()) {
2416                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2417                        "No priming domain verifications for a non system package : " +
2418                                packageName);
2419                continue;
2420            }
2421            for (PackageParser.Activity a : pkg.activities) {
2422                for (ActivityIntentInfo filter : a.intents) {
2423                    if (hasValidDomains(filter)) {
2424                        allHostsSet.addAll(filter.getHostsList());
2425                    }
2426                }
2427            }
2428            if (allHostsSet.size() == 0) {
2429                allHostsSet.add("*");
2430            }
2431            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2432            IntentFilterVerificationInfo ivi =
2433                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2434            if (ivi != null) {
2435                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2436                        "Priming domain verifications for package: " + packageName +
2437                        " with hosts:" + ivi.getDomainsString());
2438                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2439                updated = true;
2440            }
2441            else {
2442                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2443                        "No priming domain verifications for package: " + packageName);
2444            }
2445            allHostsSet.clear();
2446        }
2447        if (updated) {
2448            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2449                    "Will need to write primed domain verifications");
2450        }
2451        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2452    }
2453
2454    private void applyFactoryDefaultBrowserLPw(int userId) {
2455        // The default browser app's package name is stored in a string resource,
2456        // with a product-specific overlay used for vendor customization.
2457        String browserPkg = mContext.getResources().getString(
2458                com.android.internal.R.string.default_browser);
2459        if (browserPkg != null) {
2460            // non-empty string => required to be a known package
2461            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2462            if (ps == null) {
2463                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2464                browserPkg = null;
2465            } else {
2466                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2467            }
2468        }
2469
2470        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2471        // default.  If there's more than one, just leave everything alone.
2472        if (browserPkg == null) {
2473            calculateDefaultBrowserLPw(userId);
2474        }
2475    }
2476
2477    private void calculateDefaultBrowserLPw(int userId) {
2478        List<String> allBrowsers = resolveAllBrowserApps(userId);
2479        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2480        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2481    }
2482
2483    private List<String> resolveAllBrowserApps(int userId) {
2484        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2485        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2486                PackageManager.MATCH_ALL, userId);
2487
2488        final int count = list.size();
2489        List<String> result = new ArrayList<String>(count);
2490        for (int i=0; i<count; i++) {
2491            ResolveInfo info = list.get(i);
2492            if (info.activityInfo == null
2493                    || !info.handleAllWebDataURI
2494                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2495                    || result.contains(info.activityInfo.packageName)) {
2496                continue;
2497            }
2498            result.add(info.activityInfo.packageName);
2499        }
2500
2501        return result;
2502    }
2503
2504    private boolean packageIsBrowser(String packageName, int userId) {
2505        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2506                PackageManager.MATCH_ALL, userId);
2507        final int N = list.size();
2508        for (int i = 0; i < N; i++) {
2509            ResolveInfo info = list.get(i);
2510            if (packageName.equals(info.activityInfo.packageName)) {
2511                return true;
2512            }
2513        }
2514        return false;
2515    }
2516
2517    private void checkDefaultBrowser() {
2518        final int myUserId = UserHandle.myUserId();
2519        final String packageName = getDefaultBrowserPackageName(myUserId);
2520        if (packageName != null) {
2521            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2522            if (info == null) {
2523                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2524                synchronized (mPackages) {
2525                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2526                }
2527            }
2528        }
2529    }
2530
2531    @Override
2532    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2533            throws RemoteException {
2534        try {
2535            return super.onTransact(code, data, reply, flags);
2536        } catch (RuntimeException e) {
2537            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2538                Slog.wtf(TAG, "Package Manager Crash", e);
2539            }
2540            throw e;
2541        }
2542    }
2543
2544    void cleanupInstallFailedPackage(PackageSetting ps) {
2545        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2546
2547        removeDataDirsLI(ps.volumeUuid, ps.name);
2548        if (ps.codePath != null) {
2549            if (ps.codePath.isDirectory()) {
2550                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2551            } else {
2552                ps.codePath.delete();
2553            }
2554        }
2555        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2556            if (ps.resourcePath.isDirectory()) {
2557                FileUtils.deleteContents(ps.resourcePath);
2558            }
2559            ps.resourcePath.delete();
2560        }
2561        mSettings.removePackageLPw(ps.name);
2562    }
2563
2564    static int[] appendInts(int[] cur, int[] add) {
2565        if (add == null) return cur;
2566        if (cur == null) return add;
2567        final int N = add.length;
2568        for (int i=0; i<N; i++) {
2569            cur = appendInt(cur, add[i]);
2570        }
2571        return cur;
2572    }
2573
2574    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2575        if (!sUserManager.exists(userId)) return null;
2576        final PackageSetting ps = (PackageSetting) p.mExtras;
2577        if (ps == null) {
2578            return null;
2579        }
2580
2581        final PermissionsState permissionsState = ps.getPermissionsState();
2582
2583        final int[] gids = permissionsState.computeGids(userId);
2584        final Set<String> permissions = permissionsState.getPermissions(userId);
2585        final PackageUserState state = ps.readUserState(userId);
2586
2587        return PackageParser.generatePackageInfo(p, gids, flags,
2588                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2589    }
2590
2591    @Override
2592    public boolean isPackageFrozen(String packageName) {
2593        synchronized (mPackages) {
2594            final PackageSetting ps = mSettings.mPackages.get(packageName);
2595            if (ps != null) {
2596                return ps.frozen;
2597            }
2598        }
2599        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2600        return true;
2601    }
2602
2603    @Override
2604    public boolean isPackageAvailable(String packageName, int userId) {
2605        if (!sUserManager.exists(userId)) return false;
2606        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2607        synchronized (mPackages) {
2608            PackageParser.Package p = mPackages.get(packageName);
2609            if (p != null) {
2610                final PackageSetting ps = (PackageSetting) p.mExtras;
2611                if (ps != null) {
2612                    final PackageUserState state = ps.readUserState(userId);
2613                    if (state != null) {
2614                        return PackageParser.isAvailable(state);
2615                    }
2616                }
2617            }
2618        }
2619        return false;
2620    }
2621
2622    @Override
2623    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2624        if (!sUserManager.exists(userId)) return null;
2625        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2626        // reader
2627        synchronized (mPackages) {
2628            PackageParser.Package p = mPackages.get(packageName);
2629            if (DEBUG_PACKAGE_INFO)
2630                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2631            if (p != null) {
2632                return generatePackageInfo(p, flags, userId);
2633            }
2634            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2635                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2636            }
2637        }
2638        return null;
2639    }
2640
2641    @Override
2642    public String[] currentToCanonicalPackageNames(String[] names) {
2643        String[] out = new String[names.length];
2644        // reader
2645        synchronized (mPackages) {
2646            for (int i=names.length-1; i>=0; i--) {
2647                PackageSetting ps = mSettings.mPackages.get(names[i]);
2648                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2649            }
2650        }
2651        return out;
2652    }
2653
2654    @Override
2655    public String[] canonicalToCurrentPackageNames(String[] names) {
2656        String[] out = new String[names.length];
2657        // reader
2658        synchronized (mPackages) {
2659            for (int i=names.length-1; i>=0; i--) {
2660                String cur = mSettings.mRenamedPackages.get(names[i]);
2661                out[i] = cur != null ? cur : names[i];
2662            }
2663        }
2664        return out;
2665    }
2666
2667    @Override
2668    public int getPackageUid(String packageName, int userId) {
2669        if (!sUserManager.exists(userId)) return -1;
2670        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2671
2672        // reader
2673        synchronized (mPackages) {
2674            PackageParser.Package p = mPackages.get(packageName);
2675            if(p != null) {
2676                return UserHandle.getUid(userId, p.applicationInfo.uid);
2677            }
2678            PackageSetting ps = mSettings.mPackages.get(packageName);
2679            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2680                return -1;
2681            }
2682            p = ps.pkg;
2683            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2684        }
2685    }
2686
2687    @Override
2688    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2689        if (!sUserManager.exists(userId)) {
2690            return null;
2691        }
2692
2693        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2694                "getPackageGids");
2695
2696        // reader
2697        synchronized (mPackages) {
2698            PackageParser.Package p = mPackages.get(packageName);
2699            if (DEBUG_PACKAGE_INFO) {
2700                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2701            }
2702            if (p != null) {
2703                PackageSetting ps = (PackageSetting) p.mExtras;
2704                return ps.getPermissionsState().computeGids(userId);
2705            }
2706        }
2707
2708        return null;
2709    }
2710
2711    @Override
2712    public int getMountExternalMode(int uid) {
2713        if (Process.isIsolated(uid)) {
2714            return Zygote.MOUNT_EXTERNAL_NONE;
2715        } else {
2716            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2717                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2718            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2719                return Zygote.MOUNT_EXTERNAL_WRITE;
2720            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2721                return Zygote.MOUNT_EXTERNAL_READ;
2722            } else {
2723                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2724            }
2725        }
2726    }
2727
2728    static PermissionInfo generatePermissionInfo(
2729            BasePermission bp, int flags) {
2730        if (bp.perm != null) {
2731            return PackageParser.generatePermissionInfo(bp.perm, flags);
2732        }
2733        PermissionInfo pi = new PermissionInfo();
2734        pi.name = bp.name;
2735        pi.packageName = bp.sourcePackage;
2736        pi.nonLocalizedLabel = bp.name;
2737        pi.protectionLevel = bp.protectionLevel;
2738        return pi;
2739    }
2740
2741    @Override
2742    public PermissionInfo getPermissionInfo(String name, int flags) {
2743        // reader
2744        synchronized (mPackages) {
2745            final BasePermission p = mSettings.mPermissions.get(name);
2746            if (p != null) {
2747                return generatePermissionInfo(p, flags);
2748            }
2749            return null;
2750        }
2751    }
2752
2753    @Override
2754    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2755        // reader
2756        synchronized (mPackages) {
2757            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2758            for (BasePermission p : mSettings.mPermissions.values()) {
2759                if (group == null) {
2760                    if (p.perm == null || p.perm.info.group == null) {
2761                        out.add(generatePermissionInfo(p, flags));
2762                    }
2763                } else {
2764                    if (p.perm != null && group.equals(p.perm.info.group)) {
2765                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2766                    }
2767                }
2768            }
2769
2770            if (out.size() > 0) {
2771                return out;
2772            }
2773            return mPermissionGroups.containsKey(group) ? out : null;
2774        }
2775    }
2776
2777    @Override
2778    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2779        // reader
2780        synchronized (mPackages) {
2781            return PackageParser.generatePermissionGroupInfo(
2782                    mPermissionGroups.get(name), flags);
2783        }
2784    }
2785
2786    @Override
2787    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2788        // reader
2789        synchronized (mPackages) {
2790            final int N = mPermissionGroups.size();
2791            ArrayList<PermissionGroupInfo> out
2792                    = new ArrayList<PermissionGroupInfo>(N);
2793            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2794                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2795            }
2796            return out;
2797        }
2798    }
2799
2800    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2801            int userId) {
2802        if (!sUserManager.exists(userId)) return null;
2803        PackageSetting ps = mSettings.mPackages.get(packageName);
2804        if (ps != null) {
2805            if (ps.pkg == null) {
2806                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2807                        flags, userId);
2808                if (pInfo != null) {
2809                    return pInfo.applicationInfo;
2810                }
2811                return null;
2812            }
2813            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2814                    ps.readUserState(userId), userId);
2815        }
2816        return null;
2817    }
2818
2819    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2820            int userId) {
2821        if (!sUserManager.exists(userId)) return null;
2822        PackageSetting ps = mSettings.mPackages.get(packageName);
2823        if (ps != null) {
2824            PackageParser.Package pkg = ps.pkg;
2825            if (pkg == null) {
2826                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2827                    return null;
2828                }
2829                // Only data remains, so we aren't worried about code paths
2830                pkg = new PackageParser.Package(packageName);
2831                pkg.applicationInfo.packageName = packageName;
2832                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2833                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2834                pkg.applicationInfo.dataDir = Environment
2835                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2836                        .getAbsolutePath();
2837                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2838                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2839            }
2840            return generatePackageInfo(pkg, flags, userId);
2841        }
2842        return null;
2843    }
2844
2845    @Override
2846    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2847        if (!sUserManager.exists(userId)) return null;
2848        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2849        // writer
2850        synchronized (mPackages) {
2851            PackageParser.Package p = mPackages.get(packageName);
2852            if (DEBUG_PACKAGE_INFO) Log.v(
2853                    TAG, "getApplicationInfo " + packageName
2854                    + ": " + p);
2855            if (p != null) {
2856                PackageSetting ps = mSettings.mPackages.get(packageName);
2857                if (ps == null) return null;
2858                // Note: isEnabledLP() does not apply here - always return info
2859                return PackageParser.generateApplicationInfo(
2860                        p, flags, ps.readUserState(userId), userId);
2861            }
2862            if ("android".equals(packageName)||"system".equals(packageName)) {
2863                return mAndroidApplication;
2864            }
2865            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2866                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2867            }
2868        }
2869        return null;
2870    }
2871
2872    @Override
2873    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2874            final IPackageDataObserver observer) {
2875        mContext.enforceCallingOrSelfPermission(
2876                android.Manifest.permission.CLEAR_APP_CACHE, null);
2877        // Queue up an async operation since clearing cache may take a little while.
2878        mHandler.post(new Runnable() {
2879            public void run() {
2880                mHandler.removeCallbacks(this);
2881                int retCode = -1;
2882                synchronized (mInstallLock) {
2883                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2884                    if (retCode < 0) {
2885                        Slog.w(TAG, "Couldn't clear application caches");
2886                    }
2887                }
2888                if (observer != null) {
2889                    try {
2890                        observer.onRemoveCompleted(null, (retCode >= 0));
2891                    } catch (RemoteException e) {
2892                        Slog.w(TAG, "RemoveException when invoking call back");
2893                    }
2894                }
2895            }
2896        });
2897    }
2898
2899    @Override
2900    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2901            final IntentSender pi) {
2902        mContext.enforceCallingOrSelfPermission(
2903                android.Manifest.permission.CLEAR_APP_CACHE, null);
2904        // Queue up an async operation since clearing cache may take a little while.
2905        mHandler.post(new Runnable() {
2906            public void run() {
2907                mHandler.removeCallbacks(this);
2908                int retCode = -1;
2909                synchronized (mInstallLock) {
2910                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2911                    if (retCode < 0) {
2912                        Slog.w(TAG, "Couldn't clear application caches");
2913                    }
2914                }
2915                if(pi != null) {
2916                    try {
2917                        // Callback via pending intent
2918                        int code = (retCode >= 0) ? 1 : 0;
2919                        pi.sendIntent(null, code, null,
2920                                null, null);
2921                    } catch (SendIntentException e1) {
2922                        Slog.i(TAG, "Failed to send pending intent");
2923                    }
2924                }
2925            }
2926        });
2927    }
2928
2929    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2930        synchronized (mInstallLock) {
2931            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2932                throw new IOException("Failed to free enough space");
2933            }
2934        }
2935    }
2936
2937    @Override
2938    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2939        if (!sUserManager.exists(userId)) return null;
2940        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2941        synchronized (mPackages) {
2942            PackageParser.Activity a = mActivities.mActivities.get(component);
2943
2944            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2945            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2946                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2947                if (ps == null) return null;
2948                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2949                        userId);
2950            }
2951            if (mResolveComponentName.equals(component)) {
2952                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2953                        new PackageUserState(), userId);
2954            }
2955        }
2956        return null;
2957    }
2958
2959    @Override
2960    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2961            String resolvedType) {
2962        synchronized (mPackages) {
2963            PackageParser.Activity a = mActivities.mActivities.get(component);
2964            if (a == null) {
2965                return false;
2966            }
2967            for (int i=0; i<a.intents.size(); i++) {
2968                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2969                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2970                    return true;
2971                }
2972            }
2973            return false;
2974        }
2975    }
2976
2977    @Override
2978    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2979        if (!sUserManager.exists(userId)) return null;
2980        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2981        synchronized (mPackages) {
2982            PackageParser.Activity a = mReceivers.mActivities.get(component);
2983            if (DEBUG_PACKAGE_INFO) Log.v(
2984                TAG, "getReceiverInfo " + component + ": " + a);
2985            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2986                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2987                if (ps == null) return null;
2988                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2989                        userId);
2990            }
2991        }
2992        return null;
2993    }
2994
2995    @Override
2996    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2997        if (!sUserManager.exists(userId)) return null;
2998        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2999        synchronized (mPackages) {
3000            PackageParser.Service s = mServices.mServices.get(component);
3001            if (DEBUG_PACKAGE_INFO) Log.v(
3002                TAG, "getServiceInfo " + component + ": " + s);
3003            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3004                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3005                if (ps == null) return null;
3006                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3007                        userId);
3008            }
3009        }
3010        return null;
3011    }
3012
3013    @Override
3014    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3015        if (!sUserManager.exists(userId)) return null;
3016        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3017        synchronized (mPackages) {
3018            PackageParser.Provider p = mProviders.mProviders.get(component);
3019            if (DEBUG_PACKAGE_INFO) Log.v(
3020                TAG, "getProviderInfo " + component + ": " + p);
3021            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3022                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3023                if (ps == null) return null;
3024                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3025                        userId);
3026            }
3027        }
3028        return null;
3029    }
3030
3031    @Override
3032    public String[] getSystemSharedLibraryNames() {
3033        Set<String> libSet;
3034        synchronized (mPackages) {
3035            libSet = mSharedLibraries.keySet();
3036            int size = libSet.size();
3037            if (size > 0) {
3038                String[] libs = new String[size];
3039                libSet.toArray(libs);
3040                return libs;
3041            }
3042        }
3043        return null;
3044    }
3045
3046    /**
3047     * @hide
3048     */
3049    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3050        synchronized (mPackages) {
3051            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3052            if (lib != null && lib.apk != null) {
3053                return mPackages.get(lib.apk);
3054            }
3055        }
3056        return null;
3057    }
3058
3059    @Override
3060    public FeatureInfo[] getSystemAvailableFeatures() {
3061        Collection<FeatureInfo> featSet;
3062        synchronized (mPackages) {
3063            featSet = mAvailableFeatures.values();
3064            int size = featSet.size();
3065            if (size > 0) {
3066                FeatureInfo[] features = new FeatureInfo[size+1];
3067                featSet.toArray(features);
3068                FeatureInfo fi = new FeatureInfo();
3069                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3070                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3071                features[size] = fi;
3072                return features;
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public boolean hasSystemFeature(String name) {
3080        synchronized (mPackages) {
3081            return mAvailableFeatures.containsKey(name);
3082        }
3083    }
3084
3085    private void checkValidCaller(int uid, int userId) {
3086        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3087            return;
3088
3089        throw new SecurityException("Caller uid=" + uid
3090                + " is not privileged to communicate with user=" + userId);
3091    }
3092
3093    @Override
3094    public int checkPermission(String permName, String pkgName, int userId) {
3095        if (!sUserManager.exists(userId)) {
3096            return PackageManager.PERMISSION_DENIED;
3097        }
3098
3099        synchronized (mPackages) {
3100            final PackageParser.Package p = mPackages.get(pkgName);
3101            if (p != null && p.mExtras != null) {
3102                final PackageSetting ps = (PackageSetting) p.mExtras;
3103                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3104                    return PackageManager.PERMISSION_GRANTED;
3105                }
3106            }
3107        }
3108
3109        return PackageManager.PERMISSION_DENIED;
3110    }
3111
3112    @Override
3113    public int checkUidPermission(String permName, int uid) {
3114        final int userId = UserHandle.getUserId(uid);
3115
3116        if (!sUserManager.exists(userId)) {
3117            return PackageManager.PERMISSION_DENIED;
3118        }
3119
3120        synchronized (mPackages) {
3121            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3122            if (obj != null) {
3123                final SettingBase ps = (SettingBase) obj;
3124                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3125                    return PackageManager.PERMISSION_GRANTED;
3126                }
3127            } else {
3128                ArraySet<String> perms = mSystemPermissions.get(uid);
3129                if (perms != null && perms.contains(permName)) {
3130                    return PackageManager.PERMISSION_GRANTED;
3131                }
3132            }
3133        }
3134
3135        return PackageManager.PERMISSION_DENIED;
3136    }
3137
3138    /**
3139     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3140     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3141     * @param checkShell TODO(yamasani):
3142     * @param message the message to log on security exception
3143     */
3144    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3145            boolean checkShell, String message) {
3146        if (userId < 0) {
3147            throw new IllegalArgumentException("Invalid userId " + userId);
3148        }
3149        if (checkShell) {
3150            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3151        }
3152        if (userId == UserHandle.getUserId(callingUid)) return;
3153        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3154            if (requireFullPermission) {
3155                mContext.enforceCallingOrSelfPermission(
3156                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3157            } else {
3158                try {
3159                    mContext.enforceCallingOrSelfPermission(
3160                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3161                } catch (SecurityException se) {
3162                    mContext.enforceCallingOrSelfPermission(
3163                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3164                }
3165            }
3166        }
3167    }
3168
3169    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3170        if (callingUid == Process.SHELL_UID) {
3171            if (userHandle >= 0
3172                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3173                throw new SecurityException("Shell does not have permission to access user "
3174                        + userHandle);
3175            } else if (userHandle < 0) {
3176                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3177                        + Debug.getCallers(3));
3178            }
3179        }
3180    }
3181
3182    private BasePermission findPermissionTreeLP(String permName) {
3183        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3184            if (permName.startsWith(bp.name) &&
3185                    permName.length() > bp.name.length() &&
3186                    permName.charAt(bp.name.length()) == '.') {
3187                return bp;
3188            }
3189        }
3190        return null;
3191    }
3192
3193    private BasePermission checkPermissionTreeLP(String permName) {
3194        if (permName != null) {
3195            BasePermission bp = findPermissionTreeLP(permName);
3196            if (bp != null) {
3197                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3198                    return bp;
3199                }
3200                throw new SecurityException("Calling uid "
3201                        + Binder.getCallingUid()
3202                        + " is not allowed to add to permission tree "
3203                        + bp.name + " owned by uid " + bp.uid);
3204            }
3205        }
3206        throw new SecurityException("No permission tree found for " + permName);
3207    }
3208
3209    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3210        if (s1 == null) {
3211            return s2 == null;
3212        }
3213        if (s2 == null) {
3214            return false;
3215        }
3216        if (s1.getClass() != s2.getClass()) {
3217            return false;
3218        }
3219        return s1.equals(s2);
3220    }
3221
3222    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3223        if (pi1.icon != pi2.icon) return false;
3224        if (pi1.logo != pi2.logo) return false;
3225        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3226        if (!compareStrings(pi1.name, pi2.name)) return false;
3227        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3228        // We'll take care of setting this one.
3229        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3230        // These are not currently stored in settings.
3231        //if (!compareStrings(pi1.group, pi2.group)) return false;
3232        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3233        //if (pi1.labelRes != pi2.labelRes) return false;
3234        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3235        return true;
3236    }
3237
3238    int permissionInfoFootprint(PermissionInfo info) {
3239        int size = info.name.length();
3240        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3241        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3242        return size;
3243    }
3244
3245    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3246        int size = 0;
3247        for (BasePermission perm : mSettings.mPermissions.values()) {
3248            if (perm.uid == tree.uid) {
3249                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3250            }
3251        }
3252        return size;
3253    }
3254
3255    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3256        // We calculate the max size of permissions defined by this uid and throw
3257        // if that plus the size of 'info' would exceed our stated maximum.
3258        if (tree.uid != Process.SYSTEM_UID) {
3259            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3260            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3261                throw new SecurityException("Permission tree size cap exceeded");
3262            }
3263        }
3264    }
3265
3266    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3267        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3268            throw new SecurityException("Label must be specified in permission");
3269        }
3270        BasePermission tree = checkPermissionTreeLP(info.name);
3271        BasePermission bp = mSettings.mPermissions.get(info.name);
3272        boolean added = bp == null;
3273        boolean changed = true;
3274        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3275        if (added) {
3276            enforcePermissionCapLocked(info, tree);
3277            bp = new BasePermission(info.name, tree.sourcePackage,
3278                    BasePermission.TYPE_DYNAMIC);
3279        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3280            throw new SecurityException(
3281                    "Not allowed to modify non-dynamic permission "
3282                    + info.name);
3283        } else {
3284            if (bp.protectionLevel == fixedLevel
3285                    && bp.perm.owner.equals(tree.perm.owner)
3286                    && bp.uid == tree.uid
3287                    && comparePermissionInfos(bp.perm.info, info)) {
3288                changed = false;
3289            }
3290        }
3291        bp.protectionLevel = fixedLevel;
3292        info = new PermissionInfo(info);
3293        info.protectionLevel = fixedLevel;
3294        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3295        bp.perm.info.packageName = tree.perm.info.packageName;
3296        bp.uid = tree.uid;
3297        if (added) {
3298            mSettings.mPermissions.put(info.name, bp);
3299        }
3300        if (changed) {
3301            if (!async) {
3302                mSettings.writeLPr();
3303            } else {
3304                scheduleWriteSettingsLocked();
3305            }
3306        }
3307        return added;
3308    }
3309
3310    @Override
3311    public boolean addPermission(PermissionInfo info) {
3312        synchronized (mPackages) {
3313            return addPermissionLocked(info, false);
3314        }
3315    }
3316
3317    @Override
3318    public boolean addPermissionAsync(PermissionInfo info) {
3319        synchronized (mPackages) {
3320            return addPermissionLocked(info, true);
3321        }
3322    }
3323
3324    @Override
3325    public void removePermission(String name) {
3326        synchronized (mPackages) {
3327            checkPermissionTreeLP(name);
3328            BasePermission bp = mSettings.mPermissions.get(name);
3329            if (bp != null) {
3330                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3331                    throw new SecurityException(
3332                            "Not allowed to modify non-dynamic permission "
3333                            + name);
3334                }
3335                mSettings.mPermissions.remove(name);
3336                mSettings.writeLPr();
3337            }
3338        }
3339    }
3340
3341    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3342            BasePermission bp) {
3343        int index = pkg.requestedPermissions.indexOf(bp.name);
3344        if (index == -1) {
3345            throw new SecurityException("Package " + pkg.packageName
3346                    + " has not requested permission " + bp.name);
3347        }
3348        if (!bp.isRuntime()) {
3349            throw new SecurityException("Permission " + bp.name
3350                    + " is not a changeable permission type");
3351        }
3352    }
3353
3354    @Override
3355    public void grantRuntimePermission(String packageName, String name, final int userId) {
3356        if (!sUserManager.exists(userId)) {
3357            Log.e(TAG, "No such user:" + userId);
3358            return;
3359        }
3360
3361        mContext.enforceCallingOrSelfPermission(
3362                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3363                "grantRuntimePermission");
3364
3365        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3366                "grantRuntimePermission");
3367
3368        final int uid;
3369        final SettingBase sb;
3370
3371        synchronized (mPackages) {
3372            final PackageParser.Package pkg = mPackages.get(packageName);
3373            if (pkg == null) {
3374                throw new IllegalArgumentException("Unknown package: " + packageName);
3375            }
3376
3377            final BasePermission bp = mSettings.mPermissions.get(name);
3378            if (bp == null) {
3379                throw new IllegalArgumentException("Unknown permission: " + name);
3380            }
3381
3382            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3383
3384            uid = pkg.applicationInfo.uid;
3385            sb = (SettingBase) pkg.mExtras;
3386            if (sb == null) {
3387                throw new IllegalArgumentException("Unknown package: " + packageName);
3388            }
3389
3390            final PermissionsState permissionsState = sb.getPermissionsState();
3391
3392            final int flags = permissionsState.getPermissionFlags(name, userId);
3393            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3394                throw new SecurityException("Cannot grant system fixed permission: "
3395                        + name + " for package: " + packageName);
3396            }
3397
3398            final int result = permissionsState.grantRuntimePermission(bp, userId);
3399            switch (result) {
3400                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3401                    return;
3402                }
3403
3404                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3405                    mHandler.post(new Runnable() {
3406                        @Override
3407                        public void run() {
3408                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3409                        }
3410                    });
3411                } break;
3412            }
3413
3414            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3415
3416            // Not critical if that is lost - app has to request again.
3417            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3418        }
3419
3420        if (READ_EXTERNAL_STORAGE.equals(name)
3421                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3422            final long token = Binder.clearCallingIdentity();
3423            try {
3424                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3425                storage.remountUid(uid);
3426            } finally {
3427                Binder.restoreCallingIdentity(token);
3428            }
3429        }
3430    }
3431
3432    @Override
3433    public void revokeRuntimePermission(String packageName, String name, int userId) {
3434        if (!sUserManager.exists(userId)) {
3435            Log.e(TAG, "No such user:" + userId);
3436            return;
3437        }
3438
3439        mContext.enforceCallingOrSelfPermission(
3440                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3441                "revokeRuntimePermission");
3442
3443        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3444                "revokeRuntimePermission");
3445
3446        final SettingBase sb;
3447
3448        synchronized (mPackages) {
3449            final PackageParser.Package pkg = mPackages.get(packageName);
3450            if (pkg == null) {
3451                throw new IllegalArgumentException("Unknown package: " + packageName);
3452            }
3453
3454            final BasePermission bp = mSettings.mPermissions.get(name);
3455            if (bp == null) {
3456                throw new IllegalArgumentException("Unknown permission: " + name);
3457            }
3458
3459            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3460
3461            sb = (SettingBase) pkg.mExtras;
3462            if (sb == null) {
3463                throw new IllegalArgumentException("Unknown package: " + packageName);
3464            }
3465
3466            final PermissionsState permissionsState = sb.getPermissionsState();
3467
3468            final int flags = permissionsState.getPermissionFlags(name, userId);
3469            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3470                throw new SecurityException("Cannot revoke system fixed permission: "
3471                        + name + " for package: " + packageName);
3472            }
3473
3474            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3475                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3476                return;
3477            }
3478
3479            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3480
3481            // Critical, after this call app should never have the permission.
3482            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3483        }
3484
3485        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3486    }
3487
3488    @Override
3489    public void resetRuntimePermissions() {
3490        mContext.enforceCallingOrSelfPermission(
3491                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3492                "revokeRuntimePermission");
3493
3494        int callingUid = Binder.getCallingUid();
3495        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3496            mContext.enforceCallingOrSelfPermission(
3497                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3498                    "resetRuntimePermissions");
3499        }
3500
3501        final int[] userIds;
3502
3503        synchronized (mPackages) {
3504            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3505            final int userCount = UserManagerService.getInstance().getUserIds().length;
3506            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3507        }
3508
3509        for (int userId : userIds) {
3510            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3511        }
3512    }
3513
3514    @Override
3515    public int getPermissionFlags(String name, String packageName, int userId) {
3516        if (!sUserManager.exists(userId)) {
3517            return 0;
3518        }
3519
3520        mContext.enforceCallingOrSelfPermission(
3521                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3522                "getPermissionFlags");
3523
3524        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3525                "getPermissionFlags");
3526
3527        synchronized (mPackages) {
3528            final PackageParser.Package pkg = mPackages.get(packageName);
3529            if (pkg == null) {
3530                throw new IllegalArgumentException("Unknown package: " + packageName);
3531            }
3532
3533            final BasePermission bp = mSettings.mPermissions.get(name);
3534            if (bp == null) {
3535                throw new IllegalArgumentException("Unknown permission: " + name);
3536            }
3537
3538            SettingBase sb = (SettingBase) pkg.mExtras;
3539            if (sb == null) {
3540                throw new IllegalArgumentException("Unknown package: " + packageName);
3541            }
3542
3543            PermissionsState permissionsState = sb.getPermissionsState();
3544            return permissionsState.getPermissionFlags(name, userId);
3545        }
3546    }
3547
3548    @Override
3549    public void updatePermissionFlags(String name, String packageName, int flagMask,
3550            int flagValues, int userId) {
3551        if (!sUserManager.exists(userId)) {
3552            return;
3553        }
3554
3555        mContext.enforceCallingOrSelfPermission(
3556                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3557                "updatePermissionFlags");
3558
3559        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3560                "updatePermissionFlags");
3561
3562        // Only the system can change system fixed flags.
3563        if (getCallingUid() != Process.SYSTEM_UID) {
3564            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3565            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3566        }
3567
3568        synchronized (mPackages) {
3569            final PackageParser.Package pkg = mPackages.get(packageName);
3570            if (pkg == null) {
3571                throw new IllegalArgumentException("Unknown package: " + packageName);
3572            }
3573
3574            final BasePermission bp = mSettings.mPermissions.get(name);
3575            if (bp == null) {
3576                throw new IllegalArgumentException("Unknown permission: " + name);
3577            }
3578
3579            SettingBase sb = (SettingBase) pkg.mExtras;
3580            if (sb == null) {
3581                throw new IllegalArgumentException("Unknown package: " + packageName);
3582            }
3583
3584            PermissionsState permissionsState = sb.getPermissionsState();
3585
3586            // Only the package manager can change flags for system component permissions.
3587            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3588            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3589                return;
3590            }
3591
3592            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3593
3594            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3595                // Install and runtime permissions are stored in different places,
3596                // so figure out what permission changed and persist the change.
3597                if (permissionsState.getInstallPermissionState(name) != null) {
3598                    scheduleWriteSettingsLocked();
3599                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3600                        || hadState) {
3601                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3602                }
3603            }
3604        }
3605    }
3606
3607    /**
3608     * Update the permission flags for all packages and runtime permissions of a user in order
3609     * to allow device or profile owner to remove POLICY_FIXED.
3610     */
3611    @Override
3612    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3613        if (!sUserManager.exists(userId)) {
3614            return;
3615        }
3616
3617        mContext.enforceCallingOrSelfPermission(
3618                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3619                "updatePermissionFlagsForAllApps");
3620
3621        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3622                "updatePermissionFlagsForAllApps");
3623
3624        // Only the system can change system fixed flags.
3625        if (getCallingUid() != Process.SYSTEM_UID) {
3626            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3627            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3628        }
3629
3630        synchronized (mPackages) {
3631            boolean changed = false;
3632            final int packageCount = mPackages.size();
3633            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3634                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3635                SettingBase sb = (SettingBase) pkg.mExtras;
3636                if (sb == null) {
3637                    continue;
3638                }
3639                PermissionsState permissionsState = sb.getPermissionsState();
3640                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3641                        userId, flagMask, flagValues);
3642            }
3643            if (changed) {
3644                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3645            }
3646        }
3647    }
3648
3649    @Override
3650    public boolean shouldShowRequestPermissionRationale(String permissionName,
3651            String packageName, int userId) {
3652        if (UserHandle.getCallingUserId() != userId) {
3653            mContext.enforceCallingPermission(
3654                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3655                    "canShowRequestPermissionRationale for user " + userId);
3656        }
3657
3658        final int uid = getPackageUid(packageName, userId);
3659        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3660            return false;
3661        }
3662
3663        if (checkPermission(permissionName, packageName, userId)
3664                == PackageManager.PERMISSION_GRANTED) {
3665            return false;
3666        }
3667
3668        final int flags;
3669
3670        final long identity = Binder.clearCallingIdentity();
3671        try {
3672            flags = getPermissionFlags(permissionName,
3673                    packageName, userId);
3674        } finally {
3675            Binder.restoreCallingIdentity(identity);
3676        }
3677
3678        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3679                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3680                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3681
3682        if ((flags & fixedFlags) != 0) {
3683            return false;
3684        }
3685
3686        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3687    }
3688
3689    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3690        BasePermission bp = mSettings.mPermissions.get(permission);
3691        if (bp == null) {
3692            throw new SecurityException("Missing " + permission + " permission");
3693        }
3694
3695        SettingBase sb = (SettingBase) pkg.mExtras;
3696        PermissionsState permissionsState = sb.getPermissionsState();
3697
3698        if (permissionsState.grantInstallPermission(bp) !=
3699                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3700            scheduleWriteSettingsLocked();
3701        }
3702    }
3703
3704    @Override
3705    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3706        mContext.enforceCallingOrSelfPermission(
3707                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3708                "addOnPermissionsChangeListener");
3709
3710        synchronized (mPackages) {
3711            mOnPermissionChangeListeners.addListenerLocked(listener);
3712        }
3713    }
3714
3715    @Override
3716    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3717        synchronized (mPackages) {
3718            mOnPermissionChangeListeners.removeListenerLocked(listener);
3719        }
3720    }
3721
3722    @Override
3723    public boolean isProtectedBroadcast(String actionName) {
3724        synchronized (mPackages) {
3725            return mProtectedBroadcasts.contains(actionName);
3726        }
3727    }
3728
3729    @Override
3730    public int checkSignatures(String pkg1, String pkg2) {
3731        synchronized (mPackages) {
3732            final PackageParser.Package p1 = mPackages.get(pkg1);
3733            final PackageParser.Package p2 = mPackages.get(pkg2);
3734            if (p1 == null || p1.mExtras == null
3735                    || p2 == null || p2.mExtras == null) {
3736                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3737            }
3738            return compareSignatures(p1.mSignatures, p2.mSignatures);
3739        }
3740    }
3741
3742    @Override
3743    public int checkUidSignatures(int uid1, int uid2) {
3744        // Map to base uids.
3745        uid1 = UserHandle.getAppId(uid1);
3746        uid2 = UserHandle.getAppId(uid2);
3747        // reader
3748        synchronized (mPackages) {
3749            Signature[] s1;
3750            Signature[] s2;
3751            Object obj = mSettings.getUserIdLPr(uid1);
3752            if (obj != null) {
3753                if (obj instanceof SharedUserSetting) {
3754                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3755                } else if (obj instanceof PackageSetting) {
3756                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3757                } else {
3758                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3759                }
3760            } else {
3761                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3762            }
3763            obj = mSettings.getUserIdLPr(uid2);
3764            if (obj != null) {
3765                if (obj instanceof SharedUserSetting) {
3766                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3767                } else if (obj instanceof PackageSetting) {
3768                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3769                } else {
3770                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3771                }
3772            } else {
3773                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3774            }
3775            return compareSignatures(s1, s2);
3776        }
3777    }
3778
3779    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3780        final long identity = Binder.clearCallingIdentity();
3781        try {
3782            if (sb instanceof SharedUserSetting) {
3783                SharedUserSetting sus = (SharedUserSetting) sb;
3784                final int packageCount = sus.packages.size();
3785                for (int i = 0; i < packageCount; i++) {
3786                    PackageSetting susPs = sus.packages.valueAt(i);
3787                    if (userId == UserHandle.USER_ALL) {
3788                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3789                    } else {
3790                        final int uid = UserHandle.getUid(userId, susPs.appId);
3791                        killUid(uid, reason);
3792                    }
3793                }
3794            } else if (sb instanceof PackageSetting) {
3795                PackageSetting ps = (PackageSetting) sb;
3796                if (userId == UserHandle.USER_ALL) {
3797                    killApplication(ps.pkg.packageName, ps.appId, reason);
3798                } else {
3799                    final int uid = UserHandle.getUid(userId, ps.appId);
3800                    killUid(uid, reason);
3801                }
3802            }
3803        } finally {
3804            Binder.restoreCallingIdentity(identity);
3805        }
3806    }
3807
3808    private static void killUid(int uid, String reason) {
3809        IActivityManager am = ActivityManagerNative.getDefault();
3810        if (am != null) {
3811            try {
3812                am.killUid(uid, reason);
3813            } catch (RemoteException e) {
3814                /* ignore - same process */
3815            }
3816        }
3817    }
3818
3819    /**
3820     * Compares two sets of signatures. Returns:
3821     * <br />
3822     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3823     * <br />
3824     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3825     * <br />
3826     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3827     * <br />
3828     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3829     * <br />
3830     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3831     */
3832    static int compareSignatures(Signature[] s1, Signature[] s2) {
3833        if (s1 == null) {
3834            return s2 == null
3835                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3836                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3837        }
3838
3839        if (s2 == null) {
3840            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3841        }
3842
3843        if (s1.length != s2.length) {
3844            return PackageManager.SIGNATURE_NO_MATCH;
3845        }
3846
3847        // Since both signature sets are of size 1, we can compare without HashSets.
3848        if (s1.length == 1) {
3849            return s1[0].equals(s2[0]) ?
3850                    PackageManager.SIGNATURE_MATCH :
3851                    PackageManager.SIGNATURE_NO_MATCH;
3852        }
3853
3854        ArraySet<Signature> set1 = new ArraySet<Signature>();
3855        for (Signature sig : s1) {
3856            set1.add(sig);
3857        }
3858        ArraySet<Signature> set2 = new ArraySet<Signature>();
3859        for (Signature sig : s2) {
3860            set2.add(sig);
3861        }
3862        // Make sure s2 contains all signatures in s1.
3863        if (set1.equals(set2)) {
3864            return PackageManager.SIGNATURE_MATCH;
3865        }
3866        return PackageManager.SIGNATURE_NO_MATCH;
3867    }
3868
3869    /**
3870     * If the database version for this type of package (internal storage or
3871     * external storage) is less than the version where package signatures
3872     * were updated, return true.
3873     */
3874    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3875        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3876                DatabaseVersion.SIGNATURE_END_ENTITY))
3877                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3878                        DatabaseVersion.SIGNATURE_END_ENTITY));
3879    }
3880
3881    /**
3882     * Used for backward compatibility to make sure any packages with
3883     * certificate chains get upgraded to the new style. {@code existingSigs}
3884     * will be in the old format (since they were stored on disk from before the
3885     * system upgrade) and {@code scannedSigs} will be in the newer format.
3886     */
3887    private int compareSignaturesCompat(PackageSignatures existingSigs,
3888            PackageParser.Package scannedPkg) {
3889        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3890            return PackageManager.SIGNATURE_NO_MATCH;
3891        }
3892
3893        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3894        for (Signature sig : existingSigs.mSignatures) {
3895            existingSet.add(sig);
3896        }
3897        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3898        for (Signature sig : scannedPkg.mSignatures) {
3899            try {
3900                Signature[] chainSignatures = sig.getChainSignatures();
3901                for (Signature chainSig : chainSignatures) {
3902                    scannedCompatSet.add(chainSig);
3903                }
3904            } catch (CertificateEncodingException e) {
3905                scannedCompatSet.add(sig);
3906            }
3907        }
3908        /*
3909         * Make sure the expanded scanned set contains all signatures in the
3910         * existing one.
3911         */
3912        if (scannedCompatSet.equals(existingSet)) {
3913            // Migrate the old signatures to the new scheme.
3914            existingSigs.assignSignatures(scannedPkg.mSignatures);
3915            // The new KeySets will be re-added later in the scanning process.
3916            synchronized (mPackages) {
3917                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3918            }
3919            return PackageManager.SIGNATURE_MATCH;
3920        }
3921        return PackageManager.SIGNATURE_NO_MATCH;
3922    }
3923
3924    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3925        if (isExternal(scannedPkg)) {
3926            return mSettings.isExternalDatabaseVersionOlderThan(
3927                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3928        } else {
3929            return mSettings.isInternalDatabaseVersionOlderThan(
3930                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3931        }
3932    }
3933
3934    private int compareSignaturesRecover(PackageSignatures existingSigs,
3935            PackageParser.Package scannedPkg) {
3936        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3937            return PackageManager.SIGNATURE_NO_MATCH;
3938        }
3939
3940        String msg = null;
3941        try {
3942            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3943                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3944                        + scannedPkg.packageName);
3945                return PackageManager.SIGNATURE_MATCH;
3946            }
3947        } catch (CertificateException e) {
3948            msg = e.getMessage();
3949        }
3950
3951        logCriticalInfo(Log.INFO,
3952                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3953        return PackageManager.SIGNATURE_NO_MATCH;
3954    }
3955
3956    @Override
3957    public String[] getPackagesForUid(int uid) {
3958        uid = UserHandle.getAppId(uid);
3959        // reader
3960        synchronized (mPackages) {
3961            Object obj = mSettings.getUserIdLPr(uid);
3962            if (obj instanceof SharedUserSetting) {
3963                final SharedUserSetting sus = (SharedUserSetting) obj;
3964                final int N = sus.packages.size();
3965                final String[] res = new String[N];
3966                final Iterator<PackageSetting> it = sus.packages.iterator();
3967                int i = 0;
3968                while (it.hasNext()) {
3969                    res[i++] = it.next().name;
3970                }
3971                return res;
3972            } else if (obj instanceof PackageSetting) {
3973                final PackageSetting ps = (PackageSetting) obj;
3974                return new String[] { ps.name };
3975            }
3976        }
3977        return null;
3978    }
3979
3980    @Override
3981    public String getNameForUid(int uid) {
3982        // reader
3983        synchronized (mPackages) {
3984            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3985            if (obj instanceof SharedUserSetting) {
3986                final SharedUserSetting sus = (SharedUserSetting) obj;
3987                return sus.name + ":" + sus.userId;
3988            } else if (obj instanceof PackageSetting) {
3989                final PackageSetting ps = (PackageSetting) obj;
3990                return ps.name;
3991            }
3992        }
3993        return null;
3994    }
3995
3996    @Override
3997    public int getUidForSharedUser(String sharedUserName) {
3998        if(sharedUserName == null) {
3999            return -1;
4000        }
4001        // reader
4002        synchronized (mPackages) {
4003            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4004            if (suid == null) {
4005                return -1;
4006            }
4007            return suid.userId;
4008        }
4009    }
4010
4011    @Override
4012    public int getFlagsForUid(int uid) {
4013        synchronized (mPackages) {
4014            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4015            if (obj instanceof SharedUserSetting) {
4016                final SharedUserSetting sus = (SharedUserSetting) obj;
4017                return sus.pkgFlags;
4018            } else if (obj instanceof PackageSetting) {
4019                final PackageSetting ps = (PackageSetting) obj;
4020                return ps.pkgFlags;
4021            }
4022        }
4023        return 0;
4024    }
4025
4026    @Override
4027    public int getPrivateFlagsForUid(int uid) {
4028        synchronized (mPackages) {
4029            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4030            if (obj instanceof SharedUserSetting) {
4031                final SharedUserSetting sus = (SharedUserSetting) obj;
4032                return sus.pkgPrivateFlags;
4033            } else if (obj instanceof PackageSetting) {
4034                final PackageSetting ps = (PackageSetting) obj;
4035                return ps.pkgPrivateFlags;
4036            }
4037        }
4038        return 0;
4039    }
4040
4041    @Override
4042    public boolean isUidPrivileged(int uid) {
4043        uid = UserHandle.getAppId(uid);
4044        // reader
4045        synchronized (mPackages) {
4046            Object obj = mSettings.getUserIdLPr(uid);
4047            if (obj instanceof SharedUserSetting) {
4048                final SharedUserSetting sus = (SharedUserSetting) obj;
4049                final Iterator<PackageSetting> it = sus.packages.iterator();
4050                while (it.hasNext()) {
4051                    if (it.next().isPrivileged()) {
4052                        return true;
4053                    }
4054                }
4055            } else if (obj instanceof PackageSetting) {
4056                final PackageSetting ps = (PackageSetting) obj;
4057                return ps.isPrivileged();
4058            }
4059        }
4060        return false;
4061    }
4062
4063    @Override
4064    public String[] getAppOpPermissionPackages(String permissionName) {
4065        synchronized (mPackages) {
4066            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4067            if (pkgs == null) {
4068                return null;
4069            }
4070            return pkgs.toArray(new String[pkgs.size()]);
4071        }
4072    }
4073
4074    @Override
4075    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4076            int flags, int userId) {
4077        if (!sUserManager.exists(userId)) return null;
4078        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4079        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4080        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4081    }
4082
4083    @Override
4084    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4085            IntentFilter filter, int match, ComponentName activity) {
4086        final int userId = UserHandle.getCallingUserId();
4087        if (DEBUG_PREFERRED) {
4088            Log.v(TAG, "setLastChosenActivity intent=" + intent
4089                + " resolvedType=" + resolvedType
4090                + " flags=" + flags
4091                + " filter=" + filter
4092                + " match=" + match
4093                + " activity=" + activity);
4094            filter.dump(new PrintStreamPrinter(System.out), "    ");
4095        }
4096        intent.setComponent(null);
4097        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4098        // Find any earlier preferred or last chosen entries and nuke them
4099        findPreferredActivity(intent, resolvedType,
4100                flags, query, 0, false, true, false, userId);
4101        // Add the new activity as the last chosen for this filter
4102        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4103                "Setting last chosen");
4104    }
4105
4106    @Override
4107    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4108        final int userId = UserHandle.getCallingUserId();
4109        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4110        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4111        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4112                false, false, false, userId);
4113    }
4114
4115    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4116            int flags, List<ResolveInfo> query, int userId) {
4117        if (query != null) {
4118            final int N = query.size();
4119            if (N == 1) {
4120                return query.get(0);
4121            } else if (N > 1) {
4122                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4123                // If there is more than one activity with the same priority,
4124                // then let the user decide between them.
4125                ResolveInfo r0 = query.get(0);
4126                ResolveInfo r1 = query.get(1);
4127                if (DEBUG_INTENT_MATCHING || debug) {
4128                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4129                            + r1.activityInfo.name + "=" + r1.priority);
4130                }
4131                // If the first activity has a higher priority, or a different
4132                // default, then it is always desireable to pick it.
4133                if (r0.priority != r1.priority
4134                        || r0.preferredOrder != r1.preferredOrder
4135                        || r0.isDefault != r1.isDefault) {
4136                    return query.get(0);
4137                }
4138                // If we have saved a preference for a preferred activity for
4139                // this Intent, use that.
4140                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4141                        flags, query, r0.priority, true, false, debug, userId);
4142                if (ri != null) {
4143                    return ri;
4144                }
4145                if (userId != 0) {
4146                    ri = new ResolveInfo(mResolveInfo);
4147                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4148                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4149                            ri.activityInfo.applicationInfo);
4150                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4151                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4152                    return ri;
4153                }
4154                return mResolveInfo;
4155            }
4156        }
4157        return null;
4158    }
4159
4160    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4161            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4162        final int N = query.size();
4163        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4164                .get(userId);
4165        // Get the list of persistent preferred activities that handle the intent
4166        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4167        List<PersistentPreferredActivity> pprefs = ppir != null
4168                ? ppir.queryIntent(intent, resolvedType,
4169                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4170                : null;
4171        if (pprefs != null && pprefs.size() > 0) {
4172            final int M = pprefs.size();
4173            for (int i=0; i<M; i++) {
4174                final PersistentPreferredActivity ppa = pprefs.get(i);
4175                if (DEBUG_PREFERRED || debug) {
4176                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4177                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4178                            + "\n  component=" + ppa.mComponent);
4179                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4180                }
4181                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4182                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4183                if (DEBUG_PREFERRED || debug) {
4184                    Slog.v(TAG, "Found persistent preferred activity:");
4185                    if (ai != null) {
4186                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4187                    } else {
4188                        Slog.v(TAG, "  null");
4189                    }
4190                }
4191                if (ai == null) {
4192                    // This previously registered persistent preferred activity
4193                    // component is no longer known. Ignore it and do NOT remove it.
4194                    continue;
4195                }
4196                for (int j=0; j<N; j++) {
4197                    final ResolveInfo ri = query.get(j);
4198                    if (!ri.activityInfo.applicationInfo.packageName
4199                            .equals(ai.applicationInfo.packageName)) {
4200                        continue;
4201                    }
4202                    if (!ri.activityInfo.name.equals(ai.name)) {
4203                        continue;
4204                    }
4205                    //  Found a persistent preference that can handle the intent.
4206                    if (DEBUG_PREFERRED || debug) {
4207                        Slog.v(TAG, "Returning persistent preferred activity: " +
4208                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4209                    }
4210                    return ri;
4211                }
4212            }
4213        }
4214        return null;
4215    }
4216
4217    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4218            List<ResolveInfo> query, int priority, boolean always,
4219            boolean removeMatches, boolean debug, int userId) {
4220        if (!sUserManager.exists(userId)) return null;
4221        // writer
4222        synchronized (mPackages) {
4223            if (intent.getSelector() != null) {
4224                intent = intent.getSelector();
4225            }
4226            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4227
4228            // Try to find a matching persistent preferred activity.
4229            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4230                    debug, userId);
4231
4232            // If a persistent preferred activity matched, use it.
4233            if (pri != null) {
4234                return pri;
4235            }
4236
4237            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4238            // Get the list of preferred activities that handle the intent
4239            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4240            List<PreferredActivity> prefs = pir != null
4241                    ? pir.queryIntent(intent, resolvedType,
4242                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4243                    : null;
4244            if (prefs != null && prefs.size() > 0) {
4245                boolean changed = false;
4246                try {
4247                    // First figure out how good the original match set is.
4248                    // We will only allow preferred activities that came
4249                    // from the same match quality.
4250                    int match = 0;
4251
4252                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4253
4254                    final int N = query.size();
4255                    for (int j=0; j<N; j++) {
4256                        final ResolveInfo ri = query.get(j);
4257                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4258                                + ": 0x" + Integer.toHexString(match));
4259                        if (ri.match > match) {
4260                            match = ri.match;
4261                        }
4262                    }
4263
4264                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4265                            + Integer.toHexString(match));
4266
4267                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4268                    final int M = prefs.size();
4269                    for (int i=0; i<M; i++) {
4270                        final PreferredActivity pa = prefs.get(i);
4271                        if (DEBUG_PREFERRED || debug) {
4272                            Slog.v(TAG, "Checking PreferredActivity ds="
4273                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4274                                    + "\n  component=" + pa.mPref.mComponent);
4275                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4276                        }
4277                        if (pa.mPref.mMatch != match) {
4278                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4279                                    + Integer.toHexString(pa.mPref.mMatch));
4280                            continue;
4281                        }
4282                        // If it's not an "always" type preferred activity and that's what we're
4283                        // looking for, skip it.
4284                        if (always && !pa.mPref.mAlways) {
4285                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4286                            continue;
4287                        }
4288                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4289                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4290                        if (DEBUG_PREFERRED || debug) {
4291                            Slog.v(TAG, "Found preferred activity:");
4292                            if (ai != null) {
4293                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4294                            } else {
4295                                Slog.v(TAG, "  null");
4296                            }
4297                        }
4298                        if (ai == null) {
4299                            // This previously registered preferred activity
4300                            // component is no longer known.  Most likely an update
4301                            // to the app was installed and in the new version this
4302                            // component no longer exists.  Clean it up by removing
4303                            // it from the preferred activities list, and skip it.
4304                            Slog.w(TAG, "Removing dangling preferred activity: "
4305                                    + pa.mPref.mComponent);
4306                            pir.removeFilter(pa);
4307                            changed = true;
4308                            continue;
4309                        }
4310                        for (int j=0; j<N; j++) {
4311                            final ResolveInfo ri = query.get(j);
4312                            if (!ri.activityInfo.applicationInfo.packageName
4313                                    .equals(ai.applicationInfo.packageName)) {
4314                                continue;
4315                            }
4316                            if (!ri.activityInfo.name.equals(ai.name)) {
4317                                continue;
4318                            }
4319
4320                            if (removeMatches) {
4321                                pir.removeFilter(pa);
4322                                changed = true;
4323                                if (DEBUG_PREFERRED) {
4324                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4325                                }
4326                                break;
4327                            }
4328
4329                            // Okay we found a previously set preferred or last chosen app.
4330                            // If the result set is different from when this
4331                            // was created, we need to clear it and re-ask the
4332                            // user their preference, if we're looking for an "always" type entry.
4333                            if (always && !pa.mPref.sameSet(query)) {
4334                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4335                                        + intent + " type " + resolvedType);
4336                                if (DEBUG_PREFERRED) {
4337                                    Slog.v(TAG, "Removing preferred activity since set changed "
4338                                            + pa.mPref.mComponent);
4339                                }
4340                                pir.removeFilter(pa);
4341                                // Re-add the filter as a "last chosen" entry (!always)
4342                                PreferredActivity lastChosen = new PreferredActivity(
4343                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4344                                pir.addFilter(lastChosen);
4345                                changed = true;
4346                                return null;
4347                            }
4348
4349                            // Yay! Either the set matched or we're looking for the last chosen
4350                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4351                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4352                            return ri;
4353                        }
4354                    }
4355                } finally {
4356                    if (changed) {
4357                        if (DEBUG_PREFERRED) {
4358                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4359                        }
4360                        scheduleWritePackageRestrictionsLocked(userId);
4361                    }
4362                }
4363            }
4364        }
4365        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4366        return null;
4367    }
4368
4369    /*
4370     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4371     */
4372    @Override
4373    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4374            int targetUserId) {
4375        mContext.enforceCallingOrSelfPermission(
4376                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4377        List<CrossProfileIntentFilter> matches =
4378                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4379        if (matches != null) {
4380            int size = matches.size();
4381            for (int i = 0; i < size; i++) {
4382                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4383            }
4384        }
4385        if (hasWebURI(intent)) {
4386            // cross-profile app linking works only towards the parent.
4387            final UserInfo parent = getProfileParent(sourceUserId);
4388            synchronized(mPackages) {
4389                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4390                        parent.id) != null;
4391            }
4392        }
4393        return false;
4394    }
4395
4396    private UserInfo getProfileParent(int userId) {
4397        final long identity = Binder.clearCallingIdentity();
4398        try {
4399            return sUserManager.getProfileParent(userId);
4400        } finally {
4401            Binder.restoreCallingIdentity(identity);
4402        }
4403    }
4404
4405    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4406            String resolvedType, int userId) {
4407        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4408        if (resolver != null) {
4409            return resolver.queryIntent(intent, resolvedType, false, userId);
4410        }
4411        return null;
4412    }
4413
4414    @Override
4415    public List<ResolveInfo> queryIntentActivities(Intent intent,
4416            String resolvedType, int flags, int userId) {
4417        if (!sUserManager.exists(userId)) return Collections.emptyList();
4418        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4419        ComponentName comp = intent.getComponent();
4420        if (comp == null) {
4421            if (intent.getSelector() != null) {
4422                intent = intent.getSelector();
4423                comp = intent.getComponent();
4424            }
4425        }
4426
4427        if (comp != null) {
4428            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4429            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4430            if (ai != null) {
4431                final ResolveInfo ri = new ResolveInfo();
4432                ri.activityInfo = ai;
4433                list.add(ri);
4434            }
4435            return list;
4436        }
4437
4438        // reader
4439        synchronized (mPackages) {
4440            final String pkgName = intent.getPackage();
4441            if (pkgName == null) {
4442                List<CrossProfileIntentFilter> matchingFilters =
4443                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4444                // Check for results that need to skip the current profile.
4445                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4446                        resolvedType, flags, userId);
4447                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4448                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4449                    result.add(xpResolveInfo);
4450                    return filterIfNotPrimaryUser(result, userId);
4451                }
4452
4453                // Check for results in the current profile.
4454                List<ResolveInfo> result = mActivities.queryIntent(
4455                        intent, resolvedType, flags, userId);
4456
4457                // Check for cross profile results.
4458                xpResolveInfo = queryCrossProfileIntents(
4459                        matchingFilters, intent, resolvedType, flags, userId);
4460                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4461                    result.add(xpResolveInfo);
4462                    Collections.sort(result, mResolvePrioritySorter);
4463                }
4464                result = filterIfNotPrimaryUser(result, userId);
4465                if (hasWebURI(intent)) {
4466                    CrossProfileDomainInfo xpDomainInfo = null;
4467                    final UserInfo parent = getProfileParent(userId);
4468                    if (parent != null) {
4469                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4470                                flags, userId, parent.id);
4471                    }
4472                    if (xpDomainInfo != null) {
4473                        if (xpResolveInfo != null) {
4474                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4475                            // in the result.
4476                            result.remove(xpResolveInfo);
4477                        }
4478                        if (result.size() == 0) {
4479                            result.add(xpDomainInfo.resolveInfo);
4480                            return result;
4481                        }
4482                    } else if (result.size() <= 1) {
4483                        return result;
4484                    }
4485                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4486                            xpDomainInfo);
4487                    Collections.sort(result, mResolvePrioritySorter);
4488                }
4489                return result;
4490            }
4491            final PackageParser.Package pkg = mPackages.get(pkgName);
4492            if (pkg != null) {
4493                return filterIfNotPrimaryUser(
4494                        mActivities.queryIntentForPackage(
4495                                intent, resolvedType, flags, pkg.activities, userId),
4496                        userId);
4497            }
4498            return new ArrayList<ResolveInfo>();
4499        }
4500    }
4501
4502    private static class CrossProfileDomainInfo {
4503        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4504        ResolveInfo resolveInfo;
4505        /* Best domain verification status of the activities found in the other profile */
4506        int bestDomainVerificationStatus;
4507    }
4508
4509    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4510            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4511        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4512                sourceUserId)) {
4513            return null;
4514        }
4515        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4516                resolvedType, flags, parentUserId);
4517
4518        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4519            return null;
4520        }
4521        CrossProfileDomainInfo result = null;
4522        int size = resultTargetUser.size();
4523        for (int i = 0; i < size; i++) {
4524            ResolveInfo riTargetUser = resultTargetUser.get(i);
4525            // Intent filter verification is only for filters that specify a host. So don't return
4526            // those that handle all web uris.
4527            if (riTargetUser.handleAllWebDataURI) {
4528                continue;
4529            }
4530            String packageName = riTargetUser.activityInfo.packageName;
4531            PackageSetting ps = mSettings.mPackages.get(packageName);
4532            if (ps == null) {
4533                continue;
4534            }
4535            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4536            if (result == null) {
4537                result = new CrossProfileDomainInfo();
4538                result.resolveInfo =
4539                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4540                result.bestDomainVerificationStatus = status;
4541            } else {
4542                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4543                        result.bestDomainVerificationStatus);
4544            }
4545        }
4546        return result;
4547    }
4548
4549    /**
4550     * Verification statuses are ordered from the worse to the best, except for
4551     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4552     */
4553    private int bestDomainVerificationStatus(int status1, int status2) {
4554        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4555            return status2;
4556        }
4557        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4558            return status1;
4559        }
4560        return (int) MathUtils.max(status1, status2);
4561    }
4562
4563    private boolean isUserEnabled(int userId) {
4564        long callingId = Binder.clearCallingIdentity();
4565        try {
4566            UserInfo userInfo = sUserManager.getUserInfo(userId);
4567            return userInfo != null && userInfo.isEnabled();
4568        } finally {
4569            Binder.restoreCallingIdentity(callingId);
4570        }
4571    }
4572
4573    /**
4574     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4575     *
4576     * @return filtered list
4577     */
4578    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4579        if (userId == UserHandle.USER_OWNER) {
4580            return resolveInfos;
4581        }
4582        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4583            ResolveInfo info = resolveInfos.get(i);
4584            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4585                resolveInfos.remove(i);
4586            }
4587        }
4588        return resolveInfos;
4589    }
4590
4591    private static boolean hasWebURI(Intent intent) {
4592        if (intent.getData() == null) {
4593            return false;
4594        }
4595        final String scheme = intent.getScheme();
4596        if (TextUtils.isEmpty(scheme)) {
4597            return false;
4598        }
4599        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4600    }
4601
4602    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4603            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4604        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4605            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4606                    candidates.size());
4607        }
4608
4609        final int userId = UserHandle.getCallingUserId();
4610        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4611        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4612        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4613        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4614        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4615
4616        synchronized (mPackages) {
4617            final int count = candidates.size();
4618            // First, try to use linked apps. Partition the candidates into four lists:
4619            // one for the final results, one for the "do not use ever", one for "undefined status"
4620            // and finally one for "browser app type".
4621            for (int n=0; n<count; n++) {
4622                ResolveInfo info = candidates.get(n);
4623                String packageName = info.activityInfo.packageName;
4624                PackageSetting ps = mSettings.mPackages.get(packageName);
4625                if (ps != null) {
4626                    // Add to the special match all list (Browser use case)
4627                    if (info.handleAllWebDataURI) {
4628                        matchAllList.add(info);
4629                        continue;
4630                    }
4631                    // Try to get the status from User settings first
4632                    int status = getDomainVerificationStatusLPr(ps, userId);
4633                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4634                        if (DEBUG_DOMAIN_VERIFICATION) {
4635                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4636                        }
4637                        alwaysList.add(info);
4638                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4639                        if (DEBUG_DOMAIN_VERIFICATION) {
4640                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4641                        }
4642                        neverList.add(info);
4643                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4644                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4645                        if (DEBUG_DOMAIN_VERIFICATION) {
4646                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4647                        }
4648                        undefinedList.add(info);
4649                    }
4650                }
4651            }
4652            // First try to add the "always" resolution for the current user if there is any
4653            if (alwaysList.size() > 0) {
4654                result.addAll(alwaysList);
4655            // if there is an "always" for the parent user, add it.
4656            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4657                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4658                result.add(xpDomainInfo.resolveInfo);
4659            } else {
4660                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4661                result.addAll(undefinedList);
4662                if (xpDomainInfo != null && (
4663                        xpDomainInfo.bestDomainVerificationStatus
4664                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4665                        || xpDomainInfo.bestDomainVerificationStatus
4666                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4667                    result.add(xpDomainInfo.resolveInfo);
4668                }
4669                // Also add Browsers (all of them or only the default one)
4670                if ((flags & MATCH_ALL) != 0) {
4671                    result.addAll(matchAllList);
4672                } else {
4673                    // Try to add the Default Browser if we can
4674                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4675                            UserHandle.myUserId());
4676                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4677                        boolean defaultBrowserFound = false;
4678                        final int browserCount = matchAllList.size();
4679                        for (int n=0; n<browserCount; n++) {
4680                            ResolveInfo browser = matchAllList.get(n);
4681                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4682                                result.add(browser);
4683                                defaultBrowserFound = true;
4684                                break;
4685                            }
4686                        }
4687                        if (!defaultBrowserFound) {
4688                            result.addAll(matchAllList);
4689                        }
4690                    } else {
4691                        result.addAll(matchAllList);
4692                    }
4693                }
4694
4695                // If there is nothing selected, add all candidates and remove the ones that the user
4696                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4697                if (result.size() == 0) {
4698                    result.addAll(candidates);
4699                    result.removeAll(neverList);
4700                }
4701            }
4702        }
4703        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4704            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4705                    result.size());
4706            for (ResolveInfo info : result) {
4707                Slog.v(TAG, "  + " + info.activityInfo);
4708            }
4709        }
4710        return result;
4711    }
4712
4713    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4714        int status = ps.getDomainVerificationStatusForUser(userId);
4715        // if none available, get the master status
4716        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4717            if (ps.getIntentFilterVerificationInfo() != null) {
4718                status = ps.getIntentFilterVerificationInfo().getStatus();
4719            }
4720        }
4721        return status;
4722    }
4723
4724    private ResolveInfo querySkipCurrentProfileIntents(
4725            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4726            int flags, int sourceUserId) {
4727        if (matchingFilters != null) {
4728            int size = matchingFilters.size();
4729            for (int i = 0; i < size; i ++) {
4730                CrossProfileIntentFilter filter = matchingFilters.get(i);
4731                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4732                    // Checking if there are activities in the target user that can handle the
4733                    // intent.
4734                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4735                            flags, sourceUserId);
4736                    if (resolveInfo != null) {
4737                        return resolveInfo;
4738                    }
4739                }
4740            }
4741        }
4742        return null;
4743    }
4744
4745    // Return matching ResolveInfo if any for skip current profile intent filters.
4746    private ResolveInfo queryCrossProfileIntents(
4747            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4748            int flags, int sourceUserId) {
4749        if (matchingFilters != null) {
4750            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4751            // match the same intent. For performance reasons, it is better not to
4752            // run queryIntent twice for the same userId
4753            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4754            int size = matchingFilters.size();
4755            for (int i = 0; i < size; i++) {
4756                CrossProfileIntentFilter filter = matchingFilters.get(i);
4757                int targetUserId = filter.getTargetUserId();
4758                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4759                        && !alreadyTriedUserIds.get(targetUserId)) {
4760                    // Checking if there are activities in the target user that can handle the
4761                    // intent.
4762                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4763                            flags, sourceUserId);
4764                    if (resolveInfo != null) return resolveInfo;
4765                    alreadyTriedUserIds.put(targetUserId, true);
4766                }
4767            }
4768        }
4769        return null;
4770    }
4771
4772    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4773            String resolvedType, int flags, int sourceUserId) {
4774        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4775                resolvedType, flags, filter.getTargetUserId());
4776        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4777            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4778        }
4779        return null;
4780    }
4781
4782    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4783            int sourceUserId, int targetUserId) {
4784        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4785        String className;
4786        if (targetUserId == UserHandle.USER_OWNER) {
4787            className = FORWARD_INTENT_TO_USER_OWNER;
4788        } else {
4789            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4790        }
4791        ComponentName forwardingActivityComponentName = new ComponentName(
4792                mAndroidApplication.packageName, className);
4793        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4794                sourceUserId);
4795        if (targetUserId == UserHandle.USER_OWNER) {
4796            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4797            forwardingResolveInfo.noResourceId = true;
4798        }
4799        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4800        forwardingResolveInfo.priority = 0;
4801        forwardingResolveInfo.preferredOrder = 0;
4802        forwardingResolveInfo.match = 0;
4803        forwardingResolveInfo.isDefault = true;
4804        forwardingResolveInfo.filter = filter;
4805        forwardingResolveInfo.targetUserId = targetUserId;
4806        return forwardingResolveInfo;
4807    }
4808
4809    @Override
4810    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4811            Intent[] specifics, String[] specificTypes, Intent intent,
4812            String resolvedType, int flags, int userId) {
4813        if (!sUserManager.exists(userId)) return Collections.emptyList();
4814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4815                false, "query intent activity options");
4816        final String resultsAction = intent.getAction();
4817
4818        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4819                | PackageManager.GET_RESOLVED_FILTER, userId);
4820
4821        if (DEBUG_INTENT_MATCHING) {
4822            Log.v(TAG, "Query " + intent + ": " + results);
4823        }
4824
4825        int specificsPos = 0;
4826        int N;
4827
4828        // todo: note that the algorithm used here is O(N^2).  This
4829        // isn't a problem in our current environment, but if we start running
4830        // into situations where we have more than 5 or 10 matches then this
4831        // should probably be changed to something smarter...
4832
4833        // First we go through and resolve each of the specific items
4834        // that were supplied, taking care of removing any corresponding
4835        // duplicate items in the generic resolve list.
4836        if (specifics != null) {
4837            for (int i=0; i<specifics.length; i++) {
4838                final Intent sintent = specifics[i];
4839                if (sintent == null) {
4840                    continue;
4841                }
4842
4843                if (DEBUG_INTENT_MATCHING) {
4844                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4845                }
4846
4847                String action = sintent.getAction();
4848                if (resultsAction != null && resultsAction.equals(action)) {
4849                    // If this action was explicitly requested, then don't
4850                    // remove things that have it.
4851                    action = null;
4852                }
4853
4854                ResolveInfo ri = null;
4855                ActivityInfo ai = null;
4856
4857                ComponentName comp = sintent.getComponent();
4858                if (comp == null) {
4859                    ri = resolveIntent(
4860                        sintent,
4861                        specificTypes != null ? specificTypes[i] : null,
4862                            flags, userId);
4863                    if (ri == null) {
4864                        continue;
4865                    }
4866                    if (ri == mResolveInfo) {
4867                        // ACK!  Must do something better with this.
4868                    }
4869                    ai = ri.activityInfo;
4870                    comp = new ComponentName(ai.applicationInfo.packageName,
4871                            ai.name);
4872                } else {
4873                    ai = getActivityInfo(comp, flags, userId);
4874                    if (ai == null) {
4875                        continue;
4876                    }
4877                }
4878
4879                // Look for any generic query activities that are duplicates
4880                // of this specific one, and remove them from the results.
4881                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4882                N = results.size();
4883                int j;
4884                for (j=specificsPos; j<N; j++) {
4885                    ResolveInfo sri = results.get(j);
4886                    if ((sri.activityInfo.name.equals(comp.getClassName())
4887                            && sri.activityInfo.applicationInfo.packageName.equals(
4888                                    comp.getPackageName()))
4889                        || (action != null && sri.filter.matchAction(action))) {
4890                        results.remove(j);
4891                        if (DEBUG_INTENT_MATCHING) Log.v(
4892                            TAG, "Removing duplicate item from " + j
4893                            + " due to specific " + specificsPos);
4894                        if (ri == null) {
4895                            ri = sri;
4896                        }
4897                        j--;
4898                        N--;
4899                    }
4900                }
4901
4902                // Add this specific item to its proper place.
4903                if (ri == null) {
4904                    ri = new ResolveInfo();
4905                    ri.activityInfo = ai;
4906                }
4907                results.add(specificsPos, ri);
4908                ri.specificIndex = i;
4909                specificsPos++;
4910            }
4911        }
4912
4913        // Now we go through the remaining generic results and remove any
4914        // duplicate actions that are found here.
4915        N = results.size();
4916        for (int i=specificsPos; i<N-1; i++) {
4917            final ResolveInfo rii = results.get(i);
4918            if (rii.filter == null) {
4919                continue;
4920            }
4921
4922            // Iterate over all of the actions of this result's intent
4923            // filter...  typically this should be just one.
4924            final Iterator<String> it = rii.filter.actionsIterator();
4925            if (it == null) {
4926                continue;
4927            }
4928            while (it.hasNext()) {
4929                final String action = it.next();
4930                if (resultsAction != null && resultsAction.equals(action)) {
4931                    // If this action was explicitly requested, then don't
4932                    // remove things that have it.
4933                    continue;
4934                }
4935                for (int j=i+1; j<N; j++) {
4936                    final ResolveInfo rij = results.get(j);
4937                    if (rij.filter != null && rij.filter.hasAction(action)) {
4938                        results.remove(j);
4939                        if (DEBUG_INTENT_MATCHING) Log.v(
4940                            TAG, "Removing duplicate item from " + j
4941                            + " due to action " + action + " at " + i);
4942                        j--;
4943                        N--;
4944                    }
4945                }
4946            }
4947
4948            // If the caller didn't request filter information, drop it now
4949            // so we don't have to marshall/unmarshall it.
4950            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4951                rii.filter = null;
4952            }
4953        }
4954
4955        // Filter out the caller activity if so requested.
4956        if (caller != null) {
4957            N = results.size();
4958            for (int i=0; i<N; i++) {
4959                ActivityInfo ainfo = results.get(i).activityInfo;
4960                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4961                        && caller.getClassName().equals(ainfo.name)) {
4962                    results.remove(i);
4963                    break;
4964                }
4965            }
4966        }
4967
4968        // If the caller didn't request filter information,
4969        // drop them now so we don't have to
4970        // marshall/unmarshall it.
4971        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4972            N = results.size();
4973            for (int i=0; i<N; i++) {
4974                results.get(i).filter = null;
4975            }
4976        }
4977
4978        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4979        return results;
4980    }
4981
4982    @Override
4983    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4984            int userId) {
4985        if (!sUserManager.exists(userId)) return Collections.emptyList();
4986        ComponentName comp = intent.getComponent();
4987        if (comp == null) {
4988            if (intent.getSelector() != null) {
4989                intent = intent.getSelector();
4990                comp = intent.getComponent();
4991            }
4992        }
4993        if (comp != null) {
4994            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4995            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4996            if (ai != null) {
4997                ResolveInfo ri = new ResolveInfo();
4998                ri.activityInfo = ai;
4999                list.add(ri);
5000            }
5001            return list;
5002        }
5003
5004        // reader
5005        synchronized (mPackages) {
5006            String pkgName = intent.getPackage();
5007            if (pkgName == null) {
5008                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5009            }
5010            final PackageParser.Package pkg = mPackages.get(pkgName);
5011            if (pkg != null) {
5012                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5013                        userId);
5014            }
5015            return null;
5016        }
5017    }
5018
5019    @Override
5020    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5021        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5022        if (!sUserManager.exists(userId)) return null;
5023        if (query != null) {
5024            if (query.size() >= 1) {
5025                // If there is more than one service with the same priority,
5026                // just arbitrarily pick the first one.
5027                return query.get(0);
5028            }
5029        }
5030        return null;
5031    }
5032
5033    @Override
5034    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5035            int userId) {
5036        if (!sUserManager.exists(userId)) return Collections.emptyList();
5037        ComponentName comp = intent.getComponent();
5038        if (comp == null) {
5039            if (intent.getSelector() != null) {
5040                intent = intent.getSelector();
5041                comp = intent.getComponent();
5042            }
5043        }
5044        if (comp != null) {
5045            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5046            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5047            if (si != null) {
5048                final ResolveInfo ri = new ResolveInfo();
5049                ri.serviceInfo = si;
5050                list.add(ri);
5051            }
5052            return list;
5053        }
5054
5055        // reader
5056        synchronized (mPackages) {
5057            String pkgName = intent.getPackage();
5058            if (pkgName == null) {
5059                return mServices.queryIntent(intent, resolvedType, flags, userId);
5060            }
5061            final PackageParser.Package pkg = mPackages.get(pkgName);
5062            if (pkg != null) {
5063                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5064                        userId);
5065            }
5066            return null;
5067        }
5068    }
5069
5070    @Override
5071    public List<ResolveInfo> queryIntentContentProviders(
5072            Intent intent, String resolvedType, int flags, int userId) {
5073        if (!sUserManager.exists(userId)) return Collections.emptyList();
5074        ComponentName comp = intent.getComponent();
5075        if (comp == null) {
5076            if (intent.getSelector() != null) {
5077                intent = intent.getSelector();
5078                comp = intent.getComponent();
5079            }
5080        }
5081        if (comp != null) {
5082            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5083            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5084            if (pi != null) {
5085                final ResolveInfo ri = new ResolveInfo();
5086                ri.providerInfo = pi;
5087                list.add(ri);
5088            }
5089            return list;
5090        }
5091
5092        // reader
5093        synchronized (mPackages) {
5094            String pkgName = intent.getPackage();
5095            if (pkgName == null) {
5096                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5097            }
5098            final PackageParser.Package pkg = mPackages.get(pkgName);
5099            if (pkg != null) {
5100                return mProviders.queryIntentForPackage(
5101                        intent, resolvedType, flags, pkg.providers, userId);
5102            }
5103            return null;
5104        }
5105    }
5106
5107    @Override
5108    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5109        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5110
5111        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5112
5113        // writer
5114        synchronized (mPackages) {
5115            ArrayList<PackageInfo> list;
5116            if (listUninstalled) {
5117                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5118                for (PackageSetting ps : mSettings.mPackages.values()) {
5119                    PackageInfo pi;
5120                    if (ps.pkg != null) {
5121                        pi = generatePackageInfo(ps.pkg, flags, userId);
5122                    } else {
5123                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5124                    }
5125                    if (pi != null) {
5126                        list.add(pi);
5127                    }
5128                }
5129            } else {
5130                list = new ArrayList<PackageInfo>(mPackages.size());
5131                for (PackageParser.Package p : mPackages.values()) {
5132                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5133                    if (pi != null) {
5134                        list.add(pi);
5135                    }
5136                }
5137            }
5138
5139            return new ParceledListSlice<PackageInfo>(list);
5140        }
5141    }
5142
5143    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5144            String[] permissions, boolean[] tmp, int flags, int userId) {
5145        int numMatch = 0;
5146        final PermissionsState permissionsState = ps.getPermissionsState();
5147        for (int i=0; i<permissions.length; i++) {
5148            final String permission = permissions[i];
5149            if (permissionsState.hasPermission(permission, userId)) {
5150                tmp[i] = true;
5151                numMatch++;
5152            } else {
5153                tmp[i] = false;
5154            }
5155        }
5156        if (numMatch == 0) {
5157            return;
5158        }
5159        PackageInfo pi;
5160        if (ps.pkg != null) {
5161            pi = generatePackageInfo(ps.pkg, flags, userId);
5162        } else {
5163            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5164        }
5165        // The above might return null in cases of uninstalled apps or install-state
5166        // skew across users/profiles.
5167        if (pi != null) {
5168            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5169                if (numMatch == permissions.length) {
5170                    pi.requestedPermissions = permissions;
5171                } else {
5172                    pi.requestedPermissions = new String[numMatch];
5173                    numMatch = 0;
5174                    for (int i=0; i<permissions.length; i++) {
5175                        if (tmp[i]) {
5176                            pi.requestedPermissions[numMatch] = permissions[i];
5177                            numMatch++;
5178                        }
5179                    }
5180                }
5181            }
5182            list.add(pi);
5183        }
5184    }
5185
5186    @Override
5187    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5188            String[] permissions, int flags, int userId) {
5189        if (!sUserManager.exists(userId)) return null;
5190        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5191
5192        // writer
5193        synchronized (mPackages) {
5194            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5195            boolean[] tmpBools = new boolean[permissions.length];
5196            if (listUninstalled) {
5197                for (PackageSetting ps : mSettings.mPackages.values()) {
5198                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5199                }
5200            } else {
5201                for (PackageParser.Package pkg : mPackages.values()) {
5202                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5203                    if (ps != null) {
5204                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5205                                userId);
5206                    }
5207                }
5208            }
5209
5210            return new ParceledListSlice<PackageInfo>(list);
5211        }
5212    }
5213
5214    @Override
5215    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5216        if (!sUserManager.exists(userId)) return null;
5217        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5218
5219        // writer
5220        synchronized (mPackages) {
5221            ArrayList<ApplicationInfo> list;
5222            if (listUninstalled) {
5223                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5224                for (PackageSetting ps : mSettings.mPackages.values()) {
5225                    ApplicationInfo ai;
5226                    if (ps.pkg != null) {
5227                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5228                                ps.readUserState(userId), userId);
5229                    } else {
5230                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5231                    }
5232                    if (ai != null) {
5233                        list.add(ai);
5234                    }
5235                }
5236            } else {
5237                list = new ArrayList<ApplicationInfo>(mPackages.size());
5238                for (PackageParser.Package p : mPackages.values()) {
5239                    if (p.mExtras != null) {
5240                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5241                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5242                        if (ai != null) {
5243                            list.add(ai);
5244                        }
5245                    }
5246                }
5247            }
5248
5249            return new ParceledListSlice<ApplicationInfo>(list);
5250        }
5251    }
5252
5253    public List<ApplicationInfo> getPersistentApplications(int flags) {
5254        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5255
5256        // reader
5257        synchronized (mPackages) {
5258            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5259            final int userId = UserHandle.getCallingUserId();
5260            while (i.hasNext()) {
5261                final PackageParser.Package p = i.next();
5262                if (p.applicationInfo != null
5263                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5264                        && (!mSafeMode || isSystemApp(p))) {
5265                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5266                    if (ps != null) {
5267                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5268                                ps.readUserState(userId), userId);
5269                        if (ai != null) {
5270                            finalList.add(ai);
5271                        }
5272                    }
5273                }
5274            }
5275        }
5276
5277        return finalList;
5278    }
5279
5280    @Override
5281    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5282        if (!sUserManager.exists(userId)) return null;
5283        // reader
5284        synchronized (mPackages) {
5285            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5286            PackageSetting ps = provider != null
5287                    ? mSettings.mPackages.get(provider.owner.packageName)
5288                    : null;
5289            return ps != null
5290                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5291                    && (!mSafeMode || (provider.info.applicationInfo.flags
5292                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5293                    ? PackageParser.generateProviderInfo(provider, flags,
5294                            ps.readUserState(userId), userId)
5295                    : null;
5296        }
5297    }
5298
5299    /**
5300     * @deprecated
5301     */
5302    @Deprecated
5303    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5304        // reader
5305        synchronized (mPackages) {
5306            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5307                    .entrySet().iterator();
5308            final int userId = UserHandle.getCallingUserId();
5309            while (i.hasNext()) {
5310                Map.Entry<String, PackageParser.Provider> entry = i.next();
5311                PackageParser.Provider p = entry.getValue();
5312                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5313
5314                if (ps != null && p.syncable
5315                        && (!mSafeMode || (p.info.applicationInfo.flags
5316                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5317                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5318                            ps.readUserState(userId), userId);
5319                    if (info != null) {
5320                        outNames.add(entry.getKey());
5321                        outInfo.add(info);
5322                    }
5323                }
5324            }
5325        }
5326    }
5327
5328    @Override
5329    public List<ProviderInfo> queryContentProviders(String processName,
5330            int uid, int flags) {
5331        ArrayList<ProviderInfo> finalList = null;
5332        // reader
5333        synchronized (mPackages) {
5334            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5335            final int userId = processName != null ?
5336                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5337            while (i.hasNext()) {
5338                final PackageParser.Provider p = i.next();
5339                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5340                if (ps != null && p.info.authority != null
5341                        && (processName == null
5342                                || (p.info.processName.equals(processName)
5343                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5344                        && mSettings.isEnabledLPr(p.info, flags, userId)
5345                        && (!mSafeMode
5346                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5347                    if (finalList == null) {
5348                        finalList = new ArrayList<ProviderInfo>(3);
5349                    }
5350                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5351                            ps.readUserState(userId), userId);
5352                    if (info != null) {
5353                        finalList.add(info);
5354                    }
5355                }
5356            }
5357        }
5358
5359        if (finalList != null) {
5360            Collections.sort(finalList, mProviderInitOrderSorter);
5361        }
5362
5363        return finalList;
5364    }
5365
5366    @Override
5367    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5368            int flags) {
5369        // reader
5370        synchronized (mPackages) {
5371            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5372            return PackageParser.generateInstrumentationInfo(i, flags);
5373        }
5374    }
5375
5376    @Override
5377    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5378            int flags) {
5379        ArrayList<InstrumentationInfo> finalList =
5380            new ArrayList<InstrumentationInfo>();
5381
5382        // reader
5383        synchronized (mPackages) {
5384            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5385            while (i.hasNext()) {
5386                final PackageParser.Instrumentation p = i.next();
5387                if (targetPackage == null
5388                        || targetPackage.equals(p.info.targetPackage)) {
5389                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5390                            flags);
5391                    if (ii != null) {
5392                        finalList.add(ii);
5393                    }
5394                }
5395            }
5396        }
5397
5398        return finalList;
5399    }
5400
5401    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5402        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5403        if (overlays == null) {
5404            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5405            return;
5406        }
5407        for (PackageParser.Package opkg : overlays.values()) {
5408            // Not much to do if idmap fails: we already logged the error
5409            // and we certainly don't want to abort installation of pkg simply
5410            // because an overlay didn't fit properly. For these reasons,
5411            // ignore the return value of createIdmapForPackagePairLI.
5412            createIdmapForPackagePairLI(pkg, opkg);
5413        }
5414    }
5415
5416    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5417            PackageParser.Package opkg) {
5418        if (!opkg.mTrustedOverlay) {
5419            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5420                    opkg.baseCodePath + ": overlay not trusted");
5421            return false;
5422        }
5423        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5424        if (overlaySet == null) {
5425            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5426                    opkg.baseCodePath + " but target package has no known overlays");
5427            return false;
5428        }
5429        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5430        // TODO: generate idmap for split APKs
5431        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5432            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5433                    + opkg.baseCodePath);
5434            return false;
5435        }
5436        PackageParser.Package[] overlayArray =
5437            overlaySet.values().toArray(new PackageParser.Package[0]);
5438        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5439            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5440                return p1.mOverlayPriority - p2.mOverlayPriority;
5441            }
5442        };
5443        Arrays.sort(overlayArray, cmp);
5444
5445        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5446        int i = 0;
5447        for (PackageParser.Package p : overlayArray) {
5448            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5449        }
5450        return true;
5451    }
5452
5453    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5454        final File[] files = dir.listFiles();
5455        if (ArrayUtils.isEmpty(files)) {
5456            Log.d(TAG, "No files in app dir " + dir);
5457            return;
5458        }
5459
5460        if (DEBUG_PACKAGE_SCANNING) {
5461            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5462                    + " flags=0x" + Integer.toHexString(parseFlags));
5463        }
5464
5465        for (File file : files) {
5466            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5467                    && !PackageInstallerService.isStageName(file.getName());
5468            if (!isPackage) {
5469                // Ignore entries which are not packages
5470                continue;
5471            }
5472            try {
5473                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5474                        scanFlags, currentTime, null);
5475            } catch (PackageManagerException e) {
5476                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5477
5478                // Delete invalid userdata apps
5479                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5480                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5481                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5482                    if (file.isDirectory()) {
5483                        mInstaller.rmPackageDir(file.getAbsolutePath());
5484                    } else {
5485                        file.delete();
5486                    }
5487                }
5488            }
5489        }
5490    }
5491
5492    private static File getSettingsProblemFile() {
5493        File dataDir = Environment.getDataDirectory();
5494        File systemDir = new File(dataDir, "system");
5495        File fname = new File(systemDir, "uiderrors.txt");
5496        return fname;
5497    }
5498
5499    static void reportSettingsProblem(int priority, String msg) {
5500        logCriticalInfo(priority, msg);
5501    }
5502
5503    static void logCriticalInfo(int priority, String msg) {
5504        Slog.println(priority, TAG, msg);
5505        EventLogTags.writePmCriticalInfo(msg);
5506        try {
5507            File fname = getSettingsProblemFile();
5508            FileOutputStream out = new FileOutputStream(fname, true);
5509            PrintWriter pw = new FastPrintWriter(out);
5510            SimpleDateFormat formatter = new SimpleDateFormat();
5511            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5512            pw.println(dateString + ": " + msg);
5513            pw.close();
5514            FileUtils.setPermissions(
5515                    fname.toString(),
5516                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5517                    -1, -1);
5518        } catch (java.io.IOException e) {
5519        }
5520    }
5521
5522    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5523            PackageParser.Package pkg, File srcFile, int parseFlags)
5524            throws PackageManagerException {
5525        if (ps != null
5526                && ps.codePath.equals(srcFile)
5527                && ps.timeStamp == srcFile.lastModified()
5528                && !isCompatSignatureUpdateNeeded(pkg)
5529                && !isRecoverSignatureUpdateNeeded(pkg)) {
5530            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5531            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5532            ArraySet<PublicKey> signingKs;
5533            synchronized (mPackages) {
5534                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5535            }
5536            if (ps.signatures.mSignatures != null
5537                    && ps.signatures.mSignatures.length != 0
5538                    && signingKs != null) {
5539                // Optimization: reuse the existing cached certificates
5540                // if the package appears to be unchanged.
5541                pkg.mSignatures = ps.signatures.mSignatures;
5542                pkg.mSigningKeys = signingKs;
5543                return;
5544            }
5545
5546            Slog.w(TAG, "PackageSetting for " + ps.name
5547                    + " is missing signatures.  Collecting certs again to recover them.");
5548        } else {
5549            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5550        }
5551
5552        try {
5553            pp.collectCertificates(pkg, parseFlags);
5554            pp.collectManifestDigest(pkg);
5555        } catch (PackageParserException e) {
5556            throw PackageManagerException.from(e);
5557        }
5558    }
5559
5560    /*
5561     *  Scan a package and return the newly parsed package.
5562     *  Returns null in case of errors and the error code is stored in mLastScanError
5563     */
5564    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5565            long currentTime, UserHandle user) throws PackageManagerException {
5566        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5567        parseFlags |= mDefParseFlags;
5568        PackageParser pp = new PackageParser();
5569        pp.setSeparateProcesses(mSeparateProcesses);
5570        pp.setOnlyCoreApps(mOnlyCore);
5571        pp.setDisplayMetrics(mMetrics);
5572
5573        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5574            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5575        }
5576
5577        final PackageParser.Package pkg;
5578        try {
5579            pkg = pp.parsePackage(scanFile, parseFlags);
5580        } catch (PackageParserException e) {
5581            throw PackageManagerException.from(e);
5582        }
5583
5584        PackageSetting ps = null;
5585        PackageSetting updatedPkg;
5586        // reader
5587        synchronized (mPackages) {
5588            // Look to see if we already know about this package.
5589            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5590            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5591                // This package has been renamed to its original name.  Let's
5592                // use that.
5593                ps = mSettings.peekPackageLPr(oldName);
5594            }
5595            // If there was no original package, see one for the real package name.
5596            if (ps == null) {
5597                ps = mSettings.peekPackageLPr(pkg.packageName);
5598            }
5599            // Check to see if this package could be hiding/updating a system
5600            // package.  Must look for it either under the original or real
5601            // package name depending on our state.
5602            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5603            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5604        }
5605        boolean updatedPkgBetter = false;
5606        // First check if this is a system package that may involve an update
5607        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5608            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5609            // it needs to drop FLAG_PRIVILEGED.
5610            if (locationIsPrivileged(scanFile)) {
5611                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5612            } else {
5613                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5614            }
5615
5616            if (ps != null && !ps.codePath.equals(scanFile)) {
5617                // The path has changed from what was last scanned...  check the
5618                // version of the new path against what we have stored to determine
5619                // what to do.
5620                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5621                if (pkg.mVersionCode <= ps.versionCode) {
5622                    // The system package has been updated and the code path does not match
5623                    // Ignore entry. Skip it.
5624                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5625                            + " ignored: updated version " + ps.versionCode
5626                            + " better than this " + pkg.mVersionCode);
5627                    if (!updatedPkg.codePath.equals(scanFile)) {
5628                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5629                                + ps.name + " changing from " + updatedPkg.codePathString
5630                                + " to " + scanFile);
5631                        updatedPkg.codePath = scanFile;
5632                        updatedPkg.codePathString = scanFile.toString();
5633                        updatedPkg.resourcePath = scanFile;
5634                        updatedPkg.resourcePathString = scanFile.toString();
5635                    }
5636                    updatedPkg.pkg = pkg;
5637                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5638                } else {
5639                    // The current app on the system partition is better than
5640                    // what we have updated to on the data partition; switch
5641                    // back to the system partition version.
5642                    // At this point, its safely assumed that package installation for
5643                    // apps in system partition will go through. If not there won't be a working
5644                    // version of the app
5645                    // writer
5646                    synchronized (mPackages) {
5647                        // Just remove the loaded entries from package lists.
5648                        mPackages.remove(ps.name);
5649                    }
5650
5651                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5652                            + " reverting from " + ps.codePathString
5653                            + ": new version " + pkg.mVersionCode
5654                            + " better than installed " + ps.versionCode);
5655
5656                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5657                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5658                    synchronized (mInstallLock) {
5659                        args.cleanUpResourcesLI();
5660                    }
5661                    synchronized (mPackages) {
5662                        mSettings.enableSystemPackageLPw(ps.name);
5663                    }
5664                    updatedPkgBetter = true;
5665                }
5666            }
5667        }
5668
5669        if (updatedPkg != null) {
5670            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5671            // initially
5672            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5673
5674            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5675            // flag set initially
5676            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5677                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5678            }
5679        }
5680
5681        // Verify certificates against what was last scanned
5682        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5683
5684        /*
5685         * A new system app appeared, but we already had a non-system one of the
5686         * same name installed earlier.
5687         */
5688        boolean shouldHideSystemApp = false;
5689        if (updatedPkg == null && ps != null
5690                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5691            /*
5692             * Check to make sure the signatures match first. If they don't,
5693             * wipe the installed application and its data.
5694             */
5695            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5696                    != PackageManager.SIGNATURE_MATCH) {
5697                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5698                        + " signatures don't match existing userdata copy; removing");
5699                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5700                ps = null;
5701            } else {
5702                /*
5703                 * If the newly-added system app is an older version than the
5704                 * already installed version, hide it. It will be scanned later
5705                 * and re-added like an update.
5706                 */
5707                if (pkg.mVersionCode <= ps.versionCode) {
5708                    shouldHideSystemApp = true;
5709                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5710                            + " but new version " + pkg.mVersionCode + " better than installed "
5711                            + ps.versionCode + "; hiding system");
5712                } else {
5713                    /*
5714                     * The newly found system app is a newer version that the
5715                     * one previously installed. Simply remove the
5716                     * already-installed application and replace it with our own
5717                     * while keeping the application data.
5718                     */
5719                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5720                            + " reverting from " + ps.codePathString + ": new version "
5721                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5722                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5723                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5724                    synchronized (mInstallLock) {
5725                        args.cleanUpResourcesLI();
5726                    }
5727                }
5728            }
5729        }
5730
5731        // The apk is forward locked (not public) if its code and resources
5732        // are kept in different files. (except for app in either system or
5733        // vendor path).
5734        // TODO grab this value from PackageSettings
5735        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5736            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5737                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5738            }
5739        }
5740
5741        // TODO: extend to support forward-locked splits
5742        String resourcePath = null;
5743        String baseResourcePath = null;
5744        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5745            if (ps != null && ps.resourcePathString != null) {
5746                resourcePath = ps.resourcePathString;
5747                baseResourcePath = ps.resourcePathString;
5748            } else {
5749                // Should not happen at all. Just log an error.
5750                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5751            }
5752        } else {
5753            resourcePath = pkg.codePath;
5754            baseResourcePath = pkg.baseCodePath;
5755        }
5756
5757        // Set application objects path explicitly.
5758        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5759        pkg.applicationInfo.setCodePath(pkg.codePath);
5760        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5761        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5762        pkg.applicationInfo.setResourcePath(resourcePath);
5763        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5764        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5765
5766        // Note that we invoke the following method only if we are about to unpack an application
5767        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5768                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5769
5770        /*
5771         * If the system app should be overridden by a previously installed
5772         * data, hide the system app now and let the /data/app scan pick it up
5773         * again.
5774         */
5775        if (shouldHideSystemApp) {
5776            synchronized (mPackages) {
5777                /*
5778                 * We have to grant systems permissions before we hide, because
5779                 * grantPermissions will assume the package update is trying to
5780                 * expand its permissions.
5781                 */
5782                grantPermissionsLPw(pkg, true, pkg.packageName);
5783                mSettings.disableSystemPackageLPw(pkg.packageName);
5784            }
5785        }
5786
5787        return scannedPkg;
5788    }
5789
5790    private static String fixProcessName(String defProcessName,
5791            String processName, int uid) {
5792        if (processName == null) {
5793            return defProcessName;
5794        }
5795        return processName;
5796    }
5797
5798    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5799            throws PackageManagerException {
5800        if (pkgSetting.signatures.mSignatures != null) {
5801            // Already existing package. Make sure signatures match
5802            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5803                    == PackageManager.SIGNATURE_MATCH;
5804            if (!match) {
5805                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5806                        == PackageManager.SIGNATURE_MATCH;
5807            }
5808            if (!match) {
5809                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5810                        == PackageManager.SIGNATURE_MATCH;
5811            }
5812            if (!match) {
5813                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5814                        + pkg.packageName + " signatures do not match the "
5815                        + "previously installed version; ignoring!");
5816            }
5817        }
5818
5819        // Check for shared user signatures
5820        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5821            // Already existing package. Make sure signatures match
5822            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5823                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5824            if (!match) {
5825                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5826                        == PackageManager.SIGNATURE_MATCH;
5827            }
5828            if (!match) {
5829                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5830                        == PackageManager.SIGNATURE_MATCH;
5831            }
5832            if (!match) {
5833                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5834                        "Package " + pkg.packageName
5835                        + " has no signatures that match those in shared user "
5836                        + pkgSetting.sharedUser.name + "; ignoring!");
5837            }
5838        }
5839    }
5840
5841    /**
5842     * Enforces that only the system UID or root's UID can call a method exposed
5843     * via Binder.
5844     *
5845     * @param message used as message if SecurityException is thrown
5846     * @throws SecurityException if the caller is not system or root
5847     */
5848    private static final void enforceSystemOrRoot(String message) {
5849        final int uid = Binder.getCallingUid();
5850        if (uid != Process.SYSTEM_UID && uid != 0) {
5851            throw new SecurityException(message);
5852        }
5853    }
5854
5855    @Override
5856    public void performBootDexOpt() {
5857        enforceSystemOrRoot("Only the system can request dexopt be performed");
5858
5859        // Before everything else, see whether we need to fstrim.
5860        try {
5861            IMountService ms = PackageHelper.getMountService();
5862            if (ms != null) {
5863                final boolean isUpgrade = isUpgrade();
5864                boolean doTrim = isUpgrade;
5865                if (doTrim) {
5866                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5867                } else {
5868                    final long interval = android.provider.Settings.Global.getLong(
5869                            mContext.getContentResolver(),
5870                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5871                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5872                    if (interval > 0) {
5873                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5874                        if (timeSinceLast > interval) {
5875                            doTrim = true;
5876                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5877                                    + "; running immediately");
5878                        }
5879                    }
5880                }
5881                if (doTrim) {
5882                    if (!isFirstBoot()) {
5883                        try {
5884                            ActivityManagerNative.getDefault().showBootMessage(
5885                                    mContext.getResources().getString(
5886                                            R.string.android_upgrading_fstrim), true);
5887                        } catch (RemoteException e) {
5888                        }
5889                    }
5890                    ms.runMaintenance();
5891                }
5892            } else {
5893                Slog.e(TAG, "Mount service unavailable!");
5894            }
5895        } catch (RemoteException e) {
5896            // Can't happen; MountService is local
5897        }
5898
5899        final ArraySet<PackageParser.Package> pkgs;
5900        synchronized (mPackages) {
5901            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5902        }
5903
5904        if (pkgs != null) {
5905            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5906            // in case the device runs out of space.
5907            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5908            // Give priority to core apps.
5909            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5910                PackageParser.Package pkg = it.next();
5911                if (pkg.coreApp) {
5912                    if (DEBUG_DEXOPT) {
5913                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5914                    }
5915                    sortedPkgs.add(pkg);
5916                    it.remove();
5917                }
5918            }
5919            // Give priority to system apps that listen for pre boot complete.
5920            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5921            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5922            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5923                PackageParser.Package pkg = it.next();
5924                if (pkgNames.contains(pkg.packageName)) {
5925                    if (DEBUG_DEXOPT) {
5926                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5927                    }
5928                    sortedPkgs.add(pkg);
5929                    it.remove();
5930                }
5931            }
5932            // Give priority to system apps.
5933            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5934                PackageParser.Package pkg = it.next();
5935                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5936                    if (DEBUG_DEXOPT) {
5937                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5938                    }
5939                    sortedPkgs.add(pkg);
5940                    it.remove();
5941                }
5942            }
5943            // Give priority to updated system apps.
5944            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5945                PackageParser.Package pkg = it.next();
5946                if (pkg.isUpdatedSystemApp()) {
5947                    if (DEBUG_DEXOPT) {
5948                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5949                    }
5950                    sortedPkgs.add(pkg);
5951                    it.remove();
5952                }
5953            }
5954            // Give priority to apps that listen for boot complete.
5955            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5956            pkgNames = getPackageNamesForIntent(intent);
5957            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5958                PackageParser.Package pkg = it.next();
5959                if (pkgNames.contains(pkg.packageName)) {
5960                    if (DEBUG_DEXOPT) {
5961                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5962                    }
5963                    sortedPkgs.add(pkg);
5964                    it.remove();
5965                }
5966            }
5967            // Filter out packages that aren't recently used.
5968            filterRecentlyUsedApps(pkgs);
5969            // Add all remaining apps.
5970            for (PackageParser.Package pkg : pkgs) {
5971                if (DEBUG_DEXOPT) {
5972                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5973                }
5974                sortedPkgs.add(pkg);
5975            }
5976
5977            // If we want to be lazy, filter everything that wasn't recently used.
5978            if (mLazyDexOpt) {
5979                filterRecentlyUsedApps(sortedPkgs);
5980            }
5981
5982            int i = 0;
5983            int total = sortedPkgs.size();
5984            File dataDir = Environment.getDataDirectory();
5985            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5986            if (lowThreshold == 0) {
5987                throw new IllegalStateException("Invalid low memory threshold");
5988            }
5989            for (PackageParser.Package pkg : sortedPkgs) {
5990                long usableSpace = dataDir.getUsableSpace();
5991                if (usableSpace < lowThreshold) {
5992                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5993                    break;
5994                }
5995                performBootDexOpt(pkg, ++i, total);
5996            }
5997        }
5998    }
5999
6000    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6001        // Filter out packages that aren't recently used.
6002        //
6003        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6004        // should do a full dexopt.
6005        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6006            int total = pkgs.size();
6007            int skipped = 0;
6008            long now = System.currentTimeMillis();
6009            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6010                PackageParser.Package pkg = i.next();
6011                long then = pkg.mLastPackageUsageTimeInMills;
6012                if (then + mDexOptLRUThresholdInMills < now) {
6013                    if (DEBUG_DEXOPT) {
6014                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6015                              ((then == 0) ? "never" : new Date(then)));
6016                    }
6017                    i.remove();
6018                    skipped++;
6019                }
6020            }
6021            if (DEBUG_DEXOPT) {
6022                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6023            }
6024        }
6025    }
6026
6027    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6028        List<ResolveInfo> ris = null;
6029        try {
6030            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6031                    intent, null, 0, UserHandle.USER_OWNER);
6032        } catch (RemoteException e) {
6033        }
6034        ArraySet<String> pkgNames = new ArraySet<String>();
6035        if (ris != null) {
6036            for (ResolveInfo ri : ris) {
6037                pkgNames.add(ri.activityInfo.packageName);
6038            }
6039        }
6040        return pkgNames;
6041    }
6042
6043    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6044        if (DEBUG_DEXOPT) {
6045            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6046        }
6047        if (!isFirstBoot()) {
6048            try {
6049                ActivityManagerNative.getDefault().showBootMessage(
6050                        mContext.getResources().getString(R.string.android_upgrading_apk,
6051                                curr, total), true);
6052            } catch (RemoteException e) {
6053            }
6054        }
6055        PackageParser.Package p = pkg;
6056        synchronized (mInstallLock) {
6057            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6058                    false /* force dex */, false /* defer */, true /* include dependencies */);
6059        }
6060    }
6061
6062    @Override
6063    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6064        return performDexOpt(packageName, instructionSet, false);
6065    }
6066
6067    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6068        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6069        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6070        if (!dexopt && !updateUsage) {
6071            // We aren't going to dexopt or update usage, so bail early.
6072            return false;
6073        }
6074        PackageParser.Package p;
6075        final String targetInstructionSet;
6076        synchronized (mPackages) {
6077            p = mPackages.get(packageName);
6078            if (p == null) {
6079                return false;
6080            }
6081            if (updateUsage) {
6082                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6083            }
6084            mPackageUsage.write(false);
6085            if (!dexopt) {
6086                // We aren't going to dexopt, so bail early.
6087                return false;
6088            }
6089
6090            targetInstructionSet = instructionSet != null ? instructionSet :
6091                    getPrimaryInstructionSet(p.applicationInfo);
6092            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6093                return false;
6094            }
6095        }
6096
6097        synchronized (mInstallLock) {
6098            final String[] instructionSets = new String[] { targetInstructionSet };
6099            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6100                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6101            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6102        }
6103    }
6104
6105    public ArraySet<String> getPackagesThatNeedDexOpt() {
6106        ArraySet<String> pkgs = null;
6107        synchronized (mPackages) {
6108            for (PackageParser.Package p : mPackages.values()) {
6109                if (DEBUG_DEXOPT) {
6110                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6111                }
6112                if (!p.mDexOptPerformed.isEmpty()) {
6113                    continue;
6114                }
6115                if (pkgs == null) {
6116                    pkgs = new ArraySet<String>();
6117                }
6118                pkgs.add(p.packageName);
6119            }
6120        }
6121        return pkgs;
6122    }
6123
6124    public void shutdown() {
6125        mPackageUsage.write(true);
6126    }
6127
6128    @Override
6129    public void forceDexOpt(String packageName) {
6130        enforceSystemOrRoot("forceDexOpt");
6131
6132        PackageParser.Package pkg;
6133        synchronized (mPackages) {
6134            pkg = mPackages.get(packageName);
6135            if (pkg == null) {
6136                throw new IllegalArgumentException("Missing package: " + packageName);
6137            }
6138        }
6139
6140        synchronized (mInstallLock) {
6141            final String[] instructionSets = new String[] {
6142                    getPrimaryInstructionSet(pkg.applicationInfo) };
6143            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6144                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6145            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6146                throw new IllegalStateException("Failed to dexopt: " + res);
6147            }
6148        }
6149    }
6150
6151    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6152        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6153            Slog.w(TAG, "Unable to update from " + oldPkg.name
6154                    + " to " + newPkg.packageName
6155                    + ": old package not in system partition");
6156            return false;
6157        } else if (mPackages.get(oldPkg.name) != null) {
6158            Slog.w(TAG, "Unable to update from " + oldPkg.name
6159                    + " to " + newPkg.packageName
6160                    + ": old package still exists");
6161            return false;
6162        }
6163        return true;
6164    }
6165
6166    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6167        int[] users = sUserManager.getUserIds();
6168        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6169        if (res < 0) {
6170            return res;
6171        }
6172        for (int user : users) {
6173            if (user != 0) {
6174                res = mInstaller.createUserData(volumeUuid, packageName,
6175                        UserHandle.getUid(user, uid), user, seinfo);
6176                if (res < 0) {
6177                    return res;
6178                }
6179            }
6180        }
6181        return res;
6182    }
6183
6184    private int removeDataDirsLI(String volumeUuid, String packageName) {
6185        int[] users = sUserManager.getUserIds();
6186        int res = 0;
6187        for (int user : users) {
6188            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6189            if (resInner < 0) {
6190                res = resInner;
6191            }
6192        }
6193
6194        return res;
6195    }
6196
6197    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6198        int[] users = sUserManager.getUserIds();
6199        int res = 0;
6200        for (int user : users) {
6201            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6202            if (resInner < 0) {
6203                res = resInner;
6204            }
6205        }
6206        return res;
6207    }
6208
6209    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6210            PackageParser.Package changingLib) {
6211        if (file.path != null) {
6212            usesLibraryFiles.add(file.path);
6213            return;
6214        }
6215        PackageParser.Package p = mPackages.get(file.apk);
6216        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6217            // If we are doing this while in the middle of updating a library apk,
6218            // then we need to make sure to use that new apk for determining the
6219            // dependencies here.  (We haven't yet finished committing the new apk
6220            // to the package manager state.)
6221            if (p == null || p.packageName.equals(changingLib.packageName)) {
6222                p = changingLib;
6223            }
6224        }
6225        if (p != null) {
6226            usesLibraryFiles.addAll(p.getAllCodePaths());
6227        }
6228    }
6229
6230    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6231            PackageParser.Package changingLib) throws PackageManagerException {
6232        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6233            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6234            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6235            for (int i=0; i<N; i++) {
6236                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6237                if (file == null) {
6238                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6239                            "Package " + pkg.packageName + " requires unavailable shared library "
6240                            + pkg.usesLibraries.get(i) + "; failing!");
6241                }
6242                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6243            }
6244            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6245            for (int i=0; i<N; i++) {
6246                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6247                if (file == null) {
6248                    Slog.w(TAG, "Package " + pkg.packageName
6249                            + " desires unavailable shared library "
6250                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6251                } else {
6252                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6253                }
6254            }
6255            N = usesLibraryFiles.size();
6256            if (N > 0) {
6257                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6258            } else {
6259                pkg.usesLibraryFiles = null;
6260            }
6261        }
6262    }
6263
6264    private static boolean hasString(List<String> list, List<String> which) {
6265        if (list == null) {
6266            return false;
6267        }
6268        for (int i=list.size()-1; i>=0; i--) {
6269            for (int j=which.size()-1; j>=0; j--) {
6270                if (which.get(j).equals(list.get(i))) {
6271                    return true;
6272                }
6273            }
6274        }
6275        return false;
6276    }
6277
6278    private void updateAllSharedLibrariesLPw() {
6279        for (PackageParser.Package pkg : mPackages.values()) {
6280            try {
6281                updateSharedLibrariesLPw(pkg, null);
6282            } catch (PackageManagerException e) {
6283                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6284            }
6285        }
6286    }
6287
6288    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6289            PackageParser.Package changingPkg) {
6290        ArrayList<PackageParser.Package> res = null;
6291        for (PackageParser.Package pkg : mPackages.values()) {
6292            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6293                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6294                if (res == null) {
6295                    res = new ArrayList<PackageParser.Package>();
6296                }
6297                res.add(pkg);
6298                try {
6299                    updateSharedLibrariesLPw(pkg, changingPkg);
6300                } catch (PackageManagerException e) {
6301                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6302                }
6303            }
6304        }
6305        return res;
6306    }
6307
6308    /**
6309     * Derive the value of the {@code cpuAbiOverride} based on the provided
6310     * value and an optional stored value from the package settings.
6311     */
6312    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6313        String cpuAbiOverride = null;
6314
6315        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6316            cpuAbiOverride = null;
6317        } else if (abiOverride != null) {
6318            cpuAbiOverride = abiOverride;
6319        } else if (settings != null) {
6320            cpuAbiOverride = settings.cpuAbiOverrideString;
6321        }
6322
6323        return cpuAbiOverride;
6324    }
6325
6326    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6327            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6328        boolean success = false;
6329        try {
6330            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6331                    currentTime, user);
6332            success = true;
6333            return res;
6334        } finally {
6335            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6336                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6337            }
6338        }
6339    }
6340
6341    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6342            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6343        final File scanFile = new File(pkg.codePath);
6344        if (pkg.applicationInfo.getCodePath() == null ||
6345                pkg.applicationInfo.getResourcePath() == null) {
6346            // Bail out. The resource and code paths haven't been set.
6347            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6348                    "Code and resource paths haven't been set correctly");
6349        }
6350
6351        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6352            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6353        } else {
6354            // Only allow system apps to be flagged as core apps.
6355            pkg.coreApp = false;
6356        }
6357
6358        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6359            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6360        }
6361
6362        if (mCustomResolverComponentName != null &&
6363                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6364            setUpCustomResolverActivity(pkg);
6365        }
6366
6367        if (pkg.packageName.equals("android")) {
6368            synchronized (mPackages) {
6369                if (mAndroidApplication != null) {
6370                    Slog.w(TAG, "*************************************************");
6371                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6372                    Slog.w(TAG, " file=" + scanFile);
6373                    Slog.w(TAG, "*************************************************");
6374                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6375                            "Core android package being redefined.  Skipping.");
6376                }
6377
6378                // Set up information for our fall-back user intent resolution activity.
6379                mPlatformPackage = pkg;
6380                pkg.mVersionCode = mSdkVersion;
6381                mAndroidApplication = pkg.applicationInfo;
6382
6383                if (!mResolverReplaced) {
6384                    mResolveActivity.applicationInfo = mAndroidApplication;
6385                    mResolveActivity.name = ResolverActivity.class.getName();
6386                    mResolveActivity.packageName = mAndroidApplication.packageName;
6387                    mResolveActivity.processName = "system:ui";
6388                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6389                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6390                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6391                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6392                    mResolveActivity.exported = true;
6393                    mResolveActivity.enabled = true;
6394                    mResolveInfo.activityInfo = mResolveActivity;
6395                    mResolveInfo.priority = 0;
6396                    mResolveInfo.preferredOrder = 0;
6397                    mResolveInfo.match = 0;
6398                    mResolveComponentName = new ComponentName(
6399                            mAndroidApplication.packageName, mResolveActivity.name);
6400                }
6401            }
6402        }
6403
6404        if (DEBUG_PACKAGE_SCANNING) {
6405            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6406                Log.d(TAG, "Scanning package " + pkg.packageName);
6407        }
6408
6409        if (mPackages.containsKey(pkg.packageName)
6410                || mSharedLibraries.containsKey(pkg.packageName)) {
6411            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6412                    "Application package " + pkg.packageName
6413                    + " already installed.  Skipping duplicate.");
6414        }
6415
6416        // If we're only installing presumed-existing packages, require that the
6417        // scanned APK is both already known and at the path previously established
6418        // for it.  Previously unknown packages we pick up normally, but if we have an
6419        // a priori expectation about this package's install presence, enforce it.
6420        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6421            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6422            if (known != null) {
6423                if (DEBUG_PACKAGE_SCANNING) {
6424                    Log.d(TAG, "Examining " + pkg.codePath
6425                            + " and requiring known paths " + known.codePathString
6426                            + " & " + known.resourcePathString);
6427                }
6428                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6429                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6430                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6431                            "Application package " + pkg.packageName
6432                            + " found at " + pkg.applicationInfo.getCodePath()
6433                            + " but expected at " + known.codePathString + "; ignoring.");
6434                }
6435            }
6436        }
6437
6438        // Initialize package source and resource directories
6439        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6440        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6441
6442        SharedUserSetting suid = null;
6443        PackageSetting pkgSetting = null;
6444
6445        if (!isSystemApp(pkg)) {
6446            // Only system apps can use these features.
6447            pkg.mOriginalPackages = null;
6448            pkg.mRealPackage = null;
6449            pkg.mAdoptPermissions = null;
6450        }
6451
6452        // writer
6453        synchronized (mPackages) {
6454            if (pkg.mSharedUserId != null) {
6455                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6456                if (suid == null) {
6457                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6458                            "Creating application package " + pkg.packageName
6459                            + " for shared user failed");
6460                }
6461                if (DEBUG_PACKAGE_SCANNING) {
6462                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6463                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6464                                + "): packages=" + suid.packages);
6465                }
6466            }
6467
6468            // Check if we are renaming from an original package name.
6469            PackageSetting origPackage = null;
6470            String realName = null;
6471            if (pkg.mOriginalPackages != null) {
6472                // This package may need to be renamed to a previously
6473                // installed name.  Let's check on that...
6474                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6475                if (pkg.mOriginalPackages.contains(renamed)) {
6476                    // This package had originally been installed as the
6477                    // original name, and we have already taken care of
6478                    // transitioning to the new one.  Just update the new
6479                    // one to continue using the old name.
6480                    realName = pkg.mRealPackage;
6481                    if (!pkg.packageName.equals(renamed)) {
6482                        // Callers into this function may have already taken
6483                        // care of renaming the package; only do it here if
6484                        // it is not already done.
6485                        pkg.setPackageName(renamed);
6486                    }
6487
6488                } else {
6489                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6490                        if ((origPackage = mSettings.peekPackageLPr(
6491                                pkg.mOriginalPackages.get(i))) != null) {
6492                            // We do have the package already installed under its
6493                            // original name...  should we use it?
6494                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6495                                // New package is not compatible with original.
6496                                origPackage = null;
6497                                continue;
6498                            } else if (origPackage.sharedUser != null) {
6499                                // Make sure uid is compatible between packages.
6500                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6501                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6502                                            + " to " + pkg.packageName + ": old uid "
6503                                            + origPackage.sharedUser.name
6504                                            + " differs from " + pkg.mSharedUserId);
6505                                    origPackage = null;
6506                                    continue;
6507                                }
6508                            } else {
6509                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6510                                        + pkg.packageName + " to old name " + origPackage.name);
6511                            }
6512                            break;
6513                        }
6514                    }
6515                }
6516            }
6517
6518            if (mTransferedPackages.contains(pkg.packageName)) {
6519                Slog.w(TAG, "Package " + pkg.packageName
6520                        + " was transferred to another, but its .apk remains");
6521            }
6522
6523            // Just create the setting, don't add it yet. For already existing packages
6524            // the PkgSetting exists already and doesn't have to be created.
6525            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6526                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6527                    pkg.applicationInfo.primaryCpuAbi,
6528                    pkg.applicationInfo.secondaryCpuAbi,
6529                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6530                    user, false);
6531            if (pkgSetting == null) {
6532                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6533                        "Creating application package " + pkg.packageName + " failed");
6534            }
6535
6536            if (pkgSetting.origPackage != null) {
6537                // If we are first transitioning from an original package,
6538                // fix up the new package's name now.  We need to do this after
6539                // looking up the package under its new name, so getPackageLP
6540                // can take care of fiddling things correctly.
6541                pkg.setPackageName(origPackage.name);
6542
6543                // File a report about this.
6544                String msg = "New package " + pkgSetting.realName
6545                        + " renamed to replace old package " + pkgSetting.name;
6546                reportSettingsProblem(Log.WARN, msg);
6547
6548                // Make a note of it.
6549                mTransferedPackages.add(origPackage.name);
6550
6551                // No longer need to retain this.
6552                pkgSetting.origPackage = null;
6553            }
6554
6555            if (realName != null) {
6556                // Make a note of it.
6557                mTransferedPackages.add(pkg.packageName);
6558            }
6559
6560            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6561                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6562            }
6563
6564            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6565                // Check all shared libraries and map to their actual file path.
6566                // We only do this here for apps not on a system dir, because those
6567                // are the only ones that can fail an install due to this.  We
6568                // will take care of the system apps by updating all of their
6569                // library paths after the scan is done.
6570                updateSharedLibrariesLPw(pkg, null);
6571            }
6572
6573            if (mFoundPolicyFile) {
6574                SELinuxMMAC.assignSeinfoValue(pkg);
6575            }
6576
6577            pkg.applicationInfo.uid = pkgSetting.appId;
6578            pkg.mExtras = pkgSetting;
6579            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6580                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6581                    // We just determined the app is signed correctly, so bring
6582                    // over the latest parsed certs.
6583                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6584                } else {
6585                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6586                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6587                                "Package " + pkg.packageName + " upgrade keys do not match the "
6588                                + "previously installed version");
6589                    } else {
6590                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6591                        String msg = "System package " + pkg.packageName
6592                            + " signature changed; retaining data.";
6593                        reportSettingsProblem(Log.WARN, msg);
6594                    }
6595                }
6596            } else {
6597                try {
6598                    verifySignaturesLP(pkgSetting, pkg);
6599                    // We just determined the app is signed correctly, so bring
6600                    // over the latest parsed certs.
6601                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6602                } catch (PackageManagerException e) {
6603                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6604                        throw e;
6605                    }
6606                    // The signature has changed, but this package is in the system
6607                    // image...  let's recover!
6608                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6609                    // However...  if this package is part of a shared user, but it
6610                    // doesn't match the signature of the shared user, let's fail.
6611                    // What this means is that you can't change the signatures
6612                    // associated with an overall shared user, which doesn't seem all
6613                    // that unreasonable.
6614                    if (pkgSetting.sharedUser != null) {
6615                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6616                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6617                            throw new PackageManagerException(
6618                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6619                                            "Signature mismatch for shared user : "
6620                                            + pkgSetting.sharedUser);
6621                        }
6622                    }
6623                    // File a report about this.
6624                    String msg = "System package " + pkg.packageName
6625                        + " signature changed; retaining data.";
6626                    reportSettingsProblem(Log.WARN, msg);
6627                }
6628            }
6629            // Verify that this new package doesn't have any content providers
6630            // that conflict with existing packages.  Only do this if the
6631            // package isn't already installed, since we don't want to break
6632            // things that are installed.
6633            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6634                final int N = pkg.providers.size();
6635                int i;
6636                for (i=0; i<N; i++) {
6637                    PackageParser.Provider p = pkg.providers.get(i);
6638                    if (p.info.authority != null) {
6639                        String names[] = p.info.authority.split(";");
6640                        for (int j = 0; j < names.length; j++) {
6641                            if (mProvidersByAuthority.containsKey(names[j])) {
6642                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6643                                final String otherPackageName =
6644                                        ((other != null && other.getComponentName() != null) ?
6645                                                other.getComponentName().getPackageName() : "?");
6646                                throw new PackageManagerException(
6647                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6648                                                "Can't install because provider name " + names[j]
6649                                                + " (in package " + pkg.applicationInfo.packageName
6650                                                + ") is already used by " + otherPackageName);
6651                            }
6652                        }
6653                    }
6654                }
6655            }
6656
6657            if (pkg.mAdoptPermissions != null) {
6658                // This package wants to adopt ownership of permissions from
6659                // another package.
6660                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6661                    final String origName = pkg.mAdoptPermissions.get(i);
6662                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6663                    if (orig != null) {
6664                        if (verifyPackageUpdateLPr(orig, pkg)) {
6665                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6666                                    + pkg.packageName);
6667                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6668                        }
6669                    }
6670                }
6671            }
6672        }
6673
6674        final String pkgName = pkg.packageName;
6675
6676        final long scanFileTime = scanFile.lastModified();
6677        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6678        pkg.applicationInfo.processName = fixProcessName(
6679                pkg.applicationInfo.packageName,
6680                pkg.applicationInfo.processName,
6681                pkg.applicationInfo.uid);
6682
6683        File dataPath;
6684        if (mPlatformPackage == pkg) {
6685            // The system package is special.
6686            dataPath = new File(Environment.getDataDirectory(), "system");
6687
6688            pkg.applicationInfo.dataDir = dataPath.getPath();
6689
6690        } else {
6691            // This is a normal package, need to make its data directory.
6692            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6693                    UserHandle.USER_OWNER, pkg.packageName);
6694
6695            boolean uidError = false;
6696            if (dataPath.exists()) {
6697                int currentUid = 0;
6698                try {
6699                    StructStat stat = Os.stat(dataPath.getPath());
6700                    currentUid = stat.st_uid;
6701                } catch (ErrnoException e) {
6702                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6703                }
6704
6705                // If we have mismatched owners for the data path, we have a problem.
6706                if (currentUid != pkg.applicationInfo.uid) {
6707                    boolean recovered = false;
6708                    if (currentUid == 0) {
6709                        // The directory somehow became owned by root.  Wow.
6710                        // This is probably because the system was stopped while
6711                        // installd was in the middle of messing with its libs
6712                        // directory.  Ask installd to fix that.
6713                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6714                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6715                        if (ret >= 0) {
6716                            recovered = true;
6717                            String msg = "Package " + pkg.packageName
6718                                    + " unexpectedly changed to uid 0; recovered to " +
6719                                    + pkg.applicationInfo.uid;
6720                            reportSettingsProblem(Log.WARN, msg);
6721                        }
6722                    }
6723                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6724                            || (scanFlags&SCAN_BOOTING) != 0)) {
6725                        // If this is a system app, we can at least delete its
6726                        // current data so the application will still work.
6727                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6728                        if (ret >= 0) {
6729                            // TODO: Kill the processes first
6730                            // Old data gone!
6731                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6732                                    ? "System package " : "Third party package ";
6733                            String msg = prefix + pkg.packageName
6734                                    + " has changed from uid: "
6735                                    + currentUid + " to "
6736                                    + pkg.applicationInfo.uid + "; old data erased";
6737                            reportSettingsProblem(Log.WARN, msg);
6738                            recovered = true;
6739
6740                            // And now re-install the app.
6741                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6742                                    pkg.applicationInfo.seinfo);
6743                            if (ret == -1) {
6744                                // Ack should not happen!
6745                                msg = prefix + pkg.packageName
6746                                        + " could not have data directory re-created after delete.";
6747                                reportSettingsProblem(Log.WARN, msg);
6748                                throw new PackageManagerException(
6749                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6750                            }
6751                        }
6752                        if (!recovered) {
6753                            mHasSystemUidErrors = true;
6754                        }
6755                    } else if (!recovered) {
6756                        // If we allow this install to proceed, we will be broken.
6757                        // Abort, abort!
6758                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6759                                "scanPackageLI");
6760                    }
6761                    if (!recovered) {
6762                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6763                            + pkg.applicationInfo.uid + "/fs_"
6764                            + currentUid;
6765                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6766                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6767                        String msg = "Package " + pkg.packageName
6768                                + " has mismatched uid: "
6769                                + currentUid + " on disk, "
6770                                + pkg.applicationInfo.uid + " in settings";
6771                        // writer
6772                        synchronized (mPackages) {
6773                            mSettings.mReadMessages.append(msg);
6774                            mSettings.mReadMessages.append('\n');
6775                            uidError = true;
6776                            if (!pkgSetting.uidError) {
6777                                reportSettingsProblem(Log.ERROR, msg);
6778                            }
6779                        }
6780                    }
6781                }
6782                pkg.applicationInfo.dataDir = dataPath.getPath();
6783                if (mShouldRestoreconData) {
6784                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6785                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6786                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6787                }
6788            } else {
6789                if (DEBUG_PACKAGE_SCANNING) {
6790                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6791                        Log.v(TAG, "Want this data dir: " + dataPath);
6792                }
6793                //invoke installer to do the actual installation
6794                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6795                        pkg.applicationInfo.seinfo);
6796                if (ret < 0) {
6797                    // Error from installer
6798                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6799                            "Unable to create data dirs [errorCode=" + ret + "]");
6800                }
6801
6802                if (dataPath.exists()) {
6803                    pkg.applicationInfo.dataDir = dataPath.getPath();
6804                } else {
6805                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6806                    pkg.applicationInfo.dataDir = null;
6807                }
6808            }
6809
6810            pkgSetting.uidError = uidError;
6811        }
6812
6813        final String path = scanFile.getPath();
6814        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6815
6816        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6817            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6818
6819            // Some system apps still use directory structure for native libraries
6820            // in which case we might end up not detecting abi solely based on apk
6821            // structure. Try to detect abi based on directory structure.
6822            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6823                    pkg.applicationInfo.primaryCpuAbi == null) {
6824                setBundledAppAbisAndRoots(pkg, pkgSetting);
6825                setNativeLibraryPaths(pkg);
6826            }
6827
6828        } else {
6829            if ((scanFlags & SCAN_MOVE) != 0) {
6830                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6831                // but we already have this packages package info in the PackageSetting. We just
6832                // use that and derive the native library path based on the new codepath.
6833                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6834                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6835            }
6836
6837            // Set native library paths again. For moves, the path will be updated based on the
6838            // ABIs we've determined above. For non-moves, the path will be updated based on the
6839            // ABIs we determined during compilation, but the path will depend on the final
6840            // package path (after the rename away from the stage path).
6841            setNativeLibraryPaths(pkg);
6842        }
6843
6844        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6845        final int[] userIds = sUserManager.getUserIds();
6846        synchronized (mInstallLock) {
6847            // Make sure all user data directories are ready to roll; we're okay
6848            // if they already exist
6849            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6850                for (int userId : userIds) {
6851                    if (userId != 0) {
6852                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6853                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6854                                pkg.applicationInfo.seinfo);
6855                    }
6856                }
6857            }
6858
6859            // Create a native library symlink only if we have native libraries
6860            // and if the native libraries are 32 bit libraries. We do not provide
6861            // this symlink for 64 bit libraries.
6862            if (pkg.applicationInfo.primaryCpuAbi != null &&
6863                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6864                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6865                for (int userId : userIds) {
6866                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6867                            nativeLibPath, userId) < 0) {
6868                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6869                                "Failed linking native library dir (user=" + userId + ")");
6870                    }
6871                }
6872            }
6873        }
6874
6875        // This is a special case for the "system" package, where the ABI is
6876        // dictated by the zygote configuration (and init.rc). We should keep track
6877        // of this ABI so that we can deal with "normal" applications that run under
6878        // the same UID correctly.
6879        if (mPlatformPackage == pkg) {
6880            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6881                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6882        }
6883
6884        // If there's a mismatch between the abi-override in the package setting
6885        // and the abiOverride specified for the install. Warn about this because we
6886        // would've already compiled the app without taking the package setting into
6887        // account.
6888        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6889            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6890                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6891                        " for package: " + pkg.packageName);
6892            }
6893        }
6894
6895        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6896        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6897        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6898
6899        // Copy the derived override back to the parsed package, so that we can
6900        // update the package settings accordingly.
6901        pkg.cpuAbiOverride = cpuAbiOverride;
6902
6903        if (DEBUG_ABI_SELECTION) {
6904            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6905                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6906                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6907        }
6908
6909        // Push the derived path down into PackageSettings so we know what to
6910        // clean up at uninstall time.
6911        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6912
6913        if (DEBUG_ABI_SELECTION) {
6914            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6915                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6916                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6917        }
6918
6919        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6920            // We don't do this here during boot because we can do it all
6921            // at once after scanning all existing packages.
6922            //
6923            // We also do this *before* we perform dexopt on this package, so that
6924            // we can avoid redundant dexopts, and also to make sure we've got the
6925            // code and package path correct.
6926            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6927                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6928        }
6929
6930        if ((scanFlags & SCAN_NO_DEX) == 0) {
6931            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6932                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6933            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6934                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6935            }
6936        }
6937        if (mFactoryTest && pkg.requestedPermissions.contains(
6938                android.Manifest.permission.FACTORY_TEST)) {
6939            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6940        }
6941
6942        ArrayList<PackageParser.Package> clientLibPkgs = null;
6943
6944        // writer
6945        synchronized (mPackages) {
6946            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6947                // Only system apps can add new shared libraries.
6948                if (pkg.libraryNames != null) {
6949                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6950                        String name = pkg.libraryNames.get(i);
6951                        boolean allowed = false;
6952                        if (pkg.isUpdatedSystemApp()) {
6953                            // New library entries can only be added through the
6954                            // system image.  This is important to get rid of a lot
6955                            // of nasty edge cases: for example if we allowed a non-
6956                            // system update of the app to add a library, then uninstalling
6957                            // the update would make the library go away, and assumptions
6958                            // we made such as through app install filtering would now
6959                            // have allowed apps on the device which aren't compatible
6960                            // with it.  Better to just have the restriction here, be
6961                            // conservative, and create many fewer cases that can negatively
6962                            // impact the user experience.
6963                            final PackageSetting sysPs = mSettings
6964                                    .getDisabledSystemPkgLPr(pkg.packageName);
6965                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6966                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6967                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6968                                        allowed = true;
6969                                        allowed = true;
6970                                        break;
6971                                    }
6972                                }
6973                            }
6974                        } else {
6975                            allowed = true;
6976                        }
6977                        if (allowed) {
6978                            if (!mSharedLibraries.containsKey(name)) {
6979                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6980                            } else if (!name.equals(pkg.packageName)) {
6981                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6982                                        + name + " already exists; skipping");
6983                            }
6984                        } else {
6985                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6986                                    + name + " that is not declared on system image; skipping");
6987                        }
6988                    }
6989                    if ((scanFlags&SCAN_BOOTING) == 0) {
6990                        // If we are not booting, we need to update any applications
6991                        // that are clients of our shared library.  If we are booting,
6992                        // this will all be done once the scan is complete.
6993                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6994                    }
6995                }
6996            }
6997        }
6998
6999        // We also need to dexopt any apps that are dependent on this library.  Note that
7000        // if these fail, we should abort the install since installing the library will
7001        // result in some apps being broken.
7002        if (clientLibPkgs != null) {
7003            if ((scanFlags & SCAN_NO_DEX) == 0) {
7004                for (int i = 0; i < clientLibPkgs.size(); i++) {
7005                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7006                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7007                            null /* instruction sets */, forceDex,
7008                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7009                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7010                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7011                                "scanPackageLI failed to dexopt clientLibPkgs");
7012                    }
7013                }
7014            }
7015        }
7016
7017        // Also need to kill any apps that are dependent on the library.
7018        if (clientLibPkgs != null) {
7019            for (int i=0; i<clientLibPkgs.size(); i++) {
7020                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7021                killApplication(clientPkg.applicationInfo.packageName,
7022                        clientPkg.applicationInfo.uid, "update lib");
7023            }
7024        }
7025
7026        // Make sure we're not adding any bogus keyset info
7027        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7028        ksms.assertScannedPackageValid(pkg);
7029
7030        // writer
7031        synchronized (mPackages) {
7032            // We don't expect installation to fail beyond this point
7033
7034            // Add the new setting to mSettings
7035            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7036            // Add the new setting to mPackages
7037            mPackages.put(pkg.applicationInfo.packageName, pkg);
7038            // Make sure we don't accidentally delete its data.
7039            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7040            while (iter.hasNext()) {
7041                PackageCleanItem item = iter.next();
7042                if (pkgName.equals(item.packageName)) {
7043                    iter.remove();
7044                }
7045            }
7046
7047            // Take care of first install / last update times.
7048            if (currentTime != 0) {
7049                if (pkgSetting.firstInstallTime == 0) {
7050                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7051                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7052                    pkgSetting.lastUpdateTime = currentTime;
7053                }
7054            } else if (pkgSetting.firstInstallTime == 0) {
7055                // We need *something*.  Take time time stamp of the file.
7056                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7057            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7058                if (scanFileTime != pkgSetting.timeStamp) {
7059                    // A package on the system image has changed; consider this
7060                    // to be an update.
7061                    pkgSetting.lastUpdateTime = scanFileTime;
7062                }
7063            }
7064
7065            // Add the package's KeySets to the global KeySetManagerService
7066            ksms.addScannedPackageLPw(pkg);
7067
7068            int N = pkg.providers.size();
7069            StringBuilder r = null;
7070            int i;
7071            for (i=0; i<N; i++) {
7072                PackageParser.Provider p = pkg.providers.get(i);
7073                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7074                        p.info.processName, pkg.applicationInfo.uid);
7075                mProviders.addProvider(p);
7076                p.syncable = p.info.isSyncable;
7077                if (p.info.authority != null) {
7078                    String names[] = p.info.authority.split(";");
7079                    p.info.authority = null;
7080                    for (int j = 0; j < names.length; j++) {
7081                        if (j == 1 && p.syncable) {
7082                            // We only want the first authority for a provider to possibly be
7083                            // syncable, so if we already added this provider using a different
7084                            // authority clear the syncable flag. We copy the provider before
7085                            // changing it because the mProviders object contains a reference
7086                            // to a provider that we don't want to change.
7087                            // Only do this for the second authority since the resulting provider
7088                            // object can be the same for all future authorities for this provider.
7089                            p = new PackageParser.Provider(p);
7090                            p.syncable = false;
7091                        }
7092                        if (!mProvidersByAuthority.containsKey(names[j])) {
7093                            mProvidersByAuthority.put(names[j], p);
7094                            if (p.info.authority == null) {
7095                                p.info.authority = names[j];
7096                            } else {
7097                                p.info.authority = p.info.authority + ";" + names[j];
7098                            }
7099                            if (DEBUG_PACKAGE_SCANNING) {
7100                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7101                                    Log.d(TAG, "Registered content provider: " + names[j]
7102                                            + ", className = " + p.info.name + ", isSyncable = "
7103                                            + p.info.isSyncable);
7104                            }
7105                        } else {
7106                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7107                            Slog.w(TAG, "Skipping provider name " + names[j] +
7108                                    " (in package " + pkg.applicationInfo.packageName +
7109                                    "): name already used by "
7110                                    + ((other != null && other.getComponentName() != null)
7111                                            ? other.getComponentName().getPackageName() : "?"));
7112                        }
7113                    }
7114                }
7115                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7116                    if (r == null) {
7117                        r = new StringBuilder(256);
7118                    } else {
7119                        r.append(' ');
7120                    }
7121                    r.append(p.info.name);
7122                }
7123            }
7124            if (r != null) {
7125                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7126            }
7127
7128            N = pkg.services.size();
7129            r = null;
7130            for (i=0; i<N; i++) {
7131                PackageParser.Service s = pkg.services.get(i);
7132                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7133                        s.info.processName, pkg.applicationInfo.uid);
7134                mServices.addService(s);
7135                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7136                    if (r == null) {
7137                        r = new StringBuilder(256);
7138                    } else {
7139                        r.append(' ');
7140                    }
7141                    r.append(s.info.name);
7142                }
7143            }
7144            if (r != null) {
7145                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7146            }
7147
7148            N = pkg.receivers.size();
7149            r = null;
7150            for (i=0; i<N; i++) {
7151                PackageParser.Activity a = pkg.receivers.get(i);
7152                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7153                        a.info.processName, pkg.applicationInfo.uid);
7154                mReceivers.addActivity(a, "receiver");
7155                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7156                    if (r == null) {
7157                        r = new StringBuilder(256);
7158                    } else {
7159                        r.append(' ');
7160                    }
7161                    r.append(a.info.name);
7162                }
7163            }
7164            if (r != null) {
7165                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7166            }
7167
7168            N = pkg.activities.size();
7169            r = null;
7170            for (i=0; i<N; i++) {
7171                PackageParser.Activity a = pkg.activities.get(i);
7172                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7173                        a.info.processName, pkg.applicationInfo.uid);
7174                mActivities.addActivity(a, "activity");
7175                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7176                    if (r == null) {
7177                        r = new StringBuilder(256);
7178                    } else {
7179                        r.append(' ');
7180                    }
7181                    r.append(a.info.name);
7182                }
7183            }
7184            if (r != null) {
7185                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7186            }
7187
7188            N = pkg.permissionGroups.size();
7189            r = null;
7190            for (i=0; i<N; i++) {
7191                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7192                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7193                if (cur == null) {
7194                    mPermissionGroups.put(pg.info.name, pg);
7195                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7196                        if (r == null) {
7197                            r = new StringBuilder(256);
7198                        } else {
7199                            r.append(' ');
7200                        }
7201                        r.append(pg.info.name);
7202                    }
7203                } else {
7204                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7205                            + pg.info.packageName + " ignored: original from "
7206                            + cur.info.packageName);
7207                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7208                        if (r == null) {
7209                            r = new StringBuilder(256);
7210                        } else {
7211                            r.append(' ');
7212                        }
7213                        r.append("DUP:");
7214                        r.append(pg.info.name);
7215                    }
7216                }
7217            }
7218            if (r != null) {
7219                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7220            }
7221
7222            N = pkg.permissions.size();
7223            r = null;
7224            for (i=0; i<N; i++) {
7225                PackageParser.Permission p = pkg.permissions.get(i);
7226
7227                // Now that permission groups have a special meaning, we ignore permission
7228                // groups for legacy apps to prevent unexpected behavior. In particular,
7229                // permissions for one app being granted to someone just becuase they happen
7230                // to be in a group defined by another app (before this had no implications).
7231                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7232                    p.group = mPermissionGroups.get(p.info.group);
7233                    // Warn for a permission in an unknown group.
7234                    if (p.info.group != null && p.group == null) {
7235                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7236                                + p.info.packageName + " in an unknown group " + p.info.group);
7237                    }
7238                }
7239
7240                ArrayMap<String, BasePermission> permissionMap =
7241                        p.tree ? mSettings.mPermissionTrees
7242                                : mSettings.mPermissions;
7243                BasePermission bp = permissionMap.get(p.info.name);
7244
7245                // Allow system apps to redefine non-system permissions
7246                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7247                    final boolean currentOwnerIsSystem = (bp.perm != null
7248                            && isSystemApp(bp.perm.owner));
7249                    if (isSystemApp(p.owner)) {
7250                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7251                            // It's a built-in permission and no owner, take ownership now
7252                            bp.packageSetting = pkgSetting;
7253                            bp.perm = p;
7254                            bp.uid = pkg.applicationInfo.uid;
7255                            bp.sourcePackage = p.info.packageName;
7256                        } else if (!currentOwnerIsSystem) {
7257                            String msg = "New decl " + p.owner + " of permission  "
7258                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7259                            reportSettingsProblem(Log.WARN, msg);
7260                            bp = null;
7261                        }
7262                    }
7263                }
7264
7265                if (bp == null) {
7266                    bp = new BasePermission(p.info.name, p.info.packageName,
7267                            BasePermission.TYPE_NORMAL);
7268                    permissionMap.put(p.info.name, bp);
7269                }
7270
7271                if (bp.perm == null) {
7272                    if (bp.sourcePackage == null
7273                            || bp.sourcePackage.equals(p.info.packageName)) {
7274                        BasePermission tree = findPermissionTreeLP(p.info.name);
7275                        if (tree == null
7276                                || tree.sourcePackage.equals(p.info.packageName)) {
7277                            bp.packageSetting = pkgSetting;
7278                            bp.perm = p;
7279                            bp.uid = pkg.applicationInfo.uid;
7280                            bp.sourcePackage = p.info.packageName;
7281                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7282                                if (r == null) {
7283                                    r = new StringBuilder(256);
7284                                } else {
7285                                    r.append(' ');
7286                                }
7287                                r.append(p.info.name);
7288                            }
7289                        } else {
7290                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7291                                    + p.info.packageName + " ignored: base tree "
7292                                    + tree.name + " is from package "
7293                                    + tree.sourcePackage);
7294                        }
7295                    } else {
7296                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7297                                + p.info.packageName + " ignored: original from "
7298                                + bp.sourcePackage);
7299                    }
7300                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7301                    if (r == null) {
7302                        r = new StringBuilder(256);
7303                    } else {
7304                        r.append(' ');
7305                    }
7306                    r.append("DUP:");
7307                    r.append(p.info.name);
7308                }
7309                if (bp.perm == p) {
7310                    bp.protectionLevel = p.info.protectionLevel;
7311                }
7312            }
7313
7314            if (r != null) {
7315                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7316            }
7317
7318            N = pkg.instrumentation.size();
7319            r = null;
7320            for (i=0; i<N; i++) {
7321                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7322                a.info.packageName = pkg.applicationInfo.packageName;
7323                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7324                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7325                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7326                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7327                a.info.dataDir = pkg.applicationInfo.dataDir;
7328
7329                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7330                // need other information about the application, like the ABI and what not ?
7331                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7332                mInstrumentation.put(a.getComponentName(), a);
7333                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7334                    if (r == null) {
7335                        r = new StringBuilder(256);
7336                    } else {
7337                        r.append(' ');
7338                    }
7339                    r.append(a.info.name);
7340                }
7341            }
7342            if (r != null) {
7343                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7344            }
7345
7346            if (pkg.protectedBroadcasts != null) {
7347                N = pkg.protectedBroadcasts.size();
7348                for (i=0; i<N; i++) {
7349                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7350                }
7351            }
7352
7353            pkgSetting.setTimeStamp(scanFileTime);
7354
7355            // Create idmap files for pairs of (packages, overlay packages).
7356            // Note: "android", ie framework-res.apk, is handled by native layers.
7357            if (pkg.mOverlayTarget != null) {
7358                // This is an overlay package.
7359                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7360                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7361                        mOverlays.put(pkg.mOverlayTarget,
7362                                new ArrayMap<String, PackageParser.Package>());
7363                    }
7364                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7365                    map.put(pkg.packageName, pkg);
7366                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7367                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7368                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7369                                "scanPackageLI failed to createIdmap");
7370                    }
7371                }
7372            } else if (mOverlays.containsKey(pkg.packageName) &&
7373                    !pkg.packageName.equals("android")) {
7374                // This is a regular package, with one or more known overlay packages.
7375                createIdmapsForPackageLI(pkg);
7376            }
7377        }
7378
7379        return pkg;
7380    }
7381
7382    /**
7383     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7384     * is derived purely on the basis of the contents of {@code scanFile} and
7385     * {@code cpuAbiOverride}.
7386     *
7387     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7388     */
7389    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7390                                 String cpuAbiOverride, boolean extractLibs)
7391            throws PackageManagerException {
7392        // TODO: We can probably be smarter about this stuff. For installed apps,
7393        // we can calculate this information at install time once and for all. For
7394        // system apps, we can probably assume that this information doesn't change
7395        // after the first boot scan. As things stand, we do lots of unnecessary work.
7396
7397        // Give ourselves some initial paths; we'll come back for another
7398        // pass once we've determined ABI below.
7399        setNativeLibraryPaths(pkg);
7400
7401        // We would never need to extract libs for forward-locked and external packages,
7402        // since the container service will do it for us. We shouldn't attempt to
7403        // extract libs from system app when it was not updated.
7404        if (pkg.isForwardLocked() || isExternal(pkg) ||
7405            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7406            extractLibs = false;
7407        }
7408
7409        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7410        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7411
7412        NativeLibraryHelper.Handle handle = null;
7413        try {
7414            handle = NativeLibraryHelper.Handle.create(pkg);
7415            // TODO(multiArch): This can be null for apps that didn't go through the
7416            // usual installation process. We can calculate it again, like we
7417            // do during install time.
7418            //
7419            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7420            // unnecessary.
7421            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7422
7423            // Null out the abis so that they can be recalculated.
7424            pkg.applicationInfo.primaryCpuAbi = null;
7425            pkg.applicationInfo.secondaryCpuAbi = null;
7426            if (isMultiArch(pkg.applicationInfo)) {
7427                // Warn if we've set an abiOverride for multi-lib packages..
7428                // By definition, we need to copy both 32 and 64 bit libraries for
7429                // such packages.
7430                if (pkg.cpuAbiOverride != null
7431                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7432                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7433                }
7434
7435                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7436                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7437                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7438                    if (extractLibs) {
7439                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7440                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7441                                useIsaSpecificSubdirs);
7442                    } else {
7443                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7444                    }
7445                }
7446
7447                maybeThrowExceptionForMultiArchCopy(
7448                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7449
7450                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7451                    if (extractLibs) {
7452                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7453                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7454                                useIsaSpecificSubdirs);
7455                    } else {
7456                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7457                    }
7458                }
7459
7460                maybeThrowExceptionForMultiArchCopy(
7461                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7462
7463                if (abi64 >= 0) {
7464                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7465                }
7466
7467                if (abi32 >= 0) {
7468                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7469                    if (abi64 >= 0) {
7470                        pkg.applicationInfo.secondaryCpuAbi = abi;
7471                    } else {
7472                        pkg.applicationInfo.primaryCpuAbi = abi;
7473                    }
7474                }
7475            } else {
7476                String[] abiList = (cpuAbiOverride != null) ?
7477                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7478
7479                // Enable gross and lame hacks for apps that are built with old
7480                // SDK tools. We must scan their APKs for renderscript bitcode and
7481                // not launch them if it's present. Don't bother checking on devices
7482                // that don't have 64 bit support.
7483                boolean needsRenderScriptOverride = false;
7484                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7485                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7486                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7487                    needsRenderScriptOverride = true;
7488                }
7489
7490                final int copyRet;
7491                if (extractLibs) {
7492                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7493                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7494                } else {
7495                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7496                }
7497
7498                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7499                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7500                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7501                }
7502
7503                if (copyRet >= 0) {
7504                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7505                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7506                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7507                } else if (needsRenderScriptOverride) {
7508                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7509                }
7510            }
7511        } catch (IOException ioe) {
7512            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7513        } finally {
7514            IoUtils.closeQuietly(handle);
7515        }
7516
7517        // Now that we've calculated the ABIs and determined if it's an internal app,
7518        // we will go ahead and populate the nativeLibraryPath.
7519        setNativeLibraryPaths(pkg);
7520    }
7521
7522    /**
7523     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7524     * i.e, so that all packages can be run inside a single process if required.
7525     *
7526     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7527     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7528     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7529     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7530     * updating a package that belongs to a shared user.
7531     *
7532     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7533     * adds unnecessary complexity.
7534     */
7535    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7536            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7537        String requiredInstructionSet = null;
7538        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7539            requiredInstructionSet = VMRuntime.getInstructionSet(
7540                     scannedPackage.applicationInfo.primaryCpuAbi);
7541        }
7542
7543        PackageSetting requirer = null;
7544        for (PackageSetting ps : packagesForUser) {
7545            // If packagesForUser contains scannedPackage, we skip it. This will happen
7546            // when scannedPackage is an update of an existing package. Without this check,
7547            // we will never be able to change the ABI of any package belonging to a shared
7548            // user, even if it's compatible with other packages.
7549            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7550                if (ps.primaryCpuAbiString == null) {
7551                    continue;
7552                }
7553
7554                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7555                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7556                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7557                    // this but there's not much we can do.
7558                    String errorMessage = "Instruction set mismatch, "
7559                            + ((requirer == null) ? "[caller]" : requirer)
7560                            + " requires " + requiredInstructionSet + " whereas " + ps
7561                            + " requires " + instructionSet;
7562                    Slog.w(TAG, errorMessage);
7563                }
7564
7565                if (requiredInstructionSet == null) {
7566                    requiredInstructionSet = instructionSet;
7567                    requirer = ps;
7568                }
7569            }
7570        }
7571
7572        if (requiredInstructionSet != null) {
7573            String adjustedAbi;
7574            if (requirer != null) {
7575                // requirer != null implies that either scannedPackage was null or that scannedPackage
7576                // did not require an ABI, in which case we have to adjust scannedPackage to match
7577                // the ABI of the set (which is the same as requirer's ABI)
7578                adjustedAbi = requirer.primaryCpuAbiString;
7579                if (scannedPackage != null) {
7580                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7581                }
7582            } else {
7583                // requirer == null implies that we're updating all ABIs in the set to
7584                // match scannedPackage.
7585                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7586            }
7587
7588            for (PackageSetting ps : packagesForUser) {
7589                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7590                    if (ps.primaryCpuAbiString != null) {
7591                        continue;
7592                    }
7593
7594                    ps.primaryCpuAbiString = adjustedAbi;
7595                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7596                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7597                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7598
7599                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7600                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7601                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7602                            ps.primaryCpuAbiString = null;
7603                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7604                            return;
7605                        } else {
7606                            mInstaller.rmdex(ps.codePathString,
7607                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7608                        }
7609                    }
7610                }
7611            }
7612        }
7613    }
7614
7615    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7616        synchronized (mPackages) {
7617            mResolverReplaced = true;
7618            // Set up information for custom user intent resolution activity.
7619            mResolveActivity.applicationInfo = pkg.applicationInfo;
7620            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7621            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7622            mResolveActivity.processName = pkg.applicationInfo.packageName;
7623            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7624            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7625                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7626            mResolveActivity.theme = 0;
7627            mResolveActivity.exported = true;
7628            mResolveActivity.enabled = true;
7629            mResolveInfo.activityInfo = mResolveActivity;
7630            mResolveInfo.priority = 0;
7631            mResolveInfo.preferredOrder = 0;
7632            mResolveInfo.match = 0;
7633            mResolveComponentName = mCustomResolverComponentName;
7634            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7635                    mResolveComponentName);
7636        }
7637    }
7638
7639    private static String calculateBundledApkRoot(final String codePathString) {
7640        final File codePath = new File(codePathString);
7641        final File codeRoot;
7642        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7643            codeRoot = Environment.getRootDirectory();
7644        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7645            codeRoot = Environment.getOemDirectory();
7646        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7647            codeRoot = Environment.getVendorDirectory();
7648        } else {
7649            // Unrecognized code path; take its top real segment as the apk root:
7650            // e.g. /something/app/blah.apk => /something
7651            try {
7652                File f = codePath.getCanonicalFile();
7653                File parent = f.getParentFile();    // non-null because codePath is a file
7654                File tmp;
7655                while ((tmp = parent.getParentFile()) != null) {
7656                    f = parent;
7657                    parent = tmp;
7658                }
7659                codeRoot = f;
7660                Slog.w(TAG, "Unrecognized code path "
7661                        + codePath + " - using " + codeRoot);
7662            } catch (IOException e) {
7663                // Can't canonicalize the code path -- shenanigans?
7664                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7665                return Environment.getRootDirectory().getPath();
7666            }
7667        }
7668        return codeRoot.getPath();
7669    }
7670
7671    /**
7672     * Derive and set the location of native libraries for the given package,
7673     * which varies depending on where and how the package was installed.
7674     */
7675    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7676        final ApplicationInfo info = pkg.applicationInfo;
7677        final String codePath = pkg.codePath;
7678        final File codeFile = new File(codePath);
7679        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7680        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7681
7682        info.nativeLibraryRootDir = null;
7683        info.nativeLibraryRootRequiresIsa = false;
7684        info.nativeLibraryDir = null;
7685        info.secondaryNativeLibraryDir = null;
7686
7687        if (isApkFile(codeFile)) {
7688            // Monolithic install
7689            if (bundledApp) {
7690                // If "/system/lib64/apkname" exists, assume that is the per-package
7691                // native library directory to use; otherwise use "/system/lib/apkname".
7692                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7693                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7694                        getPrimaryInstructionSet(info));
7695
7696                // This is a bundled system app so choose the path based on the ABI.
7697                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7698                // is just the default path.
7699                final String apkName = deriveCodePathName(codePath);
7700                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7701                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7702                        apkName).getAbsolutePath();
7703
7704                if (info.secondaryCpuAbi != null) {
7705                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7706                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7707                            secondaryLibDir, apkName).getAbsolutePath();
7708                }
7709            } else if (asecApp) {
7710                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7711                        .getAbsolutePath();
7712            } else {
7713                final String apkName = deriveCodePathName(codePath);
7714                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7715                        .getAbsolutePath();
7716            }
7717
7718            info.nativeLibraryRootRequiresIsa = false;
7719            info.nativeLibraryDir = info.nativeLibraryRootDir;
7720        } else {
7721            // Cluster install
7722            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7723            info.nativeLibraryRootRequiresIsa = true;
7724
7725            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7726                    getPrimaryInstructionSet(info)).getAbsolutePath();
7727
7728            if (info.secondaryCpuAbi != null) {
7729                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7730                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7731            }
7732        }
7733    }
7734
7735    /**
7736     * Calculate the abis and roots for a bundled app. These can uniquely
7737     * be determined from the contents of the system partition, i.e whether
7738     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7739     * of this information, and instead assume that the system was built
7740     * sensibly.
7741     */
7742    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7743                                           PackageSetting pkgSetting) {
7744        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7745
7746        // If "/system/lib64/apkname" exists, assume that is the per-package
7747        // native library directory to use; otherwise use "/system/lib/apkname".
7748        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7749        setBundledAppAbi(pkg, apkRoot, apkName);
7750        // pkgSetting might be null during rescan following uninstall of updates
7751        // to a bundled app, so accommodate that possibility.  The settings in
7752        // that case will be established later from the parsed package.
7753        //
7754        // If the settings aren't null, sync them up with what we've just derived.
7755        // note that apkRoot isn't stored in the package settings.
7756        if (pkgSetting != null) {
7757            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7758            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7759        }
7760    }
7761
7762    /**
7763     * Deduces the ABI of a bundled app and sets the relevant fields on the
7764     * parsed pkg object.
7765     *
7766     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7767     *        under which system libraries are installed.
7768     * @param apkName the name of the installed package.
7769     */
7770    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7771        final File codeFile = new File(pkg.codePath);
7772
7773        final boolean has64BitLibs;
7774        final boolean has32BitLibs;
7775        if (isApkFile(codeFile)) {
7776            // Monolithic install
7777            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7778            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7779        } else {
7780            // Cluster install
7781            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7782            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7783                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7784                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7785                has64BitLibs = (new File(rootDir, isa)).exists();
7786            } else {
7787                has64BitLibs = false;
7788            }
7789            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7790                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7791                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7792                has32BitLibs = (new File(rootDir, isa)).exists();
7793            } else {
7794                has32BitLibs = false;
7795            }
7796        }
7797
7798        if (has64BitLibs && !has32BitLibs) {
7799            // The package has 64 bit libs, but not 32 bit libs. Its primary
7800            // ABI should be 64 bit. We can safely assume here that the bundled
7801            // native libraries correspond to the most preferred ABI in the list.
7802
7803            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7804            pkg.applicationInfo.secondaryCpuAbi = null;
7805        } else if (has32BitLibs && !has64BitLibs) {
7806            // The package has 32 bit libs but not 64 bit libs. Its primary
7807            // ABI should be 32 bit.
7808
7809            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7810            pkg.applicationInfo.secondaryCpuAbi = null;
7811        } else if (has32BitLibs && has64BitLibs) {
7812            // The application has both 64 and 32 bit bundled libraries. We check
7813            // here that the app declares multiArch support, and warn if it doesn't.
7814            //
7815            // We will be lenient here and record both ABIs. The primary will be the
7816            // ABI that's higher on the list, i.e, a device that's configured to prefer
7817            // 64 bit apps will see a 64 bit primary ABI,
7818
7819            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7820                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7821            }
7822
7823            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7824                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7825                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7826            } else {
7827                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7828                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7829            }
7830        } else {
7831            pkg.applicationInfo.primaryCpuAbi = null;
7832            pkg.applicationInfo.secondaryCpuAbi = null;
7833        }
7834    }
7835
7836    private void killApplication(String pkgName, int appId, String reason) {
7837        // Request the ActivityManager to kill the process(only for existing packages)
7838        // so that we do not end up in a confused state while the user is still using the older
7839        // version of the application while the new one gets installed.
7840        IActivityManager am = ActivityManagerNative.getDefault();
7841        if (am != null) {
7842            try {
7843                am.killApplicationWithAppId(pkgName, appId, reason);
7844            } catch (RemoteException e) {
7845            }
7846        }
7847    }
7848
7849    void removePackageLI(PackageSetting ps, boolean chatty) {
7850        if (DEBUG_INSTALL) {
7851            if (chatty)
7852                Log.d(TAG, "Removing package " + ps.name);
7853        }
7854
7855        // writer
7856        synchronized (mPackages) {
7857            mPackages.remove(ps.name);
7858            final PackageParser.Package pkg = ps.pkg;
7859            if (pkg != null) {
7860                cleanPackageDataStructuresLILPw(pkg, chatty);
7861            }
7862        }
7863    }
7864
7865    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7866        if (DEBUG_INSTALL) {
7867            if (chatty)
7868                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7869        }
7870
7871        // writer
7872        synchronized (mPackages) {
7873            mPackages.remove(pkg.applicationInfo.packageName);
7874            cleanPackageDataStructuresLILPw(pkg, chatty);
7875        }
7876    }
7877
7878    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7879        int N = pkg.providers.size();
7880        StringBuilder r = null;
7881        int i;
7882        for (i=0; i<N; i++) {
7883            PackageParser.Provider p = pkg.providers.get(i);
7884            mProviders.removeProvider(p);
7885            if (p.info.authority == null) {
7886
7887                /* There was another ContentProvider with this authority when
7888                 * this app was installed so this authority is null,
7889                 * Ignore it as we don't have to unregister the provider.
7890                 */
7891                continue;
7892            }
7893            String names[] = p.info.authority.split(";");
7894            for (int j = 0; j < names.length; j++) {
7895                if (mProvidersByAuthority.get(names[j]) == p) {
7896                    mProvidersByAuthority.remove(names[j]);
7897                    if (DEBUG_REMOVE) {
7898                        if (chatty)
7899                            Log.d(TAG, "Unregistered content provider: " + names[j]
7900                                    + ", className = " + p.info.name + ", isSyncable = "
7901                                    + p.info.isSyncable);
7902                    }
7903                }
7904            }
7905            if (DEBUG_REMOVE && chatty) {
7906                if (r == null) {
7907                    r = new StringBuilder(256);
7908                } else {
7909                    r.append(' ');
7910                }
7911                r.append(p.info.name);
7912            }
7913        }
7914        if (r != null) {
7915            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7916        }
7917
7918        N = pkg.services.size();
7919        r = null;
7920        for (i=0; i<N; i++) {
7921            PackageParser.Service s = pkg.services.get(i);
7922            mServices.removeService(s);
7923            if (chatty) {
7924                if (r == null) {
7925                    r = new StringBuilder(256);
7926                } else {
7927                    r.append(' ');
7928                }
7929                r.append(s.info.name);
7930            }
7931        }
7932        if (r != null) {
7933            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7934        }
7935
7936        N = pkg.receivers.size();
7937        r = null;
7938        for (i=0; i<N; i++) {
7939            PackageParser.Activity a = pkg.receivers.get(i);
7940            mReceivers.removeActivity(a, "receiver");
7941            if (DEBUG_REMOVE && chatty) {
7942                if (r == null) {
7943                    r = new StringBuilder(256);
7944                } else {
7945                    r.append(' ');
7946                }
7947                r.append(a.info.name);
7948            }
7949        }
7950        if (r != null) {
7951            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7952        }
7953
7954        N = pkg.activities.size();
7955        r = null;
7956        for (i=0; i<N; i++) {
7957            PackageParser.Activity a = pkg.activities.get(i);
7958            mActivities.removeActivity(a, "activity");
7959            if (DEBUG_REMOVE && chatty) {
7960                if (r == null) {
7961                    r = new StringBuilder(256);
7962                } else {
7963                    r.append(' ');
7964                }
7965                r.append(a.info.name);
7966            }
7967        }
7968        if (r != null) {
7969            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7970        }
7971
7972        N = pkg.permissions.size();
7973        r = null;
7974        for (i=0; i<N; i++) {
7975            PackageParser.Permission p = pkg.permissions.get(i);
7976            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7977            if (bp == null) {
7978                bp = mSettings.mPermissionTrees.get(p.info.name);
7979            }
7980            if (bp != null && bp.perm == p) {
7981                bp.perm = null;
7982                if (DEBUG_REMOVE && chatty) {
7983                    if (r == null) {
7984                        r = new StringBuilder(256);
7985                    } else {
7986                        r.append(' ');
7987                    }
7988                    r.append(p.info.name);
7989                }
7990            }
7991            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7992                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7993                if (appOpPerms != null) {
7994                    appOpPerms.remove(pkg.packageName);
7995                }
7996            }
7997        }
7998        if (r != null) {
7999            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8000        }
8001
8002        N = pkg.requestedPermissions.size();
8003        r = null;
8004        for (i=0; i<N; i++) {
8005            String perm = pkg.requestedPermissions.get(i);
8006            BasePermission bp = mSettings.mPermissions.get(perm);
8007            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8008                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8009                if (appOpPerms != null) {
8010                    appOpPerms.remove(pkg.packageName);
8011                    if (appOpPerms.isEmpty()) {
8012                        mAppOpPermissionPackages.remove(perm);
8013                    }
8014                }
8015            }
8016        }
8017        if (r != null) {
8018            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8019        }
8020
8021        N = pkg.instrumentation.size();
8022        r = null;
8023        for (i=0; i<N; i++) {
8024            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8025            mInstrumentation.remove(a.getComponentName());
8026            if (DEBUG_REMOVE && chatty) {
8027                if (r == null) {
8028                    r = new StringBuilder(256);
8029                } else {
8030                    r.append(' ');
8031                }
8032                r.append(a.info.name);
8033            }
8034        }
8035        if (r != null) {
8036            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8037        }
8038
8039        r = null;
8040        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8041            // Only system apps can hold shared libraries.
8042            if (pkg.libraryNames != null) {
8043                for (i=0; i<pkg.libraryNames.size(); i++) {
8044                    String name = pkg.libraryNames.get(i);
8045                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8046                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8047                        mSharedLibraries.remove(name);
8048                        if (DEBUG_REMOVE && chatty) {
8049                            if (r == null) {
8050                                r = new StringBuilder(256);
8051                            } else {
8052                                r.append(' ');
8053                            }
8054                            r.append(name);
8055                        }
8056                    }
8057                }
8058            }
8059        }
8060        if (r != null) {
8061            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8062        }
8063    }
8064
8065    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8066        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8067            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8068                return true;
8069            }
8070        }
8071        return false;
8072    }
8073
8074    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8075    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8076    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8077
8078    private void updatePermissionsLPw(String changingPkg,
8079            PackageParser.Package pkgInfo, int flags) {
8080        // Make sure there are no dangling permission trees.
8081        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8082        while (it.hasNext()) {
8083            final BasePermission bp = it.next();
8084            if (bp.packageSetting == null) {
8085                // We may not yet have parsed the package, so just see if
8086                // we still know about its settings.
8087                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8088            }
8089            if (bp.packageSetting == null) {
8090                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8091                        + " from package " + bp.sourcePackage);
8092                it.remove();
8093            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8094                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8095                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8096                            + " from package " + bp.sourcePackage);
8097                    flags |= UPDATE_PERMISSIONS_ALL;
8098                    it.remove();
8099                }
8100            }
8101        }
8102
8103        // Make sure all dynamic permissions have been assigned to a package,
8104        // and make sure there are no dangling permissions.
8105        it = mSettings.mPermissions.values().iterator();
8106        while (it.hasNext()) {
8107            final BasePermission bp = it.next();
8108            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8109                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8110                        + bp.name + " pkg=" + bp.sourcePackage
8111                        + " info=" + bp.pendingInfo);
8112                if (bp.packageSetting == null && bp.pendingInfo != null) {
8113                    final BasePermission tree = findPermissionTreeLP(bp.name);
8114                    if (tree != null && tree.perm != null) {
8115                        bp.packageSetting = tree.packageSetting;
8116                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8117                                new PermissionInfo(bp.pendingInfo));
8118                        bp.perm.info.packageName = tree.perm.info.packageName;
8119                        bp.perm.info.name = bp.name;
8120                        bp.uid = tree.uid;
8121                    }
8122                }
8123            }
8124            if (bp.packageSetting == null) {
8125                // We may not yet have parsed the package, so just see if
8126                // we still know about its settings.
8127                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8128            }
8129            if (bp.packageSetting == null) {
8130                Slog.w(TAG, "Removing dangling permission: " + bp.name
8131                        + " from package " + bp.sourcePackage);
8132                it.remove();
8133            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8134                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8135                    Slog.i(TAG, "Removing old permission: " + bp.name
8136                            + " from package " + bp.sourcePackage);
8137                    flags |= UPDATE_PERMISSIONS_ALL;
8138                    it.remove();
8139                }
8140            }
8141        }
8142
8143        // Now update the permissions for all packages, in particular
8144        // replace the granted permissions of the system packages.
8145        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8146            for (PackageParser.Package pkg : mPackages.values()) {
8147                if (pkg != pkgInfo) {
8148                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8149                            changingPkg);
8150                }
8151            }
8152        }
8153
8154        if (pkgInfo != null) {
8155            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8156        }
8157    }
8158
8159    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8160            String packageOfInterest) {
8161        // IMPORTANT: There are two types of permissions: install and runtime.
8162        // Install time permissions are granted when the app is installed to
8163        // all device users and users added in the future. Runtime permissions
8164        // are granted at runtime explicitly to specific users. Normal and signature
8165        // protected permissions are install time permissions. Dangerous permissions
8166        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8167        // otherwise they are runtime permissions. This function does not manage
8168        // runtime permissions except for the case an app targeting Lollipop MR1
8169        // being upgraded to target a newer SDK, in which case dangerous permissions
8170        // are transformed from install time to runtime ones.
8171
8172        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8173        if (ps == null) {
8174            return;
8175        }
8176
8177        PermissionsState permissionsState = ps.getPermissionsState();
8178        PermissionsState origPermissions = permissionsState;
8179
8180        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8181
8182        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8183
8184        boolean changedInstallPermission = false;
8185
8186        if (replace) {
8187            ps.installPermissionsFixed = false;
8188            if (!ps.isSharedUser()) {
8189                origPermissions = new PermissionsState(permissionsState);
8190                permissionsState.reset();
8191            }
8192        }
8193
8194        permissionsState.setGlobalGids(mGlobalGids);
8195
8196        final int N = pkg.requestedPermissions.size();
8197        for (int i=0; i<N; i++) {
8198            final String name = pkg.requestedPermissions.get(i);
8199            final BasePermission bp = mSettings.mPermissions.get(name);
8200
8201            if (DEBUG_INSTALL) {
8202                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8203            }
8204
8205            if (bp == null || bp.packageSetting == null) {
8206                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8207                    Slog.w(TAG, "Unknown permission " + name
8208                            + " in package " + pkg.packageName);
8209                }
8210                continue;
8211            }
8212
8213            final String perm = bp.name;
8214            boolean allowedSig = false;
8215            int grant = GRANT_DENIED;
8216
8217            // Keep track of app op permissions.
8218            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8219                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8220                if (pkgs == null) {
8221                    pkgs = new ArraySet<>();
8222                    mAppOpPermissionPackages.put(bp.name, pkgs);
8223                }
8224                pkgs.add(pkg.packageName);
8225            }
8226
8227            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8228            switch (level) {
8229                case PermissionInfo.PROTECTION_NORMAL: {
8230                    // For all apps normal permissions are install time ones.
8231                    grant = GRANT_INSTALL;
8232                } break;
8233
8234                case PermissionInfo.PROTECTION_DANGEROUS: {
8235                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8236                        // For legacy apps dangerous permissions are install time ones.
8237                        grant = GRANT_INSTALL_LEGACY;
8238                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8239                        // For legacy apps that became modern, install becomes runtime.
8240                        grant = GRANT_UPGRADE;
8241                    } else {
8242                        // For modern apps keep runtime permissions unchanged.
8243                        grant = GRANT_RUNTIME;
8244                    }
8245                } break;
8246
8247                case PermissionInfo.PROTECTION_SIGNATURE: {
8248                    // For all apps signature permissions are install time ones.
8249                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8250                    if (allowedSig) {
8251                        grant = GRANT_INSTALL;
8252                    }
8253                } break;
8254            }
8255
8256            if (DEBUG_INSTALL) {
8257                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8258            }
8259
8260            if (grant != GRANT_DENIED) {
8261                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8262                    // If this is an existing, non-system package, then
8263                    // we can't add any new permissions to it.
8264                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8265                        // Except...  if this is a permission that was added
8266                        // to the platform (note: need to only do this when
8267                        // updating the platform).
8268                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8269                            grant = GRANT_DENIED;
8270                        }
8271                    }
8272                }
8273
8274                switch (grant) {
8275                    case GRANT_INSTALL: {
8276                        // Revoke this as runtime permission to handle the case of
8277                        // a runtime permission being downgraded to an install one.
8278                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8279                            if (origPermissions.getRuntimePermissionState(
8280                                    bp.name, userId) != null) {
8281                                // Revoke the runtime permission and clear the flags.
8282                                origPermissions.revokeRuntimePermission(bp, userId);
8283                                origPermissions.updatePermissionFlags(bp, userId,
8284                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8285                                // If we revoked a permission permission, we have to write.
8286                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8287                                        changedRuntimePermissionUserIds, userId);
8288                            }
8289                        }
8290                        // Grant an install permission.
8291                        if (permissionsState.grantInstallPermission(bp) !=
8292                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8293                            changedInstallPermission = true;
8294                        }
8295                    } break;
8296
8297                    case GRANT_INSTALL_LEGACY: {
8298                        // Grant an install permission.
8299                        if (permissionsState.grantInstallPermission(bp) !=
8300                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8301                            changedInstallPermission = true;
8302                        }
8303                    } break;
8304
8305                    case GRANT_RUNTIME: {
8306                        // Grant previously granted runtime permissions.
8307                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8308                            PermissionState permissionState = origPermissions
8309                                    .getRuntimePermissionState(bp.name, userId);
8310                            final int flags = permissionState != null
8311                                    ? permissionState.getFlags() : 0;
8312                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8313                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8314                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8315                                    // If we cannot put the permission as it was, we have to write.
8316                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8317                                            changedRuntimePermissionUserIds, userId);
8318                                }
8319                            }
8320                            // Propagate the permission flags.
8321                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8322                        }
8323                    } break;
8324
8325                    case GRANT_UPGRADE: {
8326                        // Grant runtime permissions for a previously held install permission.
8327                        PermissionState permissionState = origPermissions
8328                                .getInstallPermissionState(bp.name);
8329                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8330
8331                        if (origPermissions.revokeInstallPermission(bp)
8332                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8333                            // We will be transferring the permission flags, so clear them.
8334                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8335                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8336                            changedInstallPermission = true;
8337                        }
8338
8339                        // If the permission is not to be promoted to runtime we ignore it and
8340                        // also its other flags as they are not applicable to install permissions.
8341                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8342                            for (int userId : currentUserIds) {
8343                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8344                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8345                                    // Transfer the permission flags.
8346                                    permissionsState.updatePermissionFlags(bp, userId,
8347                                            flags, flags);
8348                                    // If we granted the permission, we have to write.
8349                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8350                                            changedRuntimePermissionUserIds, userId);
8351                                }
8352                            }
8353                        }
8354                    } break;
8355
8356                    default: {
8357                        if (packageOfInterest == null
8358                                || packageOfInterest.equals(pkg.packageName)) {
8359                            Slog.w(TAG, "Not granting permission " + perm
8360                                    + " to package " + pkg.packageName
8361                                    + " because it was previously installed without");
8362                        }
8363                    } break;
8364                }
8365            } else {
8366                if (permissionsState.revokeInstallPermission(bp) !=
8367                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8368                    // Also drop the permission flags.
8369                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8370                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8371                    changedInstallPermission = true;
8372                    Slog.i(TAG, "Un-granting permission " + perm
8373                            + " from package " + pkg.packageName
8374                            + " (protectionLevel=" + bp.protectionLevel
8375                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8376                            + ")");
8377                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8378                    // Don't print warning for app op permissions, since it is fine for them
8379                    // not to be granted, there is a UI for the user to decide.
8380                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8381                        Slog.w(TAG, "Not granting permission " + perm
8382                                + " to package " + pkg.packageName
8383                                + " (protectionLevel=" + bp.protectionLevel
8384                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8385                                + ")");
8386                    }
8387                }
8388            }
8389        }
8390
8391        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8392                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8393            // This is the first that we have heard about this package, so the
8394            // permissions we have now selected are fixed until explicitly
8395            // changed.
8396            ps.installPermissionsFixed = true;
8397        }
8398
8399        // Persist the runtime permissions state for users with changes.
8400        for (int userId : changedRuntimePermissionUserIds) {
8401            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8402        }
8403    }
8404
8405    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8406        boolean allowed = false;
8407        final int NP = PackageParser.NEW_PERMISSIONS.length;
8408        for (int ip=0; ip<NP; ip++) {
8409            final PackageParser.NewPermissionInfo npi
8410                    = PackageParser.NEW_PERMISSIONS[ip];
8411            if (npi.name.equals(perm)
8412                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8413                allowed = true;
8414                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8415                        + pkg.packageName);
8416                break;
8417            }
8418        }
8419        return allowed;
8420    }
8421
8422    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8423            BasePermission bp, PermissionsState origPermissions) {
8424        boolean allowed;
8425        allowed = (compareSignatures(
8426                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8427                        == PackageManager.SIGNATURE_MATCH)
8428                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8429                        == PackageManager.SIGNATURE_MATCH);
8430        if (!allowed && (bp.protectionLevel
8431                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8432            if (isSystemApp(pkg)) {
8433                // For updated system applications, a system permission
8434                // is granted only if it had been defined by the original application.
8435                if (pkg.isUpdatedSystemApp()) {
8436                    final PackageSetting sysPs = mSettings
8437                            .getDisabledSystemPkgLPr(pkg.packageName);
8438                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8439                        // If the original was granted this permission, we take
8440                        // that grant decision as read and propagate it to the
8441                        // update.
8442                        if (sysPs.isPrivileged()) {
8443                            allowed = true;
8444                        }
8445                    } else {
8446                        // The system apk may have been updated with an older
8447                        // version of the one on the data partition, but which
8448                        // granted a new system permission that it didn't have
8449                        // before.  In this case we do want to allow the app to
8450                        // now get the new permission if the ancestral apk is
8451                        // privileged to get it.
8452                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8453                            for (int j=0;
8454                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8455                                if (perm.equals(
8456                                        sysPs.pkg.requestedPermissions.get(j))) {
8457                                    allowed = true;
8458                                    break;
8459                                }
8460                            }
8461                        }
8462                    }
8463                } else {
8464                    allowed = isPrivilegedApp(pkg);
8465                }
8466            }
8467        }
8468        if (!allowed && (bp.protectionLevel
8469                & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8470                && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8471            // If this was a previously normal/dangerous permission that got moved
8472            // to a system permission as part of the runtime permission redesign, then
8473            // we still want to blindly grant it to old apps.
8474            allowed = true;
8475        }
8476        if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8477                && pkg.packageName.equals(mRequiredInstallerPackage)) {
8478            // If this permission is to be granted to the system installer and
8479            // this app is an installer, then it gets the permission.
8480            allowed = true;
8481        }
8482        if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8483                && pkg.packageName.equals(mRequiredVerifierPackage)) {
8484            // If this permission is to be granted to the system verifier and
8485            // this app is a verifier, then it gets the permission.
8486            allowed = true;
8487        }
8488        if (!allowed && (bp.protectionLevel
8489                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8490            // For development permissions, a development permission
8491            // is granted only if it was already granted.
8492            allowed = origPermissions.hasInstallPermission(perm);
8493        }
8494        return allowed;
8495    }
8496
8497    final class ActivityIntentResolver
8498            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8499        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8500                boolean defaultOnly, int userId) {
8501            if (!sUserManager.exists(userId)) return null;
8502            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8503            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8504        }
8505
8506        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8507                int userId) {
8508            if (!sUserManager.exists(userId)) return null;
8509            mFlags = flags;
8510            return super.queryIntent(intent, resolvedType,
8511                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8512        }
8513
8514        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8515                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8516            if (!sUserManager.exists(userId)) return null;
8517            if (packageActivities == null) {
8518                return null;
8519            }
8520            mFlags = flags;
8521            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8522            final int N = packageActivities.size();
8523            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8524                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8525
8526            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8527            for (int i = 0; i < N; ++i) {
8528                intentFilters = packageActivities.get(i).intents;
8529                if (intentFilters != null && intentFilters.size() > 0) {
8530                    PackageParser.ActivityIntentInfo[] array =
8531                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8532                    intentFilters.toArray(array);
8533                    listCut.add(array);
8534                }
8535            }
8536            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8537        }
8538
8539        public final void addActivity(PackageParser.Activity a, String type) {
8540            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8541            mActivities.put(a.getComponentName(), a);
8542            if (DEBUG_SHOW_INFO)
8543                Log.v(
8544                TAG, "  " + type + " " +
8545                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8546            if (DEBUG_SHOW_INFO)
8547                Log.v(TAG, "    Class=" + a.info.name);
8548            final int NI = a.intents.size();
8549            for (int j=0; j<NI; j++) {
8550                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8551                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8552                    intent.setPriority(0);
8553                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8554                            + a.className + " with priority > 0, forcing to 0");
8555                }
8556                if (DEBUG_SHOW_INFO) {
8557                    Log.v(TAG, "    IntentFilter:");
8558                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8559                }
8560                if (!intent.debugCheck()) {
8561                    Log.w(TAG, "==> For Activity " + a.info.name);
8562                }
8563                addFilter(intent);
8564            }
8565        }
8566
8567        public final void removeActivity(PackageParser.Activity a, String type) {
8568            mActivities.remove(a.getComponentName());
8569            if (DEBUG_SHOW_INFO) {
8570                Log.v(TAG, "  " + type + " "
8571                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8572                                : a.info.name) + ":");
8573                Log.v(TAG, "    Class=" + a.info.name);
8574            }
8575            final int NI = a.intents.size();
8576            for (int j=0; j<NI; j++) {
8577                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8578                if (DEBUG_SHOW_INFO) {
8579                    Log.v(TAG, "    IntentFilter:");
8580                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8581                }
8582                removeFilter(intent);
8583            }
8584        }
8585
8586        @Override
8587        protected boolean allowFilterResult(
8588                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8589            ActivityInfo filterAi = filter.activity.info;
8590            for (int i=dest.size()-1; i>=0; i--) {
8591                ActivityInfo destAi = dest.get(i).activityInfo;
8592                if (destAi.name == filterAi.name
8593                        && destAi.packageName == filterAi.packageName) {
8594                    return false;
8595                }
8596            }
8597            return true;
8598        }
8599
8600        @Override
8601        protected ActivityIntentInfo[] newArray(int size) {
8602            return new ActivityIntentInfo[size];
8603        }
8604
8605        @Override
8606        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8607            if (!sUserManager.exists(userId)) return true;
8608            PackageParser.Package p = filter.activity.owner;
8609            if (p != null) {
8610                PackageSetting ps = (PackageSetting)p.mExtras;
8611                if (ps != null) {
8612                    // System apps are never considered stopped for purposes of
8613                    // filtering, because there may be no way for the user to
8614                    // actually re-launch them.
8615                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8616                            && ps.getStopped(userId);
8617                }
8618            }
8619            return false;
8620        }
8621
8622        @Override
8623        protected boolean isPackageForFilter(String packageName,
8624                PackageParser.ActivityIntentInfo info) {
8625            return packageName.equals(info.activity.owner.packageName);
8626        }
8627
8628        @Override
8629        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8630                int match, int userId) {
8631            if (!sUserManager.exists(userId)) return null;
8632            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8633                return null;
8634            }
8635            final PackageParser.Activity activity = info.activity;
8636            if (mSafeMode && (activity.info.applicationInfo.flags
8637                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8638                return null;
8639            }
8640            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8641            if (ps == null) {
8642                return null;
8643            }
8644            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8645                    ps.readUserState(userId), userId);
8646            if (ai == null) {
8647                return null;
8648            }
8649            final ResolveInfo res = new ResolveInfo();
8650            res.activityInfo = ai;
8651            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8652                res.filter = info;
8653            }
8654            if (info != null) {
8655                res.handleAllWebDataURI = info.handleAllWebDataURI();
8656            }
8657            res.priority = info.getPriority();
8658            res.preferredOrder = activity.owner.mPreferredOrder;
8659            //System.out.println("Result: " + res.activityInfo.className +
8660            //                   " = " + res.priority);
8661            res.match = match;
8662            res.isDefault = info.hasDefault;
8663            res.labelRes = info.labelRes;
8664            res.nonLocalizedLabel = info.nonLocalizedLabel;
8665            if (userNeedsBadging(userId)) {
8666                res.noResourceId = true;
8667            } else {
8668                res.icon = info.icon;
8669            }
8670            res.iconResourceId = info.icon;
8671            res.system = res.activityInfo.applicationInfo.isSystemApp();
8672            return res;
8673        }
8674
8675        @Override
8676        protected void sortResults(List<ResolveInfo> results) {
8677            Collections.sort(results, mResolvePrioritySorter);
8678        }
8679
8680        @Override
8681        protected void dumpFilter(PrintWriter out, String prefix,
8682                PackageParser.ActivityIntentInfo filter) {
8683            out.print(prefix); out.print(
8684                    Integer.toHexString(System.identityHashCode(filter.activity)));
8685                    out.print(' ');
8686                    filter.activity.printComponentShortName(out);
8687                    out.print(" filter ");
8688                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8689        }
8690
8691        @Override
8692        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8693            return filter.activity;
8694        }
8695
8696        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8697            PackageParser.Activity activity = (PackageParser.Activity)label;
8698            out.print(prefix); out.print(
8699                    Integer.toHexString(System.identityHashCode(activity)));
8700                    out.print(' ');
8701                    activity.printComponentShortName(out);
8702            if (count > 1) {
8703                out.print(" ("); out.print(count); out.print(" filters)");
8704            }
8705            out.println();
8706        }
8707
8708//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8709//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8710//            final List<ResolveInfo> retList = Lists.newArrayList();
8711//            while (i.hasNext()) {
8712//                final ResolveInfo resolveInfo = i.next();
8713//                if (isEnabledLP(resolveInfo.activityInfo)) {
8714//                    retList.add(resolveInfo);
8715//                }
8716//            }
8717//            return retList;
8718//        }
8719
8720        // Keys are String (activity class name), values are Activity.
8721        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8722                = new ArrayMap<ComponentName, PackageParser.Activity>();
8723        private int mFlags;
8724    }
8725
8726    private final class ServiceIntentResolver
8727            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8728        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8729                boolean defaultOnly, int userId) {
8730            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8731            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8732        }
8733
8734        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8735                int userId) {
8736            if (!sUserManager.exists(userId)) return null;
8737            mFlags = flags;
8738            return super.queryIntent(intent, resolvedType,
8739                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8740        }
8741
8742        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8743                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8744            if (!sUserManager.exists(userId)) return null;
8745            if (packageServices == null) {
8746                return null;
8747            }
8748            mFlags = flags;
8749            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8750            final int N = packageServices.size();
8751            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8752                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8753
8754            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8755            for (int i = 0; i < N; ++i) {
8756                intentFilters = packageServices.get(i).intents;
8757                if (intentFilters != null && intentFilters.size() > 0) {
8758                    PackageParser.ServiceIntentInfo[] array =
8759                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8760                    intentFilters.toArray(array);
8761                    listCut.add(array);
8762                }
8763            }
8764            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8765        }
8766
8767        public final void addService(PackageParser.Service s) {
8768            mServices.put(s.getComponentName(), s);
8769            if (DEBUG_SHOW_INFO) {
8770                Log.v(TAG, "  "
8771                        + (s.info.nonLocalizedLabel != null
8772                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8773                Log.v(TAG, "    Class=" + s.info.name);
8774            }
8775            final int NI = s.intents.size();
8776            int j;
8777            for (j=0; j<NI; j++) {
8778                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8779                if (DEBUG_SHOW_INFO) {
8780                    Log.v(TAG, "    IntentFilter:");
8781                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8782                }
8783                if (!intent.debugCheck()) {
8784                    Log.w(TAG, "==> For Service " + s.info.name);
8785                }
8786                addFilter(intent);
8787            }
8788        }
8789
8790        public final void removeService(PackageParser.Service s) {
8791            mServices.remove(s.getComponentName());
8792            if (DEBUG_SHOW_INFO) {
8793                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8794                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8795                Log.v(TAG, "    Class=" + s.info.name);
8796            }
8797            final int NI = s.intents.size();
8798            int j;
8799            for (j=0; j<NI; j++) {
8800                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8801                if (DEBUG_SHOW_INFO) {
8802                    Log.v(TAG, "    IntentFilter:");
8803                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8804                }
8805                removeFilter(intent);
8806            }
8807        }
8808
8809        @Override
8810        protected boolean allowFilterResult(
8811                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8812            ServiceInfo filterSi = filter.service.info;
8813            for (int i=dest.size()-1; i>=0; i--) {
8814                ServiceInfo destAi = dest.get(i).serviceInfo;
8815                if (destAi.name == filterSi.name
8816                        && destAi.packageName == filterSi.packageName) {
8817                    return false;
8818                }
8819            }
8820            return true;
8821        }
8822
8823        @Override
8824        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8825            return new PackageParser.ServiceIntentInfo[size];
8826        }
8827
8828        @Override
8829        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8830            if (!sUserManager.exists(userId)) return true;
8831            PackageParser.Package p = filter.service.owner;
8832            if (p != null) {
8833                PackageSetting ps = (PackageSetting)p.mExtras;
8834                if (ps != null) {
8835                    // System apps are never considered stopped for purposes of
8836                    // filtering, because there may be no way for the user to
8837                    // actually re-launch them.
8838                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8839                            && ps.getStopped(userId);
8840                }
8841            }
8842            return false;
8843        }
8844
8845        @Override
8846        protected boolean isPackageForFilter(String packageName,
8847                PackageParser.ServiceIntentInfo info) {
8848            return packageName.equals(info.service.owner.packageName);
8849        }
8850
8851        @Override
8852        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8853                int match, int userId) {
8854            if (!sUserManager.exists(userId)) return null;
8855            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8856            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8857                return null;
8858            }
8859            final PackageParser.Service service = info.service;
8860            if (mSafeMode && (service.info.applicationInfo.flags
8861                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8862                return null;
8863            }
8864            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8865            if (ps == null) {
8866                return null;
8867            }
8868            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8869                    ps.readUserState(userId), userId);
8870            if (si == null) {
8871                return null;
8872            }
8873            final ResolveInfo res = new ResolveInfo();
8874            res.serviceInfo = si;
8875            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8876                res.filter = filter;
8877            }
8878            res.priority = info.getPriority();
8879            res.preferredOrder = service.owner.mPreferredOrder;
8880            res.match = match;
8881            res.isDefault = info.hasDefault;
8882            res.labelRes = info.labelRes;
8883            res.nonLocalizedLabel = info.nonLocalizedLabel;
8884            res.icon = info.icon;
8885            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8886            return res;
8887        }
8888
8889        @Override
8890        protected void sortResults(List<ResolveInfo> results) {
8891            Collections.sort(results, mResolvePrioritySorter);
8892        }
8893
8894        @Override
8895        protected void dumpFilter(PrintWriter out, String prefix,
8896                PackageParser.ServiceIntentInfo filter) {
8897            out.print(prefix); out.print(
8898                    Integer.toHexString(System.identityHashCode(filter.service)));
8899                    out.print(' ');
8900                    filter.service.printComponentShortName(out);
8901                    out.print(" filter ");
8902                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8903        }
8904
8905        @Override
8906        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8907            return filter.service;
8908        }
8909
8910        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8911            PackageParser.Service service = (PackageParser.Service)label;
8912            out.print(prefix); out.print(
8913                    Integer.toHexString(System.identityHashCode(service)));
8914                    out.print(' ');
8915                    service.printComponentShortName(out);
8916            if (count > 1) {
8917                out.print(" ("); out.print(count); out.print(" filters)");
8918            }
8919            out.println();
8920        }
8921
8922//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8923//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8924//            final List<ResolveInfo> retList = Lists.newArrayList();
8925//            while (i.hasNext()) {
8926//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8927//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8928//                    retList.add(resolveInfo);
8929//                }
8930//            }
8931//            return retList;
8932//        }
8933
8934        // Keys are String (activity class name), values are Activity.
8935        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8936                = new ArrayMap<ComponentName, PackageParser.Service>();
8937        private int mFlags;
8938    };
8939
8940    private final class ProviderIntentResolver
8941            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8942        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8943                boolean defaultOnly, int userId) {
8944            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8945            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8946        }
8947
8948        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8949                int userId) {
8950            if (!sUserManager.exists(userId))
8951                return null;
8952            mFlags = flags;
8953            return super.queryIntent(intent, resolvedType,
8954                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8955        }
8956
8957        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8958                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8959            if (!sUserManager.exists(userId))
8960                return null;
8961            if (packageProviders == null) {
8962                return null;
8963            }
8964            mFlags = flags;
8965            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8966            final int N = packageProviders.size();
8967            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8968                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8969
8970            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8971            for (int i = 0; i < N; ++i) {
8972                intentFilters = packageProviders.get(i).intents;
8973                if (intentFilters != null && intentFilters.size() > 0) {
8974                    PackageParser.ProviderIntentInfo[] array =
8975                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8976                    intentFilters.toArray(array);
8977                    listCut.add(array);
8978                }
8979            }
8980            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8981        }
8982
8983        public final void addProvider(PackageParser.Provider p) {
8984            if (mProviders.containsKey(p.getComponentName())) {
8985                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8986                return;
8987            }
8988
8989            mProviders.put(p.getComponentName(), p);
8990            if (DEBUG_SHOW_INFO) {
8991                Log.v(TAG, "  "
8992                        + (p.info.nonLocalizedLabel != null
8993                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8994                Log.v(TAG, "    Class=" + p.info.name);
8995            }
8996            final int NI = p.intents.size();
8997            int j;
8998            for (j = 0; j < NI; j++) {
8999                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9000                if (DEBUG_SHOW_INFO) {
9001                    Log.v(TAG, "    IntentFilter:");
9002                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9003                }
9004                if (!intent.debugCheck()) {
9005                    Log.w(TAG, "==> For Provider " + p.info.name);
9006                }
9007                addFilter(intent);
9008            }
9009        }
9010
9011        public final void removeProvider(PackageParser.Provider p) {
9012            mProviders.remove(p.getComponentName());
9013            if (DEBUG_SHOW_INFO) {
9014                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9015                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9016                Log.v(TAG, "    Class=" + p.info.name);
9017            }
9018            final int NI = p.intents.size();
9019            int j;
9020            for (j = 0; j < NI; j++) {
9021                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9022                if (DEBUG_SHOW_INFO) {
9023                    Log.v(TAG, "    IntentFilter:");
9024                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9025                }
9026                removeFilter(intent);
9027            }
9028        }
9029
9030        @Override
9031        protected boolean allowFilterResult(
9032                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9033            ProviderInfo filterPi = filter.provider.info;
9034            for (int i = dest.size() - 1; i >= 0; i--) {
9035                ProviderInfo destPi = dest.get(i).providerInfo;
9036                if (destPi.name == filterPi.name
9037                        && destPi.packageName == filterPi.packageName) {
9038                    return false;
9039                }
9040            }
9041            return true;
9042        }
9043
9044        @Override
9045        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9046            return new PackageParser.ProviderIntentInfo[size];
9047        }
9048
9049        @Override
9050        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9051            if (!sUserManager.exists(userId))
9052                return true;
9053            PackageParser.Package p = filter.provider.owner;
9054            if (p != null) {
9055                PackageSetting ps = (PackageSetting) p.mExtras;
9056                if (ps != null) {
9057                    // System apps are never considered stopped for purposes of
9058                    // filtering, because there may be no way for the user to
9059                    // actually re-launch them.
9060                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9061                            && ps.getStopped(userId);
9062                }
9063            }
9064            return false;
9065        }
9066
9067        @Override
9068        protected boolean isPackageForFilter(String packageName,
9069                PackageParser.ProviderIntentInfo info) {
9070            return packageName.equals(info.provider.owner.packageName);
9071        }
9072
9073        @Override
9074        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9075                int match, int userId) {
9076            if (!sUserManager.exists(userId))
9077                return null;
9078            final PackageParser.ProviderIntentInfo info = filter;
9079            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9080                return null;
9081            }
9082            final PackageParser.Provider provider = info.provider;
9083            if (mSafeMode && (provider.info.applicationInfo.flags
9084                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9085                return null;
9086            }
9087            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9088            if (ps == null) {
9089                return null;
9090            }
9091            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9092                    ps.readUserState(userId), userId);
9093            if (pi == null) {
9094                return null;
9095            }
9096            final ResolveInfo res = new ResolveInfo();
9097            res.providerInfo = pi;
9098            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9099                res.filter = filter;
9100            }
9101            res.priority = info.getPriority();
9102            res.preferredOrder = provider.owner.mPreferredOrder;
9103            res.match = match;
9104            res.isDefault = info.hasDefault;
9105            res.labelRes = info.labelRes;
9106            res.nonLocalizedLabel = info.nonLocalizedLabel;
9107            res.icon = info.icon;
9108            res.system = res.providerInfo.applicationInfo.isSystemApp();
9109            return res;
9110        }
9111
9112        @Override
9113        protected void sortResults(List<ResolveInfo> results) {
9114            Collections.sort(results, mResolvePrioritySorter);
9115        }
9116
9117        @Override
9118        protected void dumpFilter(PrintWriter out, String prefix,
9119                PackageParser.ProviderIntentInfo filter) {
9120            out.print(prefix);
9121            out.print(
9122                    Integer.toHexString(System.identityHashCode(filter.provider)));
9123            out.print(' ');
9124            filter.provider.printComponentShortName(out);
9125            out.print(" filter ");
9126            out.println(Integer.toHexString(System.identityHashCode(filter)));
9127        }
9128
9129        @Override
9130        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9131            return filter.provider;
9132        }
9133
9134        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9135            PackageParser.Provider provider = (PackageParser.Provider)label;
9136            out.print(prefix); out.print(
9137                    Integer.toHexString(System.identityHashCode(provider)));
9138                    out.print(' ');
9139                    provider.printComponentShortName(out);
9140            if (count > 1) {
9141                out.print(" ("); out.print(count); out.print(" filters)");
9142            }
9143            out.println();
9144        }
9145
9146        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9147                = new ArrayMap<ComponentName, PackageParser.Provider>();
9148        private int mFlags;
9149    };
9150
9151    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9152            new Comparator<ResolveInfo>() {
9153        public int compare(ResolveInfo r1, ResolveInfo r2) {
9154            int v1 = r1.priority;
9155            int v2 = r2.priority;
9156            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9157            if (v1 != v2) {
9158                return (v1 > v2) ? -1 : 1;
9159            }
9160            v1 = r1.preferredOrder;
9161            v2 = r2.preferredOrder;
9162            if (v1 != v2) {
9163                return (v1 > v2) ? -1 : 1;
9164            }
9165            if (r1.isDefault != r2.isDefault) {
9166                return r1.isDefault ? -1 : 1;
9167            }
9168            v1 = r1.match;
9169            v2 = r2.match;
9170            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9171            if (v1 != v2) {
9172                return (v1 > v2) ? -1 : 1;
9173            }
9174            if (r1.system != r2.system) {
9175                return r1.system ? -1 : 1;
9176            }
9177            return 0;
9178        }
9179    };
9180
9181    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9182            new Comparator<ProviderInfo>() {
9183        public int compare(ProviderInfo p1, ProviderInfo p2) {
9184            final int v1 = p1.initOrder;
9185            final int v2 = p2.initOrder;
9186            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9187        }
9188    };
9189
9190    final void sendPackageBroadcast(final String action, final String pkg,
9191            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9192            final int[] userIds) {
9193        mHandler.post(new Runnable() {
9194            @Override
9195            public void run() {
9196                try {
9197                    final IActivityManager am = ActivityManagerNative.getDefault();
9198                    if (am == null) return;
9199                    final int[] resolvedUserIds;
9200                    if (userIds == null) {
9201                        resolvedUserIds = am.getRunningUserIds();
9202                    } else {
9203                        resolvedUserIds = userIds;
9204                    }
9205                    for (int id : resolvedUserIds) {
9206                        final Intent intent = new Intent(action,
9207                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9208                        if (extras != null) {
9209                            intent.putExtras(extras);
9210                        }
9211                        if (targetPkg != null) {
9212                            intent.setPackage(targetPkg);
9213                        }
9214                        // Modify the UID when posting to other users
9215                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9216                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9217                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9218                            intent.putExtra(Intent.EXTRA_UID, uid);
9219                        }
9220                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9221                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9222                        if (DEBUG_BROADCASTS) {
9223                            RuntimeException here = new RuntimeException("here");
9224                            here.fillInStackTrace();
9225                            Slog.d(TAG, "Sending to user " + id + ": "
9226                                    + intent.toShortString(false, true, false, false)
9227                                    + " " + intent.getExtras(), here);
9228                        }
9229                        am.broadcastIntent(null, intent, null, finishedReceiver,
9230                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9231                                null, finishedReceiver != null, false, id);
9232                    }
9233                } catch (RemoteException ex) {
9234                }
9235            }
9236        });
9237    }
9238
9239    /**
9240     * Check if the external storage media is available. This is true if there
9241     * is a mounted external storage medium or if the external storage is
9242     * emulated.
9243     */
9244    private boolean isExternalMediaAvailable() {
9245        return mMediaMounted || Environment.isExternalStorageEmulated();
9246    }
9247
9248    @Override
9249    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9250        // writer
9251        synchronized (mPackages) {
9252            if (!isExternalMediaAvailable()) {
9253                // If the external storage is no longer mounted at this point,
9254                // the caller may not have been able to delete all of this
9255                // packages files and can not delete any more.  Bail.
9256                return null;
9257            }
9258            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9259            if (lastPackage != null) {
9260                pkgs.remove(lastPackage);
9261            }
9262            if (pkgs.size() > 0) {
9263                return pkgs.get(0);
9264            }
9265        }
9266        return null;
9267    }
9268
9269    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9270        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9271                userId, andCode ? 1 : 0, packageName);
9272        if (mSystemReady) {
9273            msg.sendToTarget();
9274        } else {
9275            if (mPostSystemReadyMessages == null) {
9276                mPostSystemReadyMessages = new ArrayList<>();
9277            }
9278            mPostSystemReadyMessages.add(msg);
9279        }
9280    }
9281
9282    void startCleaningPackages() {
9283        // reader
9284        synchronized (mPackages) {
9285            if (!isExternalMediaAvailable()) {
9286                return;
9287            }
9288            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9289                return;
9290            }
9291        }
9292        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9293        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9294        IActivityManager am = ActivityManagerNative.getDefault();
9295        if (am != null) {
9296            try {
9297                am.startService(null, intent, null, mContext.getOpPackageName(),
9298                        UserHandle.USER_OWNER);
9299            } catch (RemoteException e) {
9300            }
9301        }
9302    }
9303
9304    @Override
9305    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9306            int installFlags, String installerPackageName, VerificationParams verificationParams,
9307            String packageAbiOverride) {
9308        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9309                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9310    }
9311
9312    @Override
9313    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9314            int installFlags, String installerPackageName, VerificationParams verificationParams,
9315            String packageAbiOverride, int userId) {
9316        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9317
9318        final int callingUid = Binder.getCallingUid();
9319        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9320
9321        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9322            try {
9323                if (observer != null) {
9324                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9325                }
9326            } catch (RemoteException re) {
9327            }
9328            return;
9329        }
9330
9331        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9332            installFlags |= PackageManager.INSTALL_FROM_ADB;
9333
9334        } else {
9335            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9336            // about installerPackageName.
9337
9338            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9339            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9340        }
9341
9342        UserHandle user;
9343        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9344            user = UserHandle.ALL;
9345        } else {
9346            user = new UserHandle(userId);
9347        }
9348
9349        // Only system components can circumvent runtime permissions when installing.
9350        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9351                && mContext.checkCallingOrSelfPermission(Manifest.permission
9352                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9353            throw new SecurityException("You need the "
9354                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9355                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9356        }
9357
9358        verificationParams.setInstallerUid(callingUid);
9359
9360        final File originFile = new File(originPath);
9361        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9362
9363        final Message msg = mHandler.obtainMessage(INIT_COPY);
9364        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9365                null, verificationParams, user, packageAbiOverride);
9366        mHandler.sendMessage(msg);
9367    }
9368
9369    void installStage(String packageName, File stagedDir, String stagedCid,
9370            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9371            String installerPackageName, int installerUid, UserHandle user) {
9372        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9373                params.referrerUri, installerUid, null);
9374        verifParams.setInstallerUid(installerUid);
9375
9376        final OriginInfo origin;
9377        if (stagedDir != null) {
9378            origin = OriginInfo.fromStagedFile(stagedDir);
9379        } else {
9380            origin = OriginInfo.fromStagedContainer(stagedCid);
9381        }
9382
9383        final Message msg = mHandler.obtainMessage(INIT_COPY);
9384        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9385                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9386        mHandler.sendMessage(msg);
9387    }
9388
9389    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9390        Bundle extras = new Bundle(1);
9391        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9392
9393        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9394                packageName, extras, null, null, new int[] {userId});
9395        try {
9396            IActivityManager am = ActivityManagerNative.getDefault();
9397            final boolean isSystem =
9398                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9399            if (isSystem && am.isUserRunning(userId, false)) {
9400                // The just-installed/enabled app is bundled on the system, so presumed
9401                // to be able to run automatically without needing an explicit launch.
9402                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9403                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9404                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9405                        .setPackage(packageName);
9406                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9407                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9408            }
9409        } catch (RemoteException e) {
9410            // shouldn't happen
9411            Slog.w(TAG, "Unable to bootstrap installed package", e);
9412        }
9413    }
9414
9415    @Override
9416    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9417            int userId) {
9418        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9419        PackageSetting pkgSetting;
9420        final int uid = Binder.getCallingUid();
9421        enforceCrossUserPermission(uid, userId, true, true,
9422                "setApplicationHiddenSetting for user " + userId);
9423
9424        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9425            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9426            return false;
9427        }
9428
9429        long callingId = Binder.clearCallingIdentity();
9430        try {
9431            boolean sendAdded = false;
9432            boolean sendRemoved = false;
9433            // writer
9434            synchronized (mPackages) {
9435                pkgSetting = mSettings.mPackages.get(packageName);
9436                if (pkgSetting == null) {
9437                    return false;
9438                }
9439                if (pkgSetting.getHidden(userId) != hidden) {
9440                    pkgSetting.setHidden(hidden, userId);
9441                    mSettings.writePackageRestrictionsLPr(userId);
9442                    if (hidden) {
9443                        sendRemoved = true;
9444                    } else {
9445                        sendAdded = true;
9446                    }
9447                }
9448            }
9449            if (sendAdded) {
9450                sendPackageAddedForUser(packageName, pkgSetting, userId);
9451                return true;
9452            }
9453            if (sendRemoved) {
9454                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9455                        "hiding pkg");
9456                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9457            }
9458        } finally {
9459            Binder.restoreCallingIdentity(callingId);
9460        }
9461        return false;
9462    }
9463
9464    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9465            int userId) {
9466        final PackageRemovedInfo info = new PackageRemovedInfo();
9467        info.removedPackage = packageName;
9468        info.removedUsers = new int[] {userId};
9469        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9470        info.sendBroadcast(false, false, false);
9471    }
9472
9473    /**
9474     * Returns true if application is not found or there was an error. Otherwise it returns
9475     * the hidden state of the package for the given user.
9476     */
9477    @Override
9478    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9479        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9480        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9481                false, "getApplicationHidden for user " + userId);
9482        PackageSetting pkgSetting;
9483        long callingId = Binder.clearCallingIdentity();
9484        try {
9485            // writer
9486            synchronized (mPackages) {
9487                pkgSetting = mSettings.mPackages.get(packageName);
9488                if (pkgSetting == null) {
9489                    return true;
9490                }
9491                return pkgSetting.getHidden(userId);
9492            }
9493        } finally {
9494            Binder.restoreCallingIdentity(callingId);
9495        }
9496    }
9497
9498    /**
9499     * @hide
9500     */
9501    @Override
9502    public int installExistingPackageAsUser(String packageName, int userId) {
9503        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9504                null);
9505        PackageSetting pkgSetting;
9506        final int uid = Binder.getCallingUid();
9507        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9508                + userId);
9509        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9510            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9511        }
9512
9513        long callingId = Binder.clearCallingIdentity();
9514        try {
9515            boolean sendAdded = false;
9516
9517            // writer
9518            synchronized (mPackages) {
9519                pkgSetting = mSettings.mPackages.get(packageName);
9520                if (pkgSetting == null) {
9521                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9522                }
9523                if (!pkgSetting.getInstalled(userId)) {
9524                    pkgSetting.setInstalled(true, userId);
9525                    pkgSetting.setHidden(false, userId);
9526                    mSettings.writePackageRestrictionsLPr(userId);
9527                    sendAdded = true;
9528                }
9529            }
9530
9531            if (sendAdded) {
9532                sendPackageAddedForUser(packageName, pkgSetting, userId);
9533            }
9534        } finally {
9535            Binder.restoreCallingIdentity(callingId);
9536        }
9537
9538        return PackageManager.INSTALL_SUCCEEDED;
9539    }
9540
9541    boolean isUserRestricted(int userId, String restrictionKey) {
9542        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9543        if (restrictions.getBoolean(restrictionKey, false)) {
9544            Log.w(TAG, "User is restricted: " + restrictionKey);
9545            return true;
9546        }
9547        return false;
9548    }
9549
9550    @Override
9551    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9552        mContext.enforceCallingOrSelfPermission(
9553                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9554                "Only package verification agents can verify applications");
9555
9556        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9557        final PackageVerificationResponse response = new PackageVerificationResponse(
9558                verificationCode, Binder.getCallingUid());
9559        msg.arg1 = id;
9560        msg.obj = response;
9561        mHandler.sendMessage(msg);
9562    }
9563
9564    @Override
9565    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9566            long millisecondsToDelay) {
9567        mContext.enforceCallingOrSelfPermission(
9568                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9569                "Only package verification agents can extend verification timeouts");
9570
9571        final PackageVerificationState state = mPendingVerification.get(id);
9572        final PackageVerificationResponse response = new PackageVerificationResponse(
9573                verificationCodeAtTimeout, Binder.getCallingUid());
9574
9575        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9576            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9577        }
9578        if (millisecondsToDelay < 0) {
9579            millisecondsToDelay = 0;
9580        }
9581        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9582                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9583            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9584        }
9585
9586        if ((state != null) && !state.timeoutExtended()) {
9587            state.extendTimeout();
9588
9589            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9590            msg.arg1 = id;
9591            msg.obj = response;
9592            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9593        }
9594    }
9595
9596    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9597            int verificationCode, UserHandle user) {
9598        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9599        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9600        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9601        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9602        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9603
9604        mContext.sendBroadcastAsUser(intent, user,
9605                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9606    }
9607
9608    private ComponentName matchComponentForVerifier(String packageName,
9609            List<ResolveInfo> receivers) {
9610        ActivityInfo targetReceiver = null;
9611
9612        final int NR = receivers.size();
9613        for (int i = 0; i < NR; i++) {
9614            final ResolveInfo info = receivers.get(i);
9615            if (info.activityInfo == null) {
9616                continue;
9617            }
9618
9619            if (packageName.equals(info.activityInfo.packageName)) {
9620                targetReceiver = info.activityInfo;
9621                break;
9622            }
9623        }
9624
9625        if (targetReceiver == null) {
9626            return null;
9627        }
9628
9629        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9630    }
9631
9632    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9633            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9634        if (pkgInfo.verifiers.length == 0) {
9635            return null;
9636        }
9637
9638        final int N = pkgInfo.verifiers.length;
9639        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9640        for (int i = 0; i < N; i++) {
9641            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9642
9643            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9644                    receivers);
9645            if (comp == null) {
9646                continue;
9647            }
9648
9649            final int verifierUid = getUidForVerifier(verifierInfo);
9650            if (verifierUid == -1) {
9651                continue;
9652            }
9653
9654            if (DEBUG_VERIFY) {
9655                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9656                        + " with the correct signature");
9657            }
9658            sufficientVerifiers.add(comp);
9659            verificationState.addSufficientVerifier(verifierUid);
9660        }
9661
9662        return sufficientVerifiers;
9663    }
9664
9665    private int getUidForVerifier(VerifierInfo verifierInfo) {
9666        synchronized (mPackages) {
9667            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9668            if (pkg == null) {
9669                return -1;
9670            } else if (pkg.mSignatures.length != 1) {
9671                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9672                        + " has more than one signature; ignoring");
9673                return -1;
9674            }
9675
9676            /*
9677             * If the public key of the package's signature does not match
9678             * our expected public key, then this is a different package and
9679             * we should skip.
9680             */
9681
9682            final byte[] expectedPublicKey;
9683            try {
9684                final Signature verifierSig = pkg.mSignatures[0];
9685                final PublicKey publicKey = verifierSig.getPublicKey();
9686                expectedPublicKey = publicKey.getEncoded();
9687            } catch (CertificateException e) {
9688                return -1;
9689            }
9690
9691            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9692
9693            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9694                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9695                        + " does not have the expected public key; ignoring");
9696                return -1;
9697            }
9698
9699            return pkg.applicationInfo.uid;
9700        }
9701    }
9702
9703    @Override
9704    public void finishPackageInstall(int token) {
9705        enforceSystemOrRoot("Only the system is allowed to finish installs");
9706
9707        if (DEBUG_INSTALL) {
9708            Slog.v(TAG, "BM finishing package install for " + token);
9709        }
9710
9711        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9712        mHandler.sendMessage(msg);
9713    }
9714
9715    /**
9716     * Get the verification agent timeout.
9717     *
9718     * @return verification timeout in milliseconds
9719     */
9720    private long getVerificationTimeout() {
9721        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9722                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9723                DEFAULT_VERIFICATION_TIMEOUT);
9724    }
9725
9726    /**
9727     * Get the default verification agent response code.
9728     *
9729     * @return default verification response code
9730     */
9731    private int getDefaultVerificationResponse() {
9732        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9733                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9734                DEFAULT_VERIFICATION_RESPONSE);
9735    }
9736
9737    /**
9738     * Check whether or not package verification has been enabled.
9739     *
9740     * @return true if verification should be performed
9741     */
9742    private boolean isVerificationEnabled(int userId, int installFlags) {
9743        if (!DEFAULT_VERIFY_ENABLE) {
9744            return false;
9745        }
9746
9747        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9748
9749        // Check if installing from ADB
9750        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9751            // Do not run verification in a test harness environment
9752            if (ActivityManager.isRunningInTestHarness()) {
9753                return false;
9754            }
9755            if (ensureVerifyAppsEnabled) {
9756                return true;
9757            }
9758            // Check if the developer does not want package verification for ADB installs
9759            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9760                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9761                return false;
9762            }
9763        }
9764
9765        if (ensureVerifyAppsEnabled) {
9766            return true;
9767        }
9768
9769        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9770                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9771    }
9772
9773    @Override
9774    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9775            throws RemoteException {
9776        mContext.enforceCallingOrSelfPermission(
9777                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9778                "Only intentfilter verification agents can verify applications");
9779
9780        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9781        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9782                Binder.getCallingUid(), verificationCode, failedDomains);
9783        msg.arg1 = id;
9784        msg.obj = response;
9785        mHandler.sendMessage(msg);
9786    }
9787
9788    @Override
9789    public int getIntentVerificationStatus(String packageName, int userId) {
9790        synchronized (mPackages) {
9791            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9792        }
9793    }
9794
9795    @Override
9796    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9797        mContext.enforceCallingOrSelfPermission(
9798                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9799
9800        boolean result = false;
9801        synchronized (mPackages) {
9802            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9803        }
9804        if (result) {
9805            scheduleWritePackageRestrictionsLocked(userId);
9806        }
9807        return result;
9808    }
9809
9810    @Override
9811    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9812        synchronized (mPackages) {
9813            return mSettings.getIntentFilterVerificationsLPr(packageName);
9814        }
9815    }
9816
9817    @Override
9818    public List<IntentFilter> getAllIntentFilters(String packageName) {
9819        if (TextUtils.isEmpty(packageName)) {
9820            return Collections.<IntentFilter>emptyList();
9821        }
9822        synchronized (mPackages) {
9823            PackageParser.Package pkg = mPackages.get(packageName);
9824            if (pkg == null || pkg.activities == null) {
9825                return Collections.<IntentFilter>emptyList();
9826            }
9827            final int count = pkg.activities.size();
9828            ArrayList<IntentFilter> result = new ArrayList<>();
9829            for (int n=0; n<count; n++) {
9830                PackageParser.Activity activity = pkg.activities.get(n);
9831                if (activity.intents != null || activity.intents.size() > 0) {
9832                    result.addAll(activity.intents);
9833                }
9834            }
9835            return result;
9836        }
9837    }
9838
9839    @Override
9840    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9841        mContext.enforceCallingOrSelfPermission(
9842                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9843
9844        synchronized (mPackages) {
9845            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9846            if (packageName != null) {
9847                result |= updateIntentVerificationStatus(packageName,
9848                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9849                        UserHandle.myUserId());
9850                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9851                        packageName, userId);
9852            }
9853            return result;
9854        }
9855    }
9856
9857    @Override
9858    public String getDefaultBrowserPackageName(int userId) {
9859        synchronized (mPackages) {
9860            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9861        }
9862    }
9863
9864    /**
9865     * Get the "allow unknown sources" setting.
9866     *
9867     * @return the current "allow unknown sources" setting
9868     */
9869    private int getUnknownSourcesSettings() {
9870        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9871                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9872                -1);
9873    }
9874
9875    @Override
9876    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9877        final int uid = Binder.getCallingUid();
9878        // writer
9879        synchronized (mPackages) {
9880            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9881            if (targetPackageSetting == null) {
9882                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9883            }
9884
9885            PackageSetting installerPackageSetting;
9886            if (installerPackageName != null) {
9887                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9888                if (installerPackageSetting == null) {
9889                    throw new IllegalArgumentException("Unknown installer package: "
9890                            + installerPackageName);
9891                }
9892            } else {
9893                installerPackageSetting = null;
9894            }
9895
9896            Signature[] callerSignature;
9897            Object obj = mSettings.getUserIdLPr(uid);
9898            if (obj != null) {
9899                if (obj instanceof SharedUserSetting) {
9900                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9901                } else if (obj instanceof PackageSetting) {
9902                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9903                } else {
9904                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9905                }
9906            } else {
9907                throw new SecurityException("Unknown calling uid " + uid);
9908            }
9909
9910            // Verify: can't set installerPackageName to a package that is
9911            // not signed with the same cert as the caller.
9912            if (installerPackageSetting != null) {
9913                if (compareSignatures(callerSignature,
9914                        installerPackageSetting.signatures.mSignatures)
9915                        != PackageManager.SIGNATURE_MATCH) {
9916                    throw new SecurityException(
9917                            "Caller does not have same cert as new installer package "
9918                            + installerPackageName);
9919                }
9920            }
9921
9922            // Verify: if target already has an installer package, it must
9923            // be signed with the same cert as the caller.
9924            if (targetPackageSetting.installerPackageName != null) {
9925                PackageSetting setting = mSettings.mPackages.get(
9926                        targetPackageSetting.installerPackageName);
9927                // If the currently set package isn't valid, then it's always
9928                // okay to change it.
9929                if (setting != null) {
9930                    if (compareSignatures(callerSignature,
9931                            setting.signatures.mSignatures)
9932                            != PackageManager.SIGNATURE_MATCH) {
9933                        throw new SecurityException(
9934                                "Caller does not have same cert as old installer package "
9935                                + targetPackageSetting.installerPackageName);
9936                    }
9937                }
9938            }
9939
9940            // Okay!
9941            targetPackageSetting.installerPackageName = installerPackageName;
9942            scheduleWriteSettingsLocked();
9943        }
9944    }
9945
9946    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9947        // Queue up an async operation since the package installation may take a little while.
9948        mHandler.post(new Runnable() {
9949            public void run() {
9950                mHandler.removeCallbacks(this);
9951                 // Result object to be returned
9952                PackageInstalledInfo res = new PackageInstalledInfo();
9953                res.returnCode = currentStatus;
9954                res.uid = -1;
9955                res.pkg = null;
9956                res.removedInfo = new PackageRemovedInfo();
9957                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9958                    args.doPreInstall(res.returnCode);
9959                    synchronized (mInstallLock) {
9960                        installPackageLI(args, res);
9961                    }
9962                    args.doPostInstall(res.returnCode, res.uid);
9963                }
9964
9965                // A restore should be performed at this point if (a) the install
9966                // succeeded, (b) the operation is not an update, and (c) the new
9967                // package has not opted out of backup participation.
9968                final boolean update = res.removedInfo.removedPackage != null;
9969                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9970                boolean doRestore = !update
9971                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9972
9973                // Set up the post-install work request bookkeeping.  This will be used
9974                // and cleaned up by the post-install event handling regardless of whether
9975                // there's a restore pass performed.  Token values are >= 1.
9976                int token;
9977                if (mNextInstallToken < 0) mNextInstallToken = 1;
9978                token = mNextInstallToken++;
9979
9980                PostInstallData data = new PostInstallData(args, res);
9981                mRunningInstalls.put(token, data);
9982                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9983
9984                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9985                    // Pass responsibility to the Backup Manager.  It will perform a
9986                    // restore if appropriate, then pass responsibility back to the
9987                    // Package Manager to run the post-install observer callbacks
9988                    // and broadcasts.
9989                    IBackupManager bm = IBackupManager.Stub.asInterface(
9990                            ServiceManager.getService(Context.BACKUP_SERVICE));
9991                    if (bm != null) {
9992                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9993                                + " to BM for possible restore");
9994                        try {
9995                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9996                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9997                            } else {
9998                                doRestore = false;
9999                            }
10000                        } catch (RemoteException e) {
10001                            // can't happen; the backup manager is local
10002                        } catch (Exception e) {
10003                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10004                            doRestore = false;
10005                        }
10006                    } else {
10007                        Slog.e(TAG, "Backup Manager not found!");
10008                        doRestore = false;
10009                    }
10010                }
10011
10012                if (!doRestore) {
10013                    // No restore possible, or the Backup Manager was mysteriously not
10014                    // available -- just fire the post-install work request directly.
10015                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10016                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10017                    mHandler.sendMessage(msg);
10018                }
10019            }
10020        });
10021    }
10022
10023    private abstract class HandlerParams {
10024        private static final int MAX_RETRIES = 4;
10025
10026        /**
10027         * Number of times startCopy() has been attempted and had a non-fatal
10028         * error.
10029         */
10030        private int mRetries = 0;
10031
10032        /** User handle for the user requesting the information or installation. */
10033        private final UserHandle mUser;
10034
10035        HandlerParams(UserHandle user) {
10036            mUser = user;
10037        }
10038
10039        UserHandle getUser() {
10040            return mUser;
10041        }
10042
10043        final boolean startCopy() {
10044            boolean res;
10045            try {
10046                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10047
10048                if (++mRetries > MAX_RETRIES) {
10049                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10050                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10051                    handleServiceError();
10052                    return false;
10053                } else {
10054                    handleStartCopy();
10055                    res = true;
10056                }
10057            } catch (RemoteException e) {
10058                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10059                mHandler.sendEmptyMessage(MCS_RECONNECT);
10060                res = false;
10061            }
10062            handleReturnCode();
10063            return res;
10064        }
10065
10066        final void serviceError() {
10067            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10068            handleServiceError();
10069            handleReturnCode();
10070        }
10071
10072        abstract void handleStartCopy() throws RemoteException;
10073        abstract void handleServiceError();
10074        abstract void handleReturnCode();
10075    }
10076
10077    class MeasureParams extends HandlerParams {
10078        private final PackageStats mStats;
10079        private boolean mSuccess;
10080
10081        private final IPackageStatsObserver mObserver;
10082
10083        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10084            super(new UserHandle(stats.userHandle));
10085            mObserver = observer;
10086            mStats = stats;
10087        }
10088
10089        @Override
10090        public String toString() {
10091            return "MeasureParams{"
10092                + Integer.toHexString(System.identityHashCode(this))
10093                + " " + mStats.packageName + "}";
10094        }
10095
10096        @Override
10097        void handleStartCopy() throws RemoteException {
10098            synchronized (mInstallLock) {
10099                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10100            }
10101
10102            if (mSuccess) {
10103                final boolean mounted;
10104                if (Environment.isExternalStorageEmulated()) {
10105                    mounted = true;
10106                } else {
10107                    final String status = Environment.getExternalStorageState();
10108                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10109                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10110                }
10111
10112                if (mounted) {
10113                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10114
10115                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10116                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10117
10118                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10119                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10120
10121                    // Always subtract cache size, since it's a subdirectory
10122                    mStats.externalDataSize -= mStats.externalCacheSize;
10123
10124                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10125                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10126
10127                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10128                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10129                }
10130            }
10131        }
10132
10133        @Override
10134        void handleReturnCode() {
10135            if (mObserver != null) {
10136                try {
10137                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10138                } catch (RemoteException e) {
10139                    Slog.i(TAG, "Observer no longer exists.");
10140                }
10141            }
10142        }
10143
10144        @Override
10145        void handleServiceError() {
10146            Slog.e(TAG, "Could not measure application " + mStats.packageName
10147                            + " external storage");
10148        }
10149    }
10150
10151    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10152            throws RemoteException {
10153        long result = 0;
10154        for (File path : paths) {
10155            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10156        }
10157        return result;
10158    }
10159
10160    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10161        for (File path : paths) {
10162            try {
10163                mcs.clearDirectory(path.getAbsolutePath());
10164            } catch (RemoteException e) {
10165            }
10166        }
10167    }
10168
10169    static class OriginInfo {
10170        /**
10171         * Location where install is coming from, before it has been
10172         * copied/renamed into place. This could be a single monolithic APK
10173         * file, or a cluster directory. This location may be untrusted.
10174         */
10175        final File file;
10176        final String cid;
10177
10178        /**
10179         * Flag indicating that {@link #file} or {@link #cid} has already been
10180         * staged, meaning downstream users don't need to defensively copy the
10181         * contents.
10182         */
10183        final boolean staged;
10184
10185        /**
10186         * Flag indicating that {@link #file} or {@link #cid} is an already
10187         * installed app that is being moved.
10188         */
10189        final boolean existing;
10190
10191        final String resolvedPath;
10192        final File resolvedFile;
10193
10194        static OriginInfo fromNothing() {
10195            return new OriginInfo(null, null, false, false);
10196        }
10197
10198        static OriginInfo fromUntrustedFile(File file) {
10199            return new OriginInfo(file, null, false, false);
10200        }
10201
10202        static OriginInfo fromExistingFile(File file) {
10203            return new OriginInfo(file, null, false, true);
10204        }
10205
10206        static OriginInfo fromStagedFile(File file) {
10207            return new OriginInfo(file, null, true, false);
10208        }
10209
10210        static OriginInfo fromStagedContainer(String cid) {
10211            return new OriginInfo(null, cid, true, false);
10212        }
10213
10214        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10215            this.file = file;
10216            this.cid = cid;
10217            this.staged = staged;
10218            this.existing = existing;
10219
10220            if (cid != null) {
10221                resolvedPath = PackageHelper.getSdDir(cid);
10222                resolvedFile = new File(resolvedPath);
10223            } else if (file != null) {
10224                resolvedPath = file.getAbsolutePath();
10225                resolvedFile = file;
10226            } else {
10227                resolvedPath = null;
10228                resolvedFile = null;
10229            }
10230        }
10231    }
10232
10233    class MoveInfo {
10234        final int moveId;
10235        final String fromUuid;
10236        final String toUuid;
10237        final String packageName;
10238        final String dataAppName;
10239        final int appId;
10240        final String seinfo;
10241
10242        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10243                String dataAppName, int appId, String seinfo) {
10244            this.moveId = moveId;
10245            this.fromUuid = fromUuid;
10246            this.toUuid = toUuid;
10247            this.packageName = packageName;
10248            this.dataAppName = dataAppName;
10249            this.appId = appId;
10250            this.seinfo = seinfo;
10251        }
10252    }
10253
10254    class InstallParams extends HandlerParams {
10255        final OriginInfo origin;
10256        final MoveInfo move;
10257        final IPackageInstallObserver2 observer;
10258        int installFlags;
10259        final String installerPackageName;
10260        final String volumeUuid;
10261        final VerificationParams verificationParams;
10262        private InstallArgs mArgs;
10263        private int mRet;
10264        final String packageAbiOverride;
10265
10266        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10267                int installFlags, String installerPackageName, String volumeUuid,
10268                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10269            super(user);
10270            this.origin = origin;
10271            this.move = move;
10272            this.observer = observer;
10273            this.installFlags = installFlags;
10274            this.installerPackageName = installerPackageName;
10275            this.volumeUuid = volumeUuid;
10276            this.verificationParams = verificationParams;
10277            this.packageAbiOverride = packageAbiOverride;
10278        }
10279
10280        @Override
10281        public String toString() {
10282            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10283                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10284        }
10285
10286        public ManifestDigest getManifestDigest() {
10287            if (verificationParams == null) {
10288                return null;
10289            }
10290            return verificationParams.getManifestDigest();
10291        }
10292
10293        private int installLocationPolicy(PackageInfoLite pkgLite) {
10294            String packageName = pkgLite.packageName;
10295            int installLocation = pkgLite.installLocation;
10296            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10297            // reader
10298            synchronized (mPackages) {
10299                PackageParser.Package pkg = mPackages.get(packageName);
10300                if (pkg != null) {
10301                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10302                        // Check for downgrading.
10303                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10304                            try {
10305                                checkDowngrade(pkg, pkgLite);
10306                            } catch (PackageManagerException e) {
10307                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10308                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10309                            }
10310                        }
10311                        // Check for updated system application.
10312                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10313                            if (onSd) {
10314                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10315                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10316                            }
10317                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10318                        } else {
10319                            if (onSd) {
10320                                // Install flag overrides everything.
10321                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10322                            }
10323                            // If current upgrade specifies particular preference
10324                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10325                                // Application explicitly specified internal.
10326                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10327                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10328                                // App explictly prefers external. Let policy decide
10329                            } else {
10330                                // Prefer previous location
10331                                if (isExternal(pkg)) {
10332                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10333                                }
10334                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10335                            }
10336                        }
10337                    } else {
10338                        // Invalid install. Return error code
10339                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10340                    }
10341                }
10342            }
10343            // All the special cases have been taken care of.
10344            // Return result based on recommended install location.
10345            if (onSd) {
10346                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10347            }
10348            return pkgLite.recommendedInstallLocation;
10349        }
10350
10351        /*
10352         * Invoke remote method to get package information and install
10353         * location values. Override install location based on default
10354         * policy if needed and then create install arguments based
10355         * on the install location.
10356         */
10357        public void handleStartCopy() throws RemoteException {
10358            int ret = PackageManager.INSTALL_SUCCEEDED;
10359
10360            // If we're already staged, we've firmly committed to an install location
10361            if (origin.staged) {
10362                if (origin.file != null) {
10363                    installFlags |= PackageManager.INSTALL_INTERNAL;
10364                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10365                } else if (origin.cid != null) {
10366                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10367                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10368                } else {
10369                    throw new IllegalStateException("Invalid stage location");
10370                }
10371            }
10372
10373            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10374            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10375
10376            PackageInfoLite pkgLite = null;
10377
10378            if (onInt && onSd) {
10379                // Check if both bits are set.
10380                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10381                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10382            } else {
10383                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10384                        packageAbiOverride);
10385
10386                /*
10387                 * If we have too little free space, try to free cache
10388                 * before giving up.
10389                 */
10390                if (!origin.staged && pkgLite.recommendedInstallLocation
10391                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10392                    // TODO: focus freeing disk space on the target device
10393                    final StorageManager storage = StorageManager.from(mContext);
10394                    final long lowThreshold = storage.getStorageLowBytes(
10395                            Environment.getDataDirectory());
10396
10397                    final long sizeBytes = mContainerService.calculateInstalledSize(
10398                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10399
10400                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10401                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10402                                installFlags, packageAbiOverride);
10403                    }
10404
10405                    /*
10406                     * The cache free must have deleted the file we
10407                     * downloaded to install.
10408                     *
10409                     * TODO: fix the "freeCache" call to not delete
10410                     *       the file we care about.
10411                     */
10412                    if (pkgLite.recommendedInstallLocation
10413                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10414                        pkgLite.recommendedInstallLocation
10415                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10416                    }
10417                }
10418            }
10419
10420            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10421                int loc = pkgLite.recommendedInstallLocation;
10422                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10423                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10424                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10425                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10426                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10427                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10428                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10429                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10430                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10431                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10432                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10433                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10434                } else {
10435                    // Override with defaults if needed.
10436                    loc = installLocationPolicy(pkgLite);
10437                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10438                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10439                    } else if (!onSd && !onInt) {
10440                        // Override install location with flags
10441                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10442                            // Set the flag to install on external media.
10443                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10444                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10445                        } else {
10446                            // Make sure the flag for installing on external
10447                            // media is unset
10448                            installFlags |= PackageManager.INSTALL_INTERNAL;
10449                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10450                        }
10451                    }
10452                }
10453            }
10454
10455            final InstallArgs args = createInstallArgs(this);
10456            mArgs = args;
10457
10458            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10459                 /*
10460                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10461                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10462                 */
10463                int userIdentifier = getUser().getIdentifier();
10464                if (userIdentifier == UserHandle.USER_ALL
10465                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10466                    userIdentifier = UserHandle.USER_OWNER;
10467                }
10468
10469                /*
10470                 * Determine if we have any installed package verifiers. If we
10471                 * do, then we'll defer to them to verify the packages.
10472                 */
10473                final int requiredUid = mRequiredVerifierPackage == null ? -1
10474                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10475                if (!origin.existing && requiredUid != -1
10476                        && isVerificationEnabled(userIdentifier, installFlags)) {
10477                    final Intent verification = new Intent(
10478                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10479                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10480                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10481                            PACKAGE_MIME_TYPE);
10482                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10483
10484                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10485                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10486                            0 /* TODO: Which userId? */);
10487
10488                    if (DEBUG_VERIFY) {
10489                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10490                                + verification.toString() + " with " + pkgLite.verifiers.length
10491                                + " optional verifiers");
10492                    }
10493
10494                    final int verificationId = mPendingVerificationToken++;
10495
10496                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10497
10498                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10499                            installerPackageName);
10500
10501                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10502                            installFlags);
10503
10504                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10505                            pkgLite.packageName);
10506
10507                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10508                            pkgLite.versionCode);
10509
10510                    if (verificationParams != null) {
10511                        if (verificationParams.getVerificationURI() != null) {
10512                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10513                                 verificationParams.getVerificationURI());
10514                        }
10515                        if (verificationParams.getOriginatingURI() != null) {
10516                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10517                                  verificationParams.getOriginatingURI());
10518                        }
10519                        if (verificationParams.getReferrer() != null) {
10520                            verification.putExtra(Intent.EXTRA_REFERRER,
10521                                  verificationParams.getReferrer());
10522                        }
10523                        if (verificationParams.getOriginatingUid() >= 0) {
10524                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10525                                  verificationParams.getOriginatingUid());
10526                        }
10527                        if (verificationParams.getInstallerUid() >= 0) {
10528                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10529                                  verificationParams.getInstallerUid());
10530                        }
10531                    }
10532
10533                    final PackageVerificationState verificationState = new PackageVerificationState(
10534                            requiredUid, args);
10535
10536                    mPendingVerification.append(verificationId, verificationState);
10537
10538                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10539                            receivers, verificationState);
10540
10541                    /*
10542                     * If any sufficient verifiers were listed in the package
10543                     * manifest, attempt to ask them.
10544                     */
10545                    if (sufficientVerifiers != null) {
10546                        final int N = sufficientVerifiers.size();
10547                        if (N == 0) {
10548                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10549                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10550                        } else {
10551                            for (int i = 0; i < N; i++) {
10552                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10553
10554                                final Intent sufficientIntent = new Intent(verification);
10555                                sufficientIntent.setComponent(verifierComponent);
10556
10557                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10558                            }
10559                        }
10560                    }
10561
10562                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10563                            mRequiredVerifierPackage, receivers);
10564                    if (ret == PackageManager.INSTALL_SUCCEEDED
10565                            && mRequiredVerifierPackage != null) {
10566                        /*
10567                         * Send the intent to the required verification agent,
10568                         * but only start the verification timeout after the
10569                         * target BroadcastReceivers have run.
10570                         */
10571                        verification.setComponent(requiredVerifierComponent);
10572                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10573                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10574                                new BroadcastReceiver() {
10575                                    @Override
10576                                    public void onReceive(Context context, Intent intent) {
10577                                        final Message msg = mHandler
10578                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10579                                        msg.arg1 = verificationId;
10580                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10581                                    }
10582                                }, null, 0, null, null);
10583
10584                        /*
10585                         * We don't want the copy to proceed until verification
10586                         * succeeds, so null out this field.
10587                         */
10588                        mArgs = null;
10589                    }
10590                } else {
10591                    /*
10592                     * No package verification is enabled, so immediately start
10593                     * the remote call to initiate copy using temporary file.
10594                     */
10595                    ret = args.copyApk(mContainerService, true);
10596                }
10597            }
10598
10599            mRet = ret;
10600        }
10601
10602        @Override
10603        void handleReturnCode() {
10604            // If mArgs is null, then MCS couldn't be reached. When it
10605            // reconnects, it will try again to install. At that point, this
10606            // will succeed.
10607            if (mArgs != null) {
10608                processPendingInstall(mArgs, mRet);
10609            }
10610        }
10611
10612        @Override
10613        void handleServiceError() {
10614            mArgs = createInstallArgs(this);
10615            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10616        }
10617
10618        public boolean isForwardLocked() {
10619            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10620        }
10621    }
10622
10623    /**
10624     * Used during creation of InstallArgs
10625     *
10626     * @param installFlags package installation flags
10627     * @return true if should be installed on external storage
10628     */
10629    private static boolean installOnExternalAsec(int installFlags) {
10630        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10631            return false;
10632        }
10633        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10634            return true;
10635        }
10636        return false;
10637    }
10638
10639    /**
10640     * Used during creation of InstallArgs
10641     *
10642     * @param installFlags package installation flags
10643     * @return true if should be installed as forward locked
10644     */
10645    private static boolean installForwardLocked(int installFlags) {
10646        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10647    }
10648
10649    private InstallArgs createInstallArgs(InstallParams params) {
10650        if (params.move != null) {
10651            return new MoveInstallArgs(params);
10652        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10653            return new AsecInstallArgs(params);
10654        } else {
10655            return new FileInstallArgs(params);
10656        }
10657    }
10658
10659    /**
10660     * Create args that describe an existing installed package. Typically used
10661     * when cleaning up old installs, or used as a move source.
10662     */
10663    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10664            String resourcePath, String[] instructionSets) {
10665        final boolean isInAsec;
10666        if (installOnExternalAsec(installFlags)) {
10667            /* Apps on SD card are always in ASEC containers. */
10668            isInAsec = true;
10669        } else if (installForwardLocked(installFlags)
10670                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10671            /*
10672             * Forward-locked apps are only in ASEC containers if they're the
10673             * new style
10674             */
10675            isInAsec = true;
10676        } else {
10677            isInAsec = false;
10678        }
10679
10680        if (isInAsec) {
10681            return new AsecInstallArgs(codePath, instructionSets,
10682                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10683        } else {
10684            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10685        }
10686    }
10687
10688    static abstract class InstallArgs {
10689        /** @see InstallParams#origin */
10690        final OriginInfo origin;
10691        /** @see InstallParams#move */
10692        final MoveInfo move;
10693
10694        final IPackageInstallObserver2 observer;
10695        // Always refers to PackageManager flags only
10696        final int installFlags;
10697        final String installerPackageName;
10698        final String volumeUuid;
10699        final ManifestDigest manifestDigest;
10700        final UserHandle user;
10701        final String abiOverride;
10702
10703        // The list of instruction sets supported by this app. This is currently
10704        // only used during the rmdex() phase to clean up resources. We can get rid of this
10705        // if we move dex files under the common app path.
10706        /* nullable */ String[] instructionSets;
10707
10708        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10709                int installFlags, String installerPackageName, String volumeUuid,
10710                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10711                String abiOverride) {
10712            this.origin = origin;
10713            this.move = move;
10714            this.installFlags = installFlags;
10715            this.observer = observer;
10716            this.installerPackageName = installerPackageName;
10717            this.volumeUuid = volumeUuid;
10718            this.manifestDigest = manifestDigest;
10719            this.user = user;
10720            this.instructionSets = instructionSets;
10721            this.abiOverride = abiOverride;
10722        }
10723
10724        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10725        abstract int doPreInstall(int status);
10726
10727        /**
10728         * Rename package into final resting place. All paths on the given
10729         * scanned package should be updated to reflect the rename.
10730         */
10731        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10732        abstract int doPostInstall(int status, int uid);
10733
10734        /** @see PackageSettingBase#codePathString */
10735        abstract String getCodePath();
10736        /** @see PackageSettingBase#resourcePathString */
10737        abstract String getResourcePath();
10738
10739        // Need installer lock especially for dex file removal.
10740        abstract void cleanUpResourcesLI();
10741        abstract boolean doPostDeleteLI(boolean delete);
10742
10743        /**
10744         * Called before the source arguments are copied. This is used mostly
10745         * for MoveParams when it needs to read the source file to put it in the
10746         * destination.
10747         */
10748        int doPreCopy() {
10749            return PackageManager.INSTALL_SUCCEEDED;
10750        }
10751
10752        /**
10753         * Called after the source arguments are copied. This is used mostly for
10754         * MoveParams when it needs to read the source file to put it in the
10755         * destination.
10756         *
10757         * @return
10758         */
10759        int doPostCopy(int uid) {
10760            return PackageManager.INSTALL_SUCCEEDED;
10761        }
10762
10763        protected boolean isFwdLocked() {
10764            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10765        }
10766
10767        protected boolean isExternalAsec() {
10768            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10769        }
10770
10771        UserHandle getUser() {
10772            return user;
10773        }
10774    }
10775
10776    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10777        if (!allCodePaths.isEmpty()) {
10778            if (instructionSets == null) {
10779                throw new IllegalStateException("instructionSet == null");
10780            }
10781            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10782            for (String codePath : allCodePaths) {
10783                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10784                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10785                    if (retCode < 0) {
10786                        Slog.w(TAG, "Couldn't remove dex file for package: "
10787                                + " at location " + codePath + ", retcode=" + retCode);
10788                        // we don't consider this to be a failure of the core package deletion
10789                    }
10790                }
10791            }
10792        }
10793    }
10794
10795    /**
10796     * Logic to handle installation of non-ASEC applications, including copying
10797     * and renaming logic.
10798     */
10799    class FileInstallArgs extends InstallArgs {
10800        private File codeFile;
10801        private File resourceFile;
10802
10803        // Example topology:
10804        // /data/app/com.example/base.apk
10805        // /data/app/com.example/split_foo.apk
10806        // /data/app/com.example/lib/arm/libfoo.so
10807        // /data/app/com.example/lib/arm64/libfoo.so
10808        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10809
10810        /** New install */
10811        FileInstallArgs(InstallParams params) {
10812            super(params.origin, params.move, params.observer, params.installFlags,
10813                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10814                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10815            if (isFwdLocked()) {
10816                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10817            }
10818        }
10819
10820        /** Existing install */
10821        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10822            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10823                    null);
10824            this.codeFile = (codePath != null) ? new File(codePath) : null;
10825            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10826        }
10827
10828        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10829            if (origin.staged) {
10830                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10831                codeFile = origin.file;
10832                resourceFile = origin.file;
10833                return PackageManager.INSTALL_SUCCEEDED;
10834            }
10835
10836            try {
10837                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10838                codeFile = tempDir;
10839                resourceFile = tempDir;
10840            } catch (IOException e) {
10841                Slog.w(TAG, "Failed to create copy file: " + e);
10842                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10843            }
10844
10845            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10846                @Override
10847                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10848                    if (!FileUtils.isValidExtFilename(name)) {
10849                        throw new IllegalArgumentException("Invalid filename: " + name);
10850                    }
10851                    try {
10852                        final File file = new File(codeFile, name);
10853                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10854                                O_RDWR | O_CREAT, 0644);
10855                        Os.chmod(file.getAbsolutePath(), 0644);
10856                        return new ParcelFileDescriptor(fd);
10857                    } catch (ErrnoException e) {
10858                        throw new RemoteException("Failed to open: " + e.getMessage());
10859                    }
10860                }
10861            };
10862
10863            int ret = PackageManager.INSTALL_SUCCEEDED;
10864            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10865            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10866                Slog.e(TAG, "Failed to copy package");
10867                return ret;
10868            }
10869
10870            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10871            NativeLibraryHelper.Handle handle = null;
10872            try {
10873                handle = NativeLibraryHelper.Handle.create(codeFile);
10874                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10875                        abiOverride);
10876            } catch (IOException e) {
10877                Slog.e(TAG, "Copying native libraries failed", e);
10878                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10879            } finally {
10880                IoUtils.closeQuietly(handle);
10881            }
10882
10883            return ret;
10884        }
10885
10886        int doPreInstall(int status) {
10887            if (status != PackageManager.INSTALL_SUCCEEDED) {
10888                cleanUp();
10889            }
10890            return status;
10891        }
10892
10893        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10894            if (status != PackageManager.INSTALL_SUCCEEDED) {
10895                cleanUp();
10896                return false;
10897            }
10898
10899            final File targetDir = codeFile.getParentFile();
10900            final File beforeCodeFile = codeFile;
10901            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10902
10903            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10904            try {
10905                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10906            } catch (ErrnoException e) {
10907                Slog.w(TAG, "Failed to rename", e);
10908                return false;
10909            }
10910
10911            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10912                Slog.w(TAG, "Failed to restorecon");
10913                return false;
10914            }
10915
10916            // Reflect the rename internally
10917            codeFile = afterCodeFile;
10918            resourceFile = afterCodeFile;
10919
10920            // Reflect the rename in scanned details
10921            pkg.codePath = afterCodeFile.getAbsolutePath();
10922            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10923                    pkg.baseCodePath);
10924            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10925                    pkg.splitCodePaths);
10926
10927            // Reflect the rename in app info
10928            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10929            pkg.applicationInfo.setCodePath(pkg.codePath);
10930            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10931            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10932            pkg.applicationInfo.setResourcePath(pkg.codePath);
10933            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10934            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10935
10936            return true;
10937        }
10938
10939        int doPostInstall(int status, int uid) {
10940            if (status != PackageManager.INSTALL_SUCCEEDED) {
10941                cleanUp();
10942            }
10943            return status;
10944        }
10945
10946        @Override
10947        String getCodePath() {
10948            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10949        }
10950
10951        @Override
10952        String getResourcePath() {
10953            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10954        }
10955
10956        private boolean cleanUp() {
10957            if (codeFile == null || !codeFile.exists()) {
10958                return false;
10959            }
10960
10961            if (codeFile.isDirectory()) {
10962                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10963            } else {
10964                codeFile.delete();
10965            }
10966
10967            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10968                resourceFile.delete();
10969            }
10970
10971            return true;
10972        }
10973
10974        void cleanUpResourcesLI() {
10975            // Try enumerating all code paths before deleting
10976            List<String> allCodePaths = Collections.EMPTY_LIST;
10977            if (codeFile != null && codeFile.exists()) {
10978                try {
10979                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10980                    allCodePaths = pkg.getAllCodePaths();
10981                } catch (PackageParserException e) {
10982                    // Ignored; we tried our best
10983                }
10984            }
10985
10986            cleanUp();
10987            removeDexFiles(allCodePaths, instructionSets);
10988        }
10989
10990        boolean doPostDeleteLI(boolean delete) {
10991            // XXX err, shouldn't we respect the delete flag?
10992            cleanUpResourcesLI();
10993            return true;
10994        }
10995    }
10996
10997    private boolean isAsecExternal(String cid) {
10998        final String asecPath = PackageHelper.getSdFilesystem(cid);
10999        return !asecPath.startsWith(mAsecInternalPath);
11000    }
11001
11002    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11003            PackageManagerException {
11004        if (copyRet < 0) {
11005            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11006                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11007                throw new PackageManagerException(copyRet, message);
11008            }
11009        }
11010    }
11011
11012    /**
11013     * Extract the MountService "container ID" from the full code path of an
11014     * .apk.
11015     */
11016    static String cidFromCodePath(String fullCodePath) {
11017        int eidx = fullCodePath.lastIndexOf("/");
11018        String subStr1 = fullCodePath.substring(0, eidx);
11019        int sidx = subStr1.lastIndexOf("/");
11020        return subStr1.substring(sidx+1, eidx);
11021    }
11022
11023    /**
11024     * Logic to handle installation of ASEC applications, including copying and
11025     * renaming logic.
11026     */
11027    class AsecInstallArgs extends InstallArgs {
11028        static final String RES_FILE_NAME = "pkg.apk";
11029        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11030
11031        String cid;
11032        String packagePath;
11033        String resourcePath;
11034
11035        /** New install */
11036        AsecInstallArgs(InstallParams params) {
11037            super(params.origin, params.move, params.observer, params.installFlags,
11038                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11039                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11040        }
11041
11042        /** Existing install */
11043        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11044                        boolean isExternal, boolean isForwardLocked) {
11045            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11046                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11047                    instructionSets, null);
11048            // Hackily pretend we're still looking at a full code path
11049            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11050                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11051            }
11052
11053            // Extract cid from fullCodePath
11054            int eidx = fullCodePath.lastIndexOf("/");
11055            String subStr1 = fullCodePath.substring(0, eidx);
11056            int sidx = subStr1.lastIndexOf("/");
11057            cid = subStr1.substring(sidx+1, eidx);
11058            setMountPath(subStr1);
11059        }
11060
11061        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11062            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11063                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11064                    instructionSets, null);
11065            this.cid = cid;
11066            setMountPath(PackageHelper.getSdDir(cid));
11067        }
11068
11069        void createCopyFile() {
11070            cid = mInstallerService.allocateExternalStageCidLegacy();
11071        }
11072
11073        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11074            if (origin.staged) {
11075                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11076                cid = origin.cid;
11077                setMountPath(PackageHelper.getSdDir(cid));
11078                return PackageManager.INSTALL_SUCCEEDED;
11079            }
11080
11081            if (temp) {
11082                createCopyFile();
11083            } else {
11084                /*
11085                 * Pre-emptively destroy the container since it's destroyed if
11086                 * copying fails due to it existing anyway.
11087                 */
11088                PackageHelper.destroySdDir(cid);
11089            }
11090
11091            final String newMountPath = imcs.copyPackageToContainer(
11092                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11093                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11094
11095            if (newMountPath != null) {
11096                setMountPath(newMountPath);
11097                return PackageManager.INSTALL_SUCCEEDED;
11098            } else {
11099                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11100            }
11101        }
11102
11103        @Override
11104        String getCodePath() {
11105            return packagePath;
11106        }
11107
11108        @Override
11109        String getResourcePath() {
11110            return resourcePath;
11111        }
11112
11113        int doPreInstall(int status) {
11114            if (status != PackageManager.INSTALL_SUCCEEDED) {
11115                // Destroy container
11116                PackageHelper.destroySdDir(cid);
11117            } else {
11118                boolean mounted = PackageHelper.isContainerMounted(cid);
11119                if (!mounted) {
11120                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11121                            Process.SYSTEM_UID);
11122                    if (newMountPath != null) {
11123                        setMountPath(newMountPath);
11124                    } else {
11125                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11126                    }
11127                }
11128            }
11129            return status;
11130        }
11131
11132        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11133            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11134            String newMountPath = null;
11135            if (PackageHelper.isContainerMounted(cid)) {
11136                // Unmount the container
11137                if (!PackageHelper.unMountSdDir(cid)) {
11138                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11139                    return false;
11140                }
11141            }
11142            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11143                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11144                        " which might be stale. Will try to clean up.");
11145                // Clean up the stale container and proceed to recreate.
11146                if (!PackageHelper.destroySdDir(newCacheId)) {
11147                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11148                    return false;
11149                }
11150                // Successfully cleaned up stale container. Try to rename again.
11151                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11152                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11153                            + " inspite of cleaning it up.");
11154                    return false;
11155                }
11156            }
11157            if (!PackageHelper.isContainerMounted(newCacheId)) {
11158                Slog.w(TAG, "Mounting container " + newCacheId);
11159                newMountPath = PackageHelper.mountSdDir(newCacheId,
11160                        getEncryptKey(), Process.SYSTEM_UID);
11161            } else {
11162                newMountPath = PackageHelper.getSdDir(newCacheId);
11163            }
11164            if (newMountPath == null) {
11165                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11166                return false;
11167            }
11168            Log.i(TAG, "Succesfully renamed " + cid +
11169                    " to " + newCacheId +
11170                    " at new path: " + newMountPath);
11171            cid = newCacheId;
11172
11173            final File beforeCodeFile = new File(packagePath);
11174            setMountPath(newMountPath);
11175            final File afterCodeFile = new File(packagePath);
11176
11177            // Reflect the rename in scanned details
11178            pkg.codePath = afterCodeFile.getAbsolutePath();
11179            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11180                    pkg.baseCodePath);
11181            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11182                    pkg.splitCodePaths);
11183
11184            // Reflect the rename in app info
11185            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11186            pkg.applicationInfo.setCodePath(pkg.codePath);
11187            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11188            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11189            pkg.applicationInfo.setResourcePath(pkg.codePath);
11190            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11191            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11192
11193            return true;
11194        }
11195
11196        private void setMountPath(String mountPath) {
11197            final File mountFile = new File(mountPath);
11198
11199            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11200            if (monolithicFile.exists()) {
11201                packagePath = monolithicFile.getAbsolutePath();
11202                if (isFwdLocked()) {
11203                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11204                } else {
11205                    resourcePath = packagePath;
11206                }
11207            } else {
11208                packagePath = mountFile.getAbsolutePath();
11209                resourcePath = packagePath;
11210            }
11211        }
11212
11213        int doPostInstall(int status, int uid) {
11214            if (status != PackageManager.INSTALL_SUCCEEDED) {
11215                cleanUp();
11216            } else {
11217                final int groupOwner;
11218                final String protectedFile;
11219                if (isFwdLocked()) {
11220                    groupOwner = UserHandle.getSharedAppGid(uid);
11221                    protectedFile = RES_FILE_NAME;
11222                } else {
11223                    groupOwner = -1;
11224                    protectedFile = null;
11225                }
11226
11227                if (uid < Process.FIRST_APPLICATION_UID
11228                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11229                    Slog.e(TAG, "Failed to finalize " + cid);
11230                    PackageHelper.destroySdDir(cid);
11231                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11232                }
11233
11234                boolean mounted = PackageHelper.isContainerMounted(cid);
11235                if (!mounted) {
11236                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11237                }
11238            }
11239            return status;
11240        }
11241
11242        private void cleanUp() {
11243            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11244
11245            // Destroy secure container
11246            PackageHelper.destroySdDir(cid);
11247        }
11248
11249        private List<String> getAllCodePaths() {
11250            final File codeFile = new File(getCodePath());
11251            if (codeFile != null && codeFile.exists()) {
11252                try {
11253                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11254                    return pkg.getAllCodePaths();
11255                } catch (PackageParserException e) {
11256                    // Ignored; we tried our best
11257                }
11258            }
11259            return Collections.EMPTY_LIST;
11260        }
11261
11262        void cleanUpResourcesLI() {
11263            // Enumerate all code paths before deleting
11264            cleanUpResourcesLI(getAllCodePaths());
11265        }
11266
11267        private void cleanUpResourcesLI(List<String> allCodePaths) {
11268            cleanUp();
11269            removeDexFiles(allCodePaths, instructionSets);
11270        }
11271
11272        String getPackageName() {
11273            return getAsecPackageName(cid);
11274        }
11275
11276        boolean doPostDeleteLI(boolean delete) {
11277            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11278            final List<String> allCodePaths = getAllCodePaths();
11279            boolean mounted = PackageHelper.isContainerMounted(cid);
11280            if (mounted) {
11281                // Unmount first
11282                if (PackageHelper.unMountSdDir(cid)) {
11283                    mounted = false;
11284                }
11285            }
11286            if (!mounted && delete) {
11287                cleanUpResourcesLI(allCodePaths);
11288            }
11289            return !mounted;
11290        }
11291
11292        @Override
11293        int doPreCopy() {
11294            if (isFwdLocked()) {
11295                if (!PackageHelper.fixSdPermissions(cid,
11296                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11297                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11298                }
11299            }
11300
11301            return PackageManager.INSTALL_SUCCEEDED;
11302        }
11303
11304        @Override
11305        int doPostCopy(int uid) {
11306            if (isFwdLocked()) {
11307                if (uid < Process.FIRST_APPLICATION_UID
11308                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11309                                RES_FILE_NAME)) {
11310                    Slog.e(TAG, "Failed to finalize " + cid);
11311                    PackageHelper.destroySdDir(cid);
11312                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11313                }
11314            }
11315
11316            return PackageManager.INSTALL_SUCCEEDED;
11317        }
11318    }
11319
11320    /**
11321     * Logic to handle movement of existing installed applications.
11322     */
11323    class MoveInstallArgs extends InstallArgs {
11324        private File codeFile;
11325        private File resourceFile;
11326
11327        /** New install */
11328        MoveInstallArgs(InstallParams params) {
11329            super(params.origin, params.move, params.observer, params.installFlags,
11330                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11331                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11332        }
11333
11334        int copyApk(IMediaContainerService imcs, boolean temp) {
11335            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11336                    + move.fromUuid + " to " + move.toUuid);
11337            synchronized (mInstaller) {
11338                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11339                        move.dataAppName, move.appId, move.seinfo) != 0) {
11340                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11341                }
11342            }
11343
11344            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11345            resourceFile = codeFile;
11346            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11347
11348            return PackageManager.INSTALL_SUCCEEDED;
11349        }
11350
11351        int doPreInstall(int status) {
11352            if (status != PackageManager.INSTALL_SUCCEEDED) {
11353                cleanUp(move.toUuid);
11354            }
11355            return status;
11356        }
11357
11358        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11359            if (status != PackageManager.INSTALL_SUCCEEDED) {
11360                cleanUp(move.toUuid);
11361                return false;
11362            }
11363
11364            // Reflect the move in app info
11365            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11366            pkg.applicationInfo.setCodePath(pkg.codePath);
11367            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11368            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11369            pkg.applicationInfo.setResourcePath(pkg.codePath);
11370            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11371            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11372
11373            return true;
11374        }
11375
11376        int doPostInstall(int status, int uid) {
11377            if (status == PackageManager.INSTALL_SUCCEEDED) {
11378                cleanUp(move.fromUuid);
11379            } else {
11380                cleanUp(move.toUuid);
11381            }
11382            return status;
11383        }
11384
11385        @Override
11386        String getCodePath() {
11387            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11388        }
11389
11390        @Override
11391        String getResourcePath() {
11392            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11393        }
11394
11395        private boolean cleanUp(String volumeUuid) {
11396            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11397                    move.dataAppName);
11398            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11399            synchronized (mInstallLock) {
11400                // Clean up both app data and code
11401                removeDataDirsLI(volumeUuid, move.packageName);
11402                if (codeFile.isDirectory()) {
11403                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11404                } else {
11405                    codeFile.delete();
11406                }
11407            }
11408            return true;
11409        }
11410
11411        void cleanUpResourcesLI() {
11412            throw new UnsupportedOperationException();
11413        }
11414
11415        boolean doPostDeleteLI(boolean delete) {
11416            throw new UnsupportedOperationException();
11417        }
11418    }
11419
11420    static String getAsecPackageName(String packageCid) {
11421        int idx = packageCid.lastIndexOf("-");
11422        if (idx == -1) {
11423            return packageCid;
11424        }
11425        return packageCid.substring(0, idx);
11426    }
11427
11428    // Utility method used to create code paths based on package name and available index.
11429    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11430        String idxStr = "";
11431        int idx = 1;
11432        // Fall back to default value of idx=1 if prefix is not
11433        // part of oldCodePath
11434        if (oldCodePath != null) {
11435            String subStr = oldCodePath;
11436            // Drop the suffix right away
11437            if (suffix != null && subStr.endsWith(suffix)) {
11438                subStr = subStr.substring(0, subStr.length() - suffix.length());
11439            }
11440            // If oldCodePath already contains prefix find out the
11441            // ending index to either increment or decrement.
11442            int sidx = subStr.lastIndexOf(prefix);
11443            if (sidx != -1) {
11444                subStr = subStr.substring(sidx + prefix.length());
11445                if (subStr != null) {
11446                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11447                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11448                    }
11449                    try {
11450                        idx = Integer.parseInt(subStr);
11451                        if (idx <= 1) {
11452                            idx++;
11453                        } else {
11454                            idx--;
11455                        }
11456                    } catch(NumberFormatException e) {
11457                    }
11458                }
11459            }
11460        }
11461        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11462        return prefix + idxStr;
11463    }
11464
11465    private File getNextCodePath(File targetDir, String packageName) {
11466        int suffix = 1;
11467        File result;
11468        do {
11469            result = new File(targetDir, packageName + "-" + suffix);
11470            suffix++;
11471        } while (result.exists());
11472        return result;
11473    }
11474
11475    // Utility method that returns the relative package path with respect
11476    // to the installation directory. Like say for /data/data/com.test-1.apk
11477    // string com.test-1 is returned.
11478    static String deriveCodePathName(String codePath) {
11479        if (codePath == null) {
11480            return null;
11481        }
11482        final File codeFile = new File(codePath);
11483        final String name = codeFile.getName();
11484        if (codeFile.isDirectory()) {
11485            return name;
11486        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11487            final int lastDot = name.lastIndexOf('.');
11488            return name.substring(0, lastDot);
11489        } else {
11490            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11491            return null;
11492        }
11493    }
11494
11495    class PackageInstalledInfo {
11496        String name;
11497        int uid;
11498        // The set of users that originally had this package installed.
11499        int[] origUsers;
11500        // The set of users that now have this package installed.
11501        int[] newUsers;
11502        PackageParser.Package pkg;
11503        int returnCode;
11504        String returnMsg;
11505        PackageRemovedInfo removedInfo;
11506
11507        public void setError(int code, String msg) {
11508            returnCode = code;
11509            returnMsg = msg;
11510            Slog.w(TAG, msg);
11511        }
11512
11513        public void setError(String msg, PackageParserException e) {
11514            returnCode = e.error;
11515            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11516            Slog.w(TAG, msg, e);
11517        }
11518
11519        public void setError(String msg, PackageManagerException e) {
11520            returnCode = e.error;
11521            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11522            Slog.w(TAG, msg, e);
11523        }
11524
11525        // In some error cases we want to convey more info back to the observer
11526        String origPackage;
11527        String origPermission;
11528    }
11529
11530    /*
11531     * Install a non-existing package.
11532     */
11533    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11534            UserHandle user, String installerPackageName, String volumeUuid,
11535            PackageInstalledInfo res) {
11536        // Remember this for later, in case we need to rollback this install
11537        String pkgName = pkg.packageName;
11538
11539        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11540        final boolean dataDirExists = Environment
11541                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11542        synchronized(mPackages) {
11543            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11544                // A package with the same name is already installed, though
11545                // it has been renamed to an older name.  The package we
11546                // are trying to install should be installed as an update to
11547                // the existing one, but that has not been requested, so bail.
11548                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11549                        + " without first uninstalling package running as "
11550                        + mSettings.mRenamedPackages.get(pkgName));
11551                return;
11552            }
11553            if (mPackages.containsKey(pkgName)) {
11554                // Don't allow installation over an existing package with the same name.
11555                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11556                        + " without first uninstalling.");
11557                return;
11558            }
11559        }
11560
11561        try {
11562            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11563                    System.currentTimeMillis(), user);
11564
11565            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11566            // delete the partially installed application. the data directory will have to be
11567            // restored if it was already existing
11568            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11569                // remove package from internal structures.  Note that we want deletePackageX to
11570                // delete the package data and cache directories that it created in
11571                // scanPackageLocked, unless those directories existed before we even tried to
11572                // install.
11573                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11574                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11575                                res.removedInfo, true);
11576            }
11577
11578        } catch (PackageManagerException e) {
11579            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11580        }
11581    }
11582
11583    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11584        // Can't rotate keys during boot or if sharedUser.
11585        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11586                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11587            return false;
11588        }
11589        // app is using upgradeKeySets; make sure all are valid
11590        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11591        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11592        for (int i = 0; i < upgradeKeySets.length; i++) {
11593            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11594                Slog.wtf(TAG, "Package "
11595                         + (oldPs.name != null ? oldPs.name : "<null>")
11596                         + " contains upgrade-key-set reference to unknown key-set: "
11597                         + upgradeKeySets[i]
11598                         + " reverting to signatures check.");
11599                return false;
11600            }
11601        }
11602        return true;
11603    }
11604
11605    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11606        // Upgrade keysets are being used.  Determine if new package has a superset of the
11607        // required keys.
11608        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11609        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11610        for (int i = 0; i < upgradeKeySets.length; i++) {
11611            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11612            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11613                return true;
11614            }
11615        }
11616        return false;
11617    }
11618
11619    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11620            UserHandle user, String installerPackageName, String volumeUuid,
11621            PackageInstalledInfo res) {
11622        final PackageParser.Package oldPackage;
11623        final String pkgName = pkg.packageName;
11624        final int[] allUsers;
11625        final boolean[] perUserInstalled;
11626        final boolean weFroze;
11627
11628        // First find the old package info and check signatures
11629        synchronized(mPackages) {
11630            oldPackage = mPackages.get(pkgName);
11631            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11632            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11633            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11634                if(!checkUpgradeKeySetLP(ps, pkg)) {
11635                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11636                            "New package not signed by keys specified by upgrade-keysets: "
11637                            + pkgName);
11638                    return;
11639                }
11640            } else {
11641                // default to original signature matching
11642                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11643                    != PackageManager.SIGNATURE_MATCH) {
11644                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11645                            "New package has a different signature: " + pkgName);
11646                    return;
11647                }
11648            }
11649
11650            // In case of rollback, remember per-user/profile install state
11651            allUsers = sUserManager.getUserIds();
11652            perUserInstalled = new boolean[allUsers.length];
11653            for (int i = 0; i < allUsers.length; i++) {
11654                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11655            }
11656
11657            // Mark the app as frozen to prevent launching during the upgrade
11658            // process, and then kill all running instances
11659            if (!ps.frozen) {
11660                ps.frozen = true;
11661                weFroze = true;
11662            } else {
11663                weFroze = false;
11664            }
11665        }
11666
11667        // Now that we're guarded by frozen state, kill app during upgrade
11668        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11669
11670        try {
11671            boolean sysPkg = (isSystemApp(oldPackage));
11672            if (sysPkg) {
11673                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11674                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11675            } else {
11676                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11677                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11678            }
11679        } finally {
11680            // Regardless of success or failure of upgrade steps above, always
11681            // unfreeze the package if we froze it
11682            if (weFroze) {
11683                unfreezePackage(pkgName);
11684            }
11685        }
11686    }
11687
11688    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11689            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11690            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11691            String volumeUuid, PackageInstalledInfo res) {
11692        String pkgName = deletedPackage.packageName;
11693        boolean deletedPkg = true;
11694        boolean updatedSettings = false;
11695
11696        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11697                + deletedPackage);
11698        long origUpdateTime;
11699        if (pkg.mExtras != null) {
11700            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11701        } else {
11702            origUpdateTime = 0;
11703        }
11704
11705        // First delete the existing package while retaining the data directory
11706        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11707                res.removedInfo, true)) {
11708            // If the existing package wasn't successfully deleted
11709            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11710            deletedPkg = false;
11711        } else {
11712            // Successfully deleted the old package; proceed with replace.
11713
11714            // If deleted package lived in a container, give users a chance to
11715            // relinquish resources before killing.
11716            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11717                if (DEBUG_INSTALL) {
11718                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11719                }
11720                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11721                final ArrayList<String> pkgList = new ArrayList<String>(1);
11722                pkgList.add(deletedPackage.applicationInfo.packageName);
11723                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11724            }
11725
11726            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11727            try {
11728                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11729                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11730                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11731                        perUserInstalled, res, user);
11732                updatedSettings = true;
11733            } catch (PackageManagerException e) {
11734                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11735            }
11736        }
11737
11738        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11739            // remove package from internal structures.  Note that we want deletePackageX to
11740            // delete the package data and cache directories that it created in
11741            // scanPackageLocked, unless those directories existed before we even tried to
11742            // install.
11743            if(updatedSettings) {
11744                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11745                deletePackageLI(
11746                        pkgName, null, true, allUsers, perUserInstalled,
11747                        PackageManager.DELETE_KEEP_DATA,
11748                                res.removedInfo, true);
11749            }
11750            // Since we failed to install the new package we need to restore the old
11751            // package that we deleted.
11752            if (deletedPkg) {
11753                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11754                File restoreFile = new File(deletedPackage.codePath);
11755                // Parse old package
11756                boolean oldExternal = isExternal(deletedPackage);
11757                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11758                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11759                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11760                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11761                try {
11762                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11763                } catch (PackageManagerException e) {
11764                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11765                            + e.getMessage());
11766                    return;
11767                }
11768                // Restore of old package succeeded. Update permissions.
11769                // writer
11770                synchronized (mPackages) {
11771                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11772                            UPDATE_PERMISSIONS_ALL);
11773                    // can downgrade to reader
11774                    mSettings.writeLPr();
11775                }
11776                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11777            }
11778        }
11779    }
11780
11781    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11782            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11783            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11784            String volumeUuid, PackageInstalledInfo res) {
11785        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11786                + ", old=" + deletedPackage);
11787        boolean disabledSystem = false;
11788        boolean updatedSettings = false;
11789        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11790        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11791                != 0) {
11792            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11793        }
11794        String packageName = deletedPackage.packageName;
11795        if (packageName == null) {
11796            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11797                    "Attempt to delete null packageName.");
11798            return;
11799        }
11800        PackageParser.Package oldPkg;
11801        PackageSetting oldPkgSetting;
11802        // reader
11803        synchronized (mPackages) {
11804            oldPkg = mPackages.get(packageName);
11805            oldPkgSetting = mSettings.mPackages.get(packageName);
11806            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11807                    (oldPkgSetting == null)) {
11808                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11809                        "Couldn't find package:" + packageName + " information");
11810                return;
11811            }
11812        }
11813
11814        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11815        res.removedInfo.removedPackage = packageName;
11816        // Remove existing system package
11817        removePackageLI(oldPkgSetting, true);
11818        // writer
11819        synchronized (mPackages) {
11820            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11821            if (!disabledSystem && deletedPackage != null) {
11822                // We didn't need to disable the .apk as a current system package,
11823                // which means we are replacing another update that is already
11824                // installed.  We need to make sure to delete the older one's .apk.
11825                res.removedInfo.args = createInstallArgsForExisting(0,
11826                        deletedPackage.applicationInfo.getCodePath(),
11827                        deletedPackage.applicationInfo.getResourcePath(),
11828                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11829            } else {
11830                res.removedInfo.args = null;
11831            }
11832        }
11833
11834        // Successfully disabled the old package. Now proceed with re-installation
11835        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11836
11837        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11838        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11839
11840        PackageParser.Package newPackage = null;
11841        try {
11842            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11843            if (newPackage.mExtras != null) {
11844                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11845                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11846                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11847
11848                // is the update attempting to change shared user? that isn't going to work...
11849                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11850                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11851                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11852                            + " to " + newPkgSetting.sharedUser);
11853                    updatedSettings = true;
11854                }
11855            }
11856
11857            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11858                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11859                        perUserInstalled, res, user);
11860                updatedSettings = true;
11861            }
11862
11863        } catch (PackageManagerException e) {
11864            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11865        }
11866
11867        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11868            // Re installation failed. Restore old information
11869            // Remove new pkg information
11870            if (newPackage != null) {
11871                removeInstalledPackageLI(newPackage, true);
11872            }
11873            // Add back the old system package
11874            try {
11875                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11876            } catch (PackageManagerException e) {
11877                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11878            }
11879            // Restore the old system information in Settings
11880            synchronized (mPackages) {
11881                if (disabledSystem) {
11882                    mSettings.enableSystemPackageLPw(packageName);
11883                }
11884                if (updatedSettings) {
11885                    mSettings.setInstallerPackageName(packageName,
11886                            oldPkgSetting.installerPackageName);
11887                }
11888                mSettings.writeLPr();
11889            }
11890        }
11891    }
11892
11893    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11894            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11895            UserHandle user) {
11896        String pkgName = newPackage.packageName;
11897        synchronized (mPackages) {
11898            //write settings. the installStatus will be incomplete at this stage.
11899            //note that the new package setting would have already been
11900            //added to mPackages. It hasn't been persisted yet.
11901            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11902            mSettings.writeLPr();
11903        }
11904
11905        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11906
11907        synchronized (mPackages) {
11908            updatePermissionsLPw(newPackage.packageName, newPackage,
11909                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11910                            ? UPDATE_PERMISSIONS_ALL : 0));
11911            // For system-bundled packages, we assume that installing an upgraded version
11912            // of the package implies that the user actually wants to run that new code,
11913            // so we enable the package.
11914            PackageSetting ps = mSettings.mPackages.get(pkgName);
11915            if (ps != null) {
11916                if (isSystemApp(newPackage)) {
11917                    // NB: implicit assumption that system package upgrades apply to all users
11918                    if (DEBUG_INSTALL) {
11919                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11920                    }
11921                    if (res.origUsers != null) {
11922                        for (int userHandle : res.origUsers) {
11923                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11924                                    userHandle, installerPackageName);
11925                        }
11926                    }
11927                    // Also convey the prior install/uninstall state
11928                    if (allUsers != null && perUserInstalled != null) {
11929                        for (int i = 0; i < allUsers.length; i++) {
11930                            if (DEBUG_INSTALL) {
11931                                Slog.d(TAG, "    user " + allUsers[i]
11932                                        + " => " + perUserInstalled[i]);
11933                            }
11934                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11935                        }
11936                        // these install state changes will be persisted in the
11937                        // upcoming call to mSettings.writeLPr().
11938                    }
11939                }
11940                // It's implied that when a user requests installation, they want the app to be
11941                // installed and enabled.
11942                int userId = user.getIdentifier();
11943                if (userId != UserHandle.USER_ALL) {
11944                    ps.setInstalled(true, userId);
11945                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11946                }
11947            }
11948            res.name = pkgName;
11949            res.uid = newPackage.applicationInfo.uid;
11950            res.pkg = newPackage;
11951            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11952            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11953            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11954            //to update install status
11955            mSettings.writeLPr();
11956        }
11957    }
11958
11959    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11960        final int installFlags = args.installFlags;
11961        final String installerPackageName = args.installerPackageName;
11962        final String volumeUuid = args.volumeUuid;
11963        final File tmpPackageFile = new File(args.getCodePath());
11964        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11965        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11966                || (args.volumeUuid != null));
11967        boolean replace = false;
11968        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11969        if (args.move != null) {
11970            // moving a complete application; perfom an initial scan on the new install location
11971            scanFlags |= SCAN_INITIAL;
11972        }
11973        // Result object to be returned
11974        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11975
11976        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11977        // Retrieve PackageSettings and parse package
11978        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11979                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11980                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11981        PackageParser pp = new PackageParser();
11982        pp.setSeparateProcesses(mSeparateProcesses);
11983        pp.setDisplayMetrics(mMetrics);
11984
11985        final PackageParser.Package pkg;
11986        try {
11987            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11988        } catch (PackageParserException e) {
11989            res.setError("Failed parse during installPackageLI", e);
11990            return;
11991        }
11992
11993        // Mark that we have an install time CPU ABI override.
11994        pkg.cpuAbiOverride = args.abiOverride;
11995
11996        String pkgName = res.name = pkg.packageName;
11997        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11998            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11999                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12000                return;
12001            }
12002        }
12003
12004        try {
12005            pp.collectCertificates(pkg, parseFlags);
12006            pp.collectManifestDigest(pkg);
12007        } catch (PackageParserException e) {
12008            res.setError("Failed collect during installPackageLI", e);
12009            return;
12010        }
12011
12012        /* If the installer passed in a manifest digest, compare it now. */
12013        if (args.manifestDigest != null) {
12014            if (DEBUG_INSTALL) {
12015                final String parsedManifest = pkg.manifestDigest == null ? "null"
12016                        : pkg.manifestDigest.toString();
12017                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12018                        + parsedManifest);
12019            }
12020
12021            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12022                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12023                return;
12024            }
12025        } else if (DEBUG_INSTALL) {
12026            final String parsedManifest = pkg.manifestDigest == null
12027                    ? "null" : pkg.manifestDigest.toString();
12028            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12029        }
12030
12031        // Get rid of all references to package scan path via parser.
12032        pp = null;
12033        String oldCodePath = null;
12034        boolean systemApp = false;
12035        synchronized (mPackages) {
12036            // Check if installing already existing package
12037            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12038                String oldName = mSettings.mRenamedPackages.get(pkgName);
12039                if (pkg.mOriginalPackages != null
12040                        && pkg.mOriginalPackages.contains(oldName)
12041                        && mPackages.containsKey(oldName)) {
12042                    // This package is derived from an original package,
12043                    // and this device has been updating from that original
12044                    // name.  We must continue using the original name, so
12045                    // rename the new package here.
12046                    pkg.setPackageName(oldName);
12047                    pkgName = pkg.packageName;
12048                    replace = true;
12049                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12050                            + oldName + " pkgName=" + pkgName);
12051                } else if (mPackages.containsKey(pkgName)) {
12052                    // This package, under its official name, already exists
12053                    // on the device; we should replace it.
12054                    replace = true;
12055                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12056                }
12057
12058                // Prevent apps opting out from runtime permissions
12059                if (replace) {
12060                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12061                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12062                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12063                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12064                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12065                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12066                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12067                                        + " doesn't support runtime permissions but the old"
12068                                        + " target SDK " + oldTargetSdk + " does.");
12069                        return;
12070                    }
12071                }
12072            }
12073
12074            PackageSetting ps = mSettings.mPackages.get(pkgName);
12075            if (ps != null) {
12076                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12077
12078                // Quick sanity check that we're signed correctly if updating;
12079                // we'll check this again later when scanning, but we want to
12080                // bail early here before tripping over redefined permissions.
12081                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12082                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12083                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12084                                + pkg.packageName + " upgrade keys do not match the "
12085                                + "previously installed version");
12086                        return;
12087                    }
12088                } else {
12089                    try {
12090                        verifySignaturesLP(ps, pkg);
12091                    } catch (PackageManagerException e) {
12092                        res.setError(e.error, e.getMessage());
12093                        return;
12094                    }
12095                }
12096
12097                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12098                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12099                    systemApp = (ps.pkg.applicationInfo.flags &
12100                            ApplicationInfo.FLAG_SYSTEM) != 0;
12101                }
12102                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12103            }
12104
12105            // Check whether the newly-scanned package wants to define an already-defined perm
12106            int N = pkg.permissions.size();
12107            for (int i = N-1; i >= 0; i--) {
12108                PackageParser.Permission perm = pkg.permissions.get(i);
12109                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12110                if (bp != null) {
12111                    // If the defining package is signed with our cert, it's okay.  This
12112                    // also includes the "updating the same package" case, of course.
12113                    // "updating same package" could also involve key-rotation.
12114                    final boolean sigsOk;
12115                    if (bp.sourcePackage.equals(pkg.packageName)
12116                            && (bp.packageSetting instanceof PackageSetting)
12117                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12118                                    scanFlags))) {
12119                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12120                    } else {
12121                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12122                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12123                    }
12124                    if (!sigsOk) {
12125                        // If the owning package is the system itself, we log but allow
12126                        // install to proceed; we fail the install on all other permission
12127                        // redefinitions.
12128                        if (!bp.sourcePackage.equals("android")) {
12129                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12130                                    + pkg.packageName + " attempting to redeclare permission "
12131                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12132                            res.origPermission = perm.info.name;
12133                            res.origPackage = bp.sourcePackage;
12134                            return;
12135                        } else {
12136                            Slog.w(TAG, "Package " + pkg.packageName
12137                                    + " attempting to redeclare system permission "
12138                                    + perm.info.name + "; ignoring new declaration");
12139                            pkg.permissions.remove(i);
12140                        }
12141                    }
12142                }
12143            }
12144
12145        }
12146
12147        if (systemApp && onExternal) {
12148            // Disable updates to system apps on sdcard
12149            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12150                    "Cannot install updates to system apps on sdcard");
12151            return;
12152        }
12153
12154        if (args.move != null) {
12155            // We did an in-place move, so dex is ready to roll
12156            scanFlags |= SCAN_NO_DEX;
12157            scanFlags |= SCAN_MOVE;
12158        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12159            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12160            scanFlags |= SCAN_NO_DEX;
12161
12162            try {
12163                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12164                        true /* extract libs */);
12165            } catch (PackageManagerException pme) {
12166                Slog.e(TAG, "Error deriving application ABI", pme);
12167                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12168                return;
12169            }
12170
12171            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12172            int result = mPackageDexOptimizer
12173                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12174                            false /* defer */, false /* inclDependencies */);
12175            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12176                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12177                return;
12178            }
12179        }
12180
12181        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12182            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12183            return;
12184        }
12185
12186        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12187
12188        if (replace) {
12189            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12190                    installerPackageName, volumeUuid, res);
12191        } else {
12192            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12193                    args.user, installerPackageName, volumeUuid, res);
12194        }
12195        synchronized (mPackages) {
12196            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12197            if (ps != null) {
12198                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12199            }
12200        }
12201    }
12202
12203    private void startIntentFilterVerifications(int userId, boolean replacing,
12204            PackageParser.Package pkg) {
12205        if (mIntentFilterVerifierComponent == null) {
12206            Slog.w(TAG, "No IntentFilter verification will not be done as "
12207                    + "there is no IntentFilterVerifier available!");
12208            return;
12209        }
12210
12211        final int verifierUid = getPackageUid(
12212                mIntentFilterVerifierComponent.getPackageName(),
12213                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12214
12215        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12216        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12217        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12218        mHandler.sendMessage(msg);
12219    }
12220
12221    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12222            PackageParser.Package pkg) {
12223        int size = pkg.activities.size();
12224        if (size == 0) {
12225            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12226                    "No activity, so no need to verify any IntentFilter!");
12227            return;
12228        }
12229
12230        final boolean hasDomainURLs = hasDomainURLs(pkg);
12231        if (!hasDomainURLs) {
12232            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12233                    "No domain URLs, so no need to verify any IntentFilter!");
12234            return;
12235        }
12236
12237        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12238                + " if any IntentFilter from the " + size
12239                + " Activities needs verification ...");
12240
12241        int count = 0;
12242        final String packageName = pkg.packageName;
12243
12244        synchronized (mPackages) {
12245            // If this is a new install and we see that we've already run verification for this
12246            // package, we have nothing to do: it means the state was restored from backup.
12247            if (!replacing) {
12248                IntentFilterVerificationInfo ivi =
12249                        mSettings.getIntentFilterVerificationLPr(packageName);
12250                if (ivi != null) {
12251                    if (DEBUG_DOMAIN_VERIFICATION) {
12252                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12253                                + ivi.getStatusString());
12254                    }
12255                    return;
12256                }
12257            }
12258
12259            // If any filters need to be verified, then all need to be.
12260            boolean needToVerify = false;
12261            for (PackageParser.Activity a : pkg.activities) {
12262                for (ActivityIntentInfo filter : a.intents) {
12263                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12264                        if (DEBUG_DOMAIN_VERIFICATION) {
12265                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12266                        }
12267                        needToVerify = true;
12268                        break;
12269                    }
12270                }
12271            }
12272
12273            if (needToVerify) {
12274                final int verificationId = mIntentFilterVerificationToken++;
12275                for (PackageParser.Activity a : pkg.activities) {
12276                    for (ActivityIntentInfo filter : a.intents) {
12277                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12278                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12279                                    "Verification needed for IntentFilter:" + filter.toString());
12280                            mIntentFilterVerifier.addOneIntentFilterVerification(
12281                                    verifierUid, userId, verificationId, filter, packageName);
12282                            count++;
12283                        }
12284                    }
12285                }
12286            }
12287        }
12288
12289        if (count > 0) {
12290            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12291                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12292                    +  " for userId:" + userId);
12293            mIntentFilterVerifier.startVerifications(userId);
12294        } else {
12295            if (DEBUG_DOMAIN_VERIFICATION) {
12296                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12297            }
12298        }
12299    }
12300
12301    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12302        final ComponentName cn  = filter.activity.getComponentName();
12303        final String packageName = cn.getPackageName();
12304
12305        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12306                packageName);
12307        if (ivi == null) {
12308            return true;
12309        }
12310        int status = ivi.getStatus();
12311        switch (status) {
12312            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12313            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12314                return true;
12315
12316            default:
12317                // Nothing to do
12318                return false;
12319        }
12320    }
12321
12322    private static boolean isMultiArch(PackageSetting ps) {
12323        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12324    }
12325
12326    private static boolean isMultiArch(ApplicationInfo info) {
12327        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12328    }
12329
12330    private static boolean isExternal(PackageParser.Package pkg) {
12331        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12332    }
12333
12334    private static boolean isExternal(PackageSetting ps) {
12335        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12336    }
12337
12338    private static boolean isExternal(ApplicationInfo info) {
12339        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12340    }
12341
12342    private static boolean isSystemApp(PackageParser.Package pkg) {
12343        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12344    }
12345
12346    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12347        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12348    }
12349
12350    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12351        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12352    }
12353
12354    private static boolean isSystemApp(PackageSetting ps) {
12355        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12356    }
12357
12358    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12359        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12360    }
12361
12362    private int packageFlagsToInstallFlags(PackageSetting ps) {
12363        int installFlags = 0;
12364        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12365            // This existing package was an external ASEC install when we have
12366            // the external flag without a UUID
12367            installFlags |= PackageManager.INSTALL_EXTERNAL;
12368        }
12369        if (ps.isForwardLocked()) {
12370            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12371        }
12372        return installFlags;
12373    }
12374
12375    private void deleteTempPackageFiles() {
12376        final FilenameFilter filter = new FilenameFilter() {
12377            public boolean accept(File dir, String name) {
12378                return name.startsWith("vmdl") && name.endsWith(".tmp");
12379            }
12380        };
12381        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12382            file.delete();
12383        }
12384    }
12385
12386    @Override
12387    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12388            int flags) {
12389        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12390                flags);
12391    }
12392
12393    @Override
12394    public void deletePackage(final String packageName,
12395            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12396        mContext.enforceCallingOrSelfPermission(
12397                android.Manifest.permission.DELETE_PACKAGES, null);
12398        Preconditions.checkNotNull(packageName);
12399        Preconditions.checkNotNull(observer);
12400        final int uid = Binder.getCallingUid();
12401        if (UserHandle.getUserId(uid) != userId) {
12402            mContext.enforceCallingPermission(
12403                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12404                    "deletePackage for user " + userId);
12405        }
12406        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12407            try {
12408                observer.onPackageDeleted(packageName,
12409                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12410            } catch (RemoteException re) {
12411            }
12412            return;
12413        }
12414
12415        boolean uninstallBlocked = false;
12416        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12417            int[] users = sUserManager.getUserIds();
12418            for (int i = 0; i < users.length; ++i) {
12419                if (getBlockUninstallForUser(packageName, users[i])) {
12420                    uninstallBlocked = true;
12421                    break;
12422                }
12423            }
12424        } else {
12425            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12426        }
12427        if (uninstallBlocked) {
12428            try {
12429                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12430                        null);
12431            } catch (RemoteException re) {
12432            }
12433            return;
12434        }
12435
12436        if (DEBUG_REMOVE) {
12437            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12438        }
12439        // Queue up an async operation since the package deletion may take a little while.
12440        mHandler.post(new Runnable() {
12441            public void run() {
12442                mHandler.removeCallbacks(this);
12443                final int returnCode = deletePackageX(packageName, userId, flags);
12444                if (observer != null) {
12445                    try {
12446                        observer.onPackageDeleted(packageName, returnCode, null);
12447                    } catch (RemoteException e) {
12448                        Log.i(TAG, "Observer no longer exists.");
12449                    } //end catch
12450                } //end if
12451            } //end run
12452        });
12453    }
12454
12455    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12456        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12457                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12458        try {
12459            if (dpm != null) {
12460                if (dpm.isDeviceOwner(packageName)) {
12461                    return true;
12462                }
12463                int[] users;
12464                if (userId == UserHandle.USER_ALL) {
12465                    users = sUserManager.getUserIds();
12466                } else {
12467                    users = new int[]{userId};
12468                }
12469                for (int i = 0; i < users.length; ++i) {
12470                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12471                        return true;
12472                    }
12473                }
12474            }
12475        } catch (RemoteException e) {
12476        }
12477        return false;
12478    }
12479
12480    /**
12481     *  This method is an internal method that could be get invoked either
12482     *  to delete an installed package or to clean up a failed installation.
12483     *  After deleting an installed package, a broadcast is sent to notify any
12484     *  listeners that the package has been installed. For cleaning up a failed
12485     *  installation, the broadcast is not necessary since the package's
12486     *  installation wouldn't have sent the initial broadcast either
12487     *  The key steps in deleting a package are
12488     *  deleting the package information in internal structures like mPackages,
12489     *  deleting the packages base directories through installd
12490     *  updating mSettings to reflect current status
12491     *  persisting settings for later use
12492     *  sending a broadcast if necessary
12493     */
12494    private int deletePackageX(String packageName, int userId, int flags) {
12495        final PackageRemovedInfo info = new PackageRemovedInfo();
12496        final boolean res;
12497
12498        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12499                ? UserHandle.ALL : new UserHandle(userId);
12500
12501        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12502            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12503            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12504        }
12505
12506        boolean removedForAllUsers = false;
12507        boolean systemUpdate = false;
12508
12509        // for the uninstall-updates case and restricted profiles, remember the per-
12510        // userhandle installed state
12511        int[] allUsers;
12512        boolean[] perUserInstalled;
12513        synchronized (mPackages) {
12514            PackageSetting ps = mSettings.mPackages.get(packageName);
12515            allUsers = sUserManager.getUserIds();
12516            perUserInstalled = new boolean[allUsers.length];
12517            for (int i = 0; i < allUsers.length; i++) {
12518                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12519            }
12520        }
12521
12522        synchronized (mInstallLock) {
12523            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12524            res = deletePackageLI(packageName, removeForUser,
12525                    true, allUsers, perUserInstalled,
12526                    flags | REMOVE_CHATTY, info, true);
12527            systemUpdate = info.isRemovedPackageSystemUpdate;
12528            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12529                removedForAllUsers = true;
12530            }
12531            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12532                    + " removedForAllUsers=" + removedForAllUsers);
12533        }
12534
12535        if (res) {
12536            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12537
12538            // If the removed package was a system update, the old system package
12539            // was re-enabled; we need to broadcast this information
12540            if (systemUpdate) {
12541                Bundle extras = new Bundle(1);
12542                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12543                        ? info.removedAppId : info.uid);
12544                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12545
12546                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12547                        extras, null, null, null);
12548                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12549                        extras, null, null, null);
12550                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12551                        null, packageName, null, null);
12552            }
12553        }
12554        // Force a gc here.
12555        Runtime.getRuntime().gc();
12556        // Delete the resources here after sending the broadcast to let
12557        // other processes clean up before deleting resources.
12558        if (info.args != null) {
12559            synchronized (mInstallLock) {
12560                info.args.doPostDeleteLI(true);
12561            }
12562        }
12563
12564        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12565    }
12566
12567    class PackageRemovedInfo {
12568        String removedPackage;
12569        int uid = -1;
12570        int removedAppId = -1;
12571        int[] removedUsers = null;
12572        boolean isRemovedPackageSystemUpdate = false;
12573        // Clean up resources deleted packages.
12574        InstallArgs args = null;
12575
12576        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12577            Bundle extras = new Bundle(1);
12578            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12579            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12580            if (replacing) {
12581                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12582            }
12583            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12584            if (removedPackage != null) {
12585                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12586                        extras, null, null, removedUsers);
12587                if (fullRemove && !replacing) {
12588                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12589                            extras, null, null, removedUsers);
12590                }
12591            }
12592            if (removedAppId >= 0) {
12593                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12594                        removedUsers);
12595            }
12596        }
12597    }
12598
12599    /*
12600     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12601     * flag is not set, the data directory is removed as well.
12602     * make sure this flag is set for partially installed apps. If not its meaningless to
12603     * delete a partially installed application.
12604     */
12605    private void removePackageDataLI(PackageSetting ps,
12606            int[] allUserHandles, boolean[] perUserInstalled,
12607            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12608        String packageName = ps.name;
12609        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12610        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12611        // Retrieve object to delete permissions for shared user later on
12612        final PackageSetting deletedPs;
12613        // reader
12614        synchronized (mPackages) {
12615            deletedPs = mSettings.mPackages.get(packageName);
12616            if (outInfo != null) {
12617                outInfo.removedPackage = packageName;
12618                outInfo.removedUsers = deletedPs != null
12619                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12620                        : null;
12621            }
12622        }
12623        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12624            removeDataDirsLI(ps.volumeUuid, packageName);
12625            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12626        }
12627        // writer
12628        synchronized (mPackages) {
12629            if (deletedPs != null) {
12630                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12631                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12632                    clearDefaultBrowserIfNeeded(packageName);
12633                    if (outInfo != null) {
12634                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12635                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12636                    }
12637                    updatePermissionsLPw(deletedPs.name, null, 0);
12638                    if (deletedPs.sharedUser != null) {
12639                        // Remove permissions associated with package. Since runtime
12640                        // permissions are per user we have to kill the removed package
12641                        // or packages running under the shared user of the removed
12642                        // package if revoking the permissions requested only by the removed
12643                        // package is successful and this causes a change in gids.
12644                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12645                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12646                                    userId);
12647                            if (userIdToKill == UserHandle.USER_ALL
12648                                    || userIdToKill >= UserHandle.USER_OWNER) {
12649                                // If gids changed for this user, kill all affected packages.
12650                                mHandler.post(new Runnable() {
12651                                    @Override
12652                                    public void run() {
12653                                        // This has to happen with no lock held.
12654                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12655                                                KILL_APP_REASON_GIDS_CHANGED);
12656                                    }
12657                                });
12658                            break;
12659                            }
12660                        }
12661                    }
12662                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12663                }
12664                // make sure to preserve per-user disabled state if this removal was just
12665                // a downgrade of a system app to the factory package
12666                if (allUserHandles != null && perUserInstalled != null) {
12667                    if (DEBUG_REMOVE) {
12668                        Slog.d(TAG, "Propagating install state across downgrade");
12669                    }
12670                    for (int i = 0; i < allUserHandles.length; i++) {
12671                        if (DEBUG_REMOVE) {
12672                            Slog.d(TAG, "    user " + allUserHandles[i]
12673                                    + " => " + perUserInstalled[i]);
12674                        }
12675                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12676                    }
12677                }
12678            }
12679            // can downgrade to reader
12680            if (writeSettings) {
12681                // Save settings now
12682                mSettings.writeLPr();
12683            }
12684        }
12685        if (outInfo != null) {
12686            // A user ID was deleted here. Go through all users and remove it
12687            // from KeyStore.
12688            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12689        }
12690    }
12691
12692    static boolean locationIsPrivileged(File path) {
12693        try {
12694            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12695                    .getCanonicalPath();
12696            return path.getCanonicalPath().startsWith(privilegedAppDir);
12697        } catch (IOException e) {
12698            Slog.e(TAG, "Unable to access code path " + path);
12699        }
12700        return false;
12701    }
12702
12703    /*
12704     * Tries to delete system package.
12705     */
12706    private boolean deleteSystemPackageLI(PackageSetting newPs,
12707            int[] allUserHandles, boolean[] perUserInstalled,
12708            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12709        final boolean applyUserRestrictions
12710                = (allUserHandles != null) && (perUserInstalled != null);
12711        PackageSetting disabledPs = null;
12712        // Confirm if the system package has been updated
12713        // An updated system app can be deleted. This will also have to restore
12714        // the system pkg from system partition
12715        // reader
12716        synchronized (mPackages) {
12717            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12718        }
12719        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12720                + " disabledPs=" + disabledPs);
12721        if (disabledPs == null) {
12722            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12723            return false;
12724        } else if (DEBUG_REMOVE) {
12725            Slog.d(TAG, "Deleting system pkg from data partition");
12726        }
12727        if (DEBUG_REMOVE) {
12728            if (applyUserRestrictions) {
12729                Slog.d(TAG, "Remembering install states:");
12730                for (int i = 0; i < allUserHandles.length; i++) {
12731                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12732                }
12733            }
12734        }
12735        // Delete the updated package
12736        outInfo.isRemovedPackageSystemUpdate = true;
12737        if (disabledPs.versionCode < newPs.versionCode) {
12738            // Delete data for downgrades
12739            flags &= ~PackageManager.DELETE_KEEP_DATA;
12740        } else {
12741            // Preserve data by setting flag
12742            flags |= PackageManager.DELETE_KEEP_DATA;
12743        }
12744        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12745                allUserHandles, perUserInstalled, outInfo, writeSettings);
12746        if (!ret) {
12747            return false;
12748        }
12749        // writer
12750        synchronized (mPackages) {
12751            // Reinstate the old system package
12752            mSettings.enableSystemPackageLPw(newPs.name);
12753            // Remove any native libraries from the upgraded package.
12754            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12755        }
12756        // Install the system package
12757        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12758        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12759        if (locationIsPrivileged(disabledPs.codePath)) {
12760            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12761        }
12762
12763        final PackageParser.Package newPkg;
12764        try {
12765            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12766        } catch (PackageManagerException e) {
12767            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12768            return false;
12769        }
12770
12771        // writer
12772        synchronized (mPackages) {
12773            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12774            updatePermissionsLPw(newPkg.packageName, newPkg,
12775                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12776            if (applyUserRestrictions) {
12777                if (DEBUG_REMOVE) {
12778                    Slog.d(TAG, "Propagating install state across reinstall");
12779                }
12780                for (int i = 0; i < allUserHandles.length; i++) {
12781                    if (DEBUG_REMOVE) {
12782                        Slog.d(TAG, "    user " + allUserHandles[i]
12783                                + " => " + perUserInstalled[i]);
12784                    }
12785                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12786                }
12787                // Regardless of writeSettings we need to ensure that this restriction
12788                // state propagation is persisted
12789                mSettings.writeAllUsersPackageRestrictionsLPr();
12790            }
12791            // can downgrade to reader here
12792            if (writeSettings) {
12793                mSettings.writeLPr();
12794            }
12795        }
12796        return true;
12797    }
12798
12799    private boolean deleteInstalledPackageLI(PackageSetting ps,
12800            boolean deleteCodeAndResources, int flags,
12801            int[] allUserHandles, boolean[] perUserInstalled,
12802            PackageRemovedInfo outInfo, boolean writeSettings) {
12803        if (outInfo != null) {
12804            outInfo.uid = ps.appId;
12805        }
12806
12807        // Delete package data from internal structures and also remove data if flag is set
12808        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12809
12810        // Delete application code and resources
12811        if (deleteCodeAndResources && (outInfo != null)) {
12812            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12813                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12814            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12815        }
12816        return true;
12817    }
12818
12819    @Override
12820    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12821            int userId) {
12822        mContext.enforceCallingOrSelfPermission(
12823                android.Manifest.permission.DELETE_PACKAGES, null);
12824        synchronized (mPackages) {
12825            PackageSetting ps = mSettings.mPackages.get(packageName);
12826            if (ps == null) {
12827                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12828                return false;
12829            }
12830            if (!ps.getInstalled(userId)) {
12831                // Can't block uninstall for an app that is not installed or enabled.
12832                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12833                return false;
12834            }
12835            ps.setBlockUninstall(blockUninstall, userId);
12836            mSettings.writePackageRestrictionsLPr(userId);
12837        }
12838        return true;
12839    }
12840
12841    @Override
12842    public boolean getBlockUninstallForUser(String packageName, int userId) {
12843        synchronized (mPackages) {
12844            PackageSetting ps = mSettings.mPackages.get(packageName);
12845            if (ps == null) {
12846                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12847                return false;
12848            }
12849            return ps.getBlockUninstall(userId);
12850        }
12851    }
12852
12853    /*
12854     * This method handles package deletion in general
12855     */
12856    private boolean deletePackageLI(String packageName, UserHandle user,
12857            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12858            int flags, PackageRemovedInfo outInfo,
12859            boolean writeSettings) {
12860        if (packageName == null) {
12861            Slog.w(TAG, "Attempt to delete null packageName.");
12862            return false;
12863        }
12864        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12865        PackageSetting ps;
12866        boolean dataOnly = false;
12867        int removeUser = -1;
12868        int appId = -1;
12869        synchronized (mPackages) {
12870            ps = mSettings.mPackages.get(packageName);
12871            if (ps == null) {
12872                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12873                return false;
12874            }
12875            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12876                    && user.getIdentifier() != UserHandle.USER_ALL) {
12877                // The caller is asking that the package only be deleted for a single
12878                // user.  To do this, we just mark its uninstalled state and delete
12879                // its data.  If this is a system app, we only allow this to happen if
12880                // they have set the special DELETE_SYSTEM_APP which requests different
12881                // semantics than normal for uninstalling system apps.
12882                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12883                ps.setUserState(user.getIdentifier(),
12884                        COMPONENT_ENABLED_STATE_DEFAULT,
12885                        false, //installed
12886                        true,  //stopped
12887                        true,  //notLaunched
12888                        false, //hidden
12889                        null, null, null,
12890                        false, // blockUninstall
12891                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12892                if (!isSystemApp(ps)) {
12893                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12894                        // Other user still have this package installed, so all
12895                        // we need to do is clear this user's data and save that
12896                        // it is uninstalled.
12897                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12898                        removeUser = user.getIdentifier();
12899                        appId = ps.appId;
12900                        scheduleWritePackageRestrictionsLocked(removeUser);
12901                    } else {
12902                        // We need to set it back to 'installed' so the uninstall
12903                        // broadcasts will be sent correctly.
12904                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12905                        ps.setInstalled(true, user.getIdentifier());
12906                    }
12907                } else {
12908                    // This is a system app, so we assume that the
12909                    // other users still have this package installed, so all
12910                    // we need to do is clear this user's data and save that
12911                    // it is uninstalled.
12912                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12913                    removeUser = user.getIdentifier();
12914                    appId = ps.appId;
12915                    scheduleWritePackageRestrictionsLocked(removeUser);
12916                }
12917            }
12918        }
12919
12920        if (removeUser >= 0) {
12921            // From above, we determined that we are deleting this only
12922            // for a single user.  Continue the work here.
12923            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12924            if (outInfo != null) {
12925                outInfo.removedPackage = packageName;
12926                outInfo.removedAppId = appId;
12927                outInfo.removedUsers = new int[] {removeUser};
12928            }
12929            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12930            removeKeystoreDataIfNeeded(removeUser, appId);
12931            schedulePackageCleaning(packageName, removeUser, false);
12932            synchronized (mPackages) {
12933                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12934                    scheduleWritePackageRestrictionsLocked(removeUser);
12935                }
12936                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12937                        removeUser);
12938            }
12939            return true;
12940        }
12941
12942        if (dataOnly) {
12943            // Delete application data first
12944            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12945            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12946            return true;
12947        }
12948
12949        boolean ret = false;
12950        if (isSystemApp(ps)) {
12951            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12952            // When an updated system application is deleted we delete the existing resources as well and
12953            // fall back to existing code in system partition
12954            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12955                    flags, outInfo, writeSettings);
12956        } else {
12957            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12958            // Kill application pre-emptively especially for apps on sd.
12959            killApplication(packageName, ps.appId, "uninstall pkg");
12960            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12961                    allUserHandles, perUserInstalled,
12962                    outInfo, writeSettings);
12963        }
12964
12965        return ret;
12966    }
12967
12968    private final class ClearStorageConnection implements ServiceConnection {
12969        IMediaContainerService mContainerService;
12970
12971        @Override
12972        public void onServiceConnected(ComponentName name, IBinder service) {
12973            synchronized (this) {
12974                mContainerService = IMediaContainerService.Stub.asInterface(service);
12975                notifyAll();
12976            }
12977        }
12978
12979        @Override
12980        public void onServiceDisconnected(ComponentName name) {
12981        }
12982    }
12983
12984    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12985        final boolean mounted;
12986        if (Environment.isExternalStorageEmulated()) {
12987            mounted = true;
12988        } else {
12989            final String status = Environment.getExternalStorageState();
12990
12991            mounted = status.equals(Environment.MEDIA_MOUNTED)
12992                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12993        }
12994
12995        if (!mounted) {
12996            return;
12997        }
12998
12999        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13000        int[] users;
13001        if (userId == UserHandle.USER_ALL) {
13002            users = sUserManager.getUserIds();
13003        } else {
13004            users = new int[] { userId };
13005        }
13006        final ClearStorageConnection conn = new ClearStorageConnection();
13007        if (mContext.bindServiceAsUser(
13008                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13009            try {
13010                for (int curUser : users) {
13011                    long timeout = SystemClock.uptimeMillis() + 5000;
13012                    synchronized (conn) {
13013                        long now = SystemClock.uptimeMillis();
13014                        while (conn.mContainerService == null && now < timeout) {
13015                            try {
13016                                conn.wait(timeout - now);
13017                            } catch (InterruptedException e) {
13018                            }
13019                        }
13020                    }
13021                    if (conn.mContainerService == null) {
13022                        return;
13023                    }
13024
13025                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13026                    clearDirectory(conn.mContainerService,
13027                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13028                    if (allData) {
13029                        clearDirectory(conn.mContainerService,
13030                                userEnv.buildExternalStorageAppDataDirs(packageName));
13031                        clearDirectory(conn.mContainerService,
13032                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13033                    }
13034                }
13035            } finally {
13036                mContext.unbindService(conn);
13037            }
13038        }
13039    }
13040
13041    @Override
13042    public void clearApplicationUserData(final String packageName,
13043            final IPackageDataObserver observer, final int userId) {
13044        mContext.enforceCallingOrSelfPermission(
13045                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13046        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13047        // Queue up an async operation since the package deletion may take a little while.
13048        mHandler.post(new Runnable() {
13049            public void run() {
13050                mHandler.removeCallbacks(this);
13051                final boolean succeeded;
13052                synchronized (mInstallLock) {
13053                    succeeded = clearApplicationUserDataLI(packageName, userId);
13054                }
13055                clearExternalStorageDataSync(packageName, userId, true);
13056                if (succeeded) {
13057                    // invoke DeviceStorageMonitor's update method to clear any notifications
13058                    DeviceStorageMonitorInternal
13059                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13060                    if (dsm != null) {
13061                        dsm.checkMemory();
13062                    }
13063                }
13064                if(observer != null) {
13065                    try {
13066                        observer.onRemoveCompleted(packageName, succeeded);
13067                    } catch (RemoteException e) {
13068                        Log.i(TAG, "Observer no longer exists.");
13069                    }
13070                } //end if observer
13071            } //end run
13072        });
13073    }
13074
13075    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13076        if (packageName == null) {
13077            Slog.w(TAG, "Attempt to delete null packageName.");
13078            return false;
13079        }
13080
13081        // Try finding details about the requested package
13082        PackageParser.Package pkg;
13083        synchronized (mPackages) {
13084            pkg = mPackages.get(packageName);
13085            if (pkg == null) {
13086                final PackageSetting ps = mSettings.mPackages.get(packageName);
13087                if (ps != null) {
13088                    pkg = ps.pkg;
13089                }
13090            }
13091
13092            if (pkg == null) {
13093                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13094                return false;
13095            }
13096
13097            PackageSetting ps = (PackageSetting) pkg.mExtras;
13098            PermissionsState permissionsState = ps.getPermissionsState();
13099            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13100        }
13101
13102        // Always delete data directories for package, even if we found no other
13103        // record of app. This helps users recover from UID mismatches without
13104        // resorting to a full data wipe.
13105        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13106        if (retCode < 0) {
13107            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13108            return false;
13109        }
13110
13111        final int appId = pkg.applicationInfo.uid;
13112        removeKeystoreDataIfNeeded(userId, appId);
13113
13114        // Create a native library symlink only if we have native libraries
13115        // and if the native libraries are 32 bit libraries. We do not provide
13116        // this symlink for 64 bit libraries.
13117        if (pkg.applicationInfo.primaryCpuAbi != null &&
13118                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13119            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13120            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13121                    nativeLibPath, userId) < 0) {
13122                Slog.w(TAG, "Failed linking native library dir");
13123                return false;
13124            }
13125        }
13126
13127        return true;
13128    }
13129
13130
13131    /**
13132     * Revokes granted runtime permissions and clears resettable flags
13133     * which are flags that can be set by a user interaction.
13134     *
13135     * @param permissionsState The permission state to reset.
13136     * @param userId The device user for which to do a reset.
13137     */
13138    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13139            PermissionsState permissionsState, int userId) {
13140        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13141                | PackageManager.FLAG_PERMISSION_USER_FIXED
13142                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13143
13144        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13145    }
13146
13147    /**
13148     * Revokes granted runtime permissions and clears all flags.
13149     *
13150     * @param permissionsState The permission state to reset.
13151     * @param userId The device user for which to do a reset.
13152     */
13153    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13154            PermissionsState permissionsState, int userId) {
13155        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13156                PackageManager.MASK_PERMISSION_FLAGS);
13157    }
13158
13159    /**
13160     * Revokes granted runtime permissions and clears certain flags.
13161     *
13162     * @param permissionsState The permission state to reset.
13163     * @param userId The device user for which to do a reset.
13164     * @param flags The flags that is going to be reset.
13165     */
13166    private void revokeRuntimePermissionsAndClearFlagsLocked(
13167            PermissionsState permissionsState, final int userId, int flags) {
13168        boolean needsWrite = false;
13169
13170        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13171            BasePermission bp = mSettings.mPermissions.get(state.getName());
13172            if (bp != null) {
13173                permissionsState.revokeRuntimePermission(bp, userId);
13174                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13175                needsWrite = true;
13176            }
13177        }
13178
13179        // Ensure default permissions are never cleared.
13180        mHandler.post(new Runnable() {
13181            @Override
13182            public void run() {
13183                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13184            }
13185        });
13186
13187        if (needsWrite) {
13188            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13189        }
13190    }
13191
13192    /**
13193     * Remove entries from the keystore daemon. Will only remove it if the
13194     * {@code appId} is valid.
13195     */
13196    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13197        if (appId < 0) {
13198            return;
13199        }
13200
13201        final KeyStore keyStore = KeyStore.getInstance();
13202        if (keyStore != null) {
13203            if (userId == UserHandle.USER_ALL) {
13204                for (final int individual : sUserManager.getUserIds()) {
13205                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13206                }
13207            } else {
13208                keyStore.clearUid(UserHandle.getUid(userId, appId));
13209            }
13210        } else {
13211            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13212        }
13213    }
13214
13215    @Override
13216    public void deleteApplicationCacheFiles(final String packageName,
13217            final IPackageDataObserver observer) {
13218        mContext.enforceCallingOrSelfPermission(
13219                android.Manifest.permission.DELETE_CACHE_FILES, null);
13220        // Queue up an async operation since the package deletion may take a little while.
13221        final int userId = UserHandle.getCallingUserId();
13222        mHandler.post(new Runnable() {
13223            public void run() {
13224                mHandler.removeCallbacks(this);
13225                final boolean succeded;
13226                synchronized (mInstallLock) {
13227                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13228                }
13229                clearExternalStorageDataSync(packageName, userId, false);
13230                if (observer != null) {
13231                    try {
13232                        observer.onRemoveCompleted(packageName, succeded);
13233                    } catch (RemoteException e) {
13234                        Log.i(TAG, "Observer no longer exists.");
13235                    }
13236                } //end if observer
13237            } //end run
13238        });
13239    }
13240
13241    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13242        if (packageName == null) {
13243            Slog.w(TAG, "Attempt to delete null packageName.");
13244            return false;
13245        }
13246        PackageParser.Package p;
13247        synchronized (mPackages) {
13248            p = mPackages.get(packageName);
13249        }
13250        if (p == null) {
13251            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13252            return false;
13253        }
13254        final ApplicationInfo applicationInfo = p.applicationInfo;
13255        if (applicationInfo == null) {
13256            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13257            return false;
13258        }
13259        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13260        if (retCode < 0) {
13261            Slog.w(TAG, "Couldn't remove cache files for package: "
13262                       + packageName + " u" + userId);
13263            return false;
13264        }
13265        return true;
13266    }
13267
13268    @Override
13269    public void getPackageSizeInfo(final String packageName, int userHandle,
13270            final IPackageStatsObserver observer) {
13271        mContext.enforceCallingOrSelfPermission(
13272                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13273        if (packageName == null) {
13274            throw new IllegalArgumentException("Attempt to get size of null packageName");
13275        }
13276
13277        PackageStats stats = new PackageStats(packageName, userHandle);
13278
13279        /*
13280         * Queue up an async operation since the package measurement may take a
13281         * little while.
13282         */
13283        Message msg = mHandler.obtainMessage(INIT_COPY);
13284        msg.obj = new MeasureParams(stats, observer);
13285        mHandler.sendMessage(msg);
13286    }
13287
13288    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13289            PackageStats pStats) {
13290        if (packageName == null) {
13291            Slog.w(TAG, "Attempt to get size of null packageName.");
13292            return false;
13293        }
13294        PackageParser.Package p;
13295        boolean dataOnly = false;
13296        String libDirRoot = null;
13297        String asecPath = null;
13298        PackageSetting ps = null;
13299        synchronized (mPackages) {
13300            p = mPackages.get(packageName);
13301            ps = mSettings.mPackages.get(packageName);
13302            if(p == null) {
13303                dataOnly = true;
13304                if((ps == null) || (ps.pkg == null)) {
13305                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13306                    return false;
13307                }
13308                p = ps.pkg;
13309            }
13310            if (ps != null) {
13311                libDirRoot = ps.legacyNativeLibraryPathString;
13312            }
13313            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13314                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13315                if (secureContainerId != null) {
13316                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13317                }
13318            }
13319        }
13320        String publicSrcDir = null;
13321        if(!dataOnly) {
13322            final ApplicationInfo applicationInfo = p.applicationInfo;
13323            if (applicationInfo == null) {
13324                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13325                return false;
13326            }
13327            if (p.isForwardLocked()) {
13328                publicSrcDir = applicationInfo.getBaseResourcePath();
13329            }
13330        }
13331        // TODO: extend to measure size of split APKs
13332        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13333        // not just the first level.
13334        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13335        // just the primary.
13336        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13337        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13338                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13339        if (res < 0) {
13340            return false;
13341        }
13342
13343        // Fix-up for forward-locked applications in ASEC containers.
13344        if (!isExternal(p)) {
13345            pStats.codeSize += pStats.externalCodeSize;
13346            pStats.externalCodeSize = 0L;
13347        }
13348
13349        return true;
13350    }
13351
13352
13353    @Override
13354    public void addPackageToPreferred(String packageName) {
13355        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13356    }
13357
13358    @Override
13359    public void removePackageFromPreferred(String packageName) {
13360        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13361    }
13362
13363    @Override
13364    public List<PackageInfo> getPreferredPackages(int flags) {
13365        return new ArrayList<PackageInfo>();
13366    }
13367
13368    private int getUidTargetSdkVersionLockedLPr(int uid) {
13369        Object obj = mSettings.getUserIdLPr(uid);
13370        if (obj instanceof SharedUserSetting) {
13371            final SharedUserSetting sus = (SharedUserSetting) obj;
13372            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13373            final Iterator<PackageSetting> it = sus.packages.iterator();
13374            while (it.hasNext()) {
13375                final PackageSetting ps = it.next();
13376                if (ps.pkg != null) {
13377                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13378                    if (v < vers) vers = v;
13379                }
13380            }
13381            return vers;
13382        } else if (obj instanceof PackageSetting) {
13383            final PackageSetting ps = (PackageSetting) obj;
13384            if (ps.pkg != null) {
13385                return ps.pkg.applicationInfo.targetSdkVersion;
13386            }
13387        }
13388        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13389    }
13390
13391    @Override
13392    public void addPreferredActivity(IntentFilter filter, int match,
13393            ComponentName[] set, ComponentName activity, int userId) {
13394        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13395                "Adding preferred");
13396    }
13397
13398    private void addPreferredActivityInternal(IntentFilter filter, int match,
13399            ComponentName[] set, ComponentName activity, boolean always, int userId,
13400            String opname) {
13401        // writer
13402        int callingUid = Binder.getCallingUid();
13403        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13404        if (filter.countActions() == 0) {
13405            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13406            return;
13407        }
13408        synchronized (mPackages) {
13409            if (mContext.checkCallingOrSelfPermission(
13410                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13411                    != PackageManager.PERMISSION_GRANTED) {
13412                if (getUidTargetSdkVersionLockedLPr(callingUid)
13413                        < Build.VERSION_CODES.FROYO) {
13414                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13415                            + callingUid);
13416                    return;
13417                }
13418                mContext.enforceCallingOrSelfPermission(
13419                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13420            }
13421
13422            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13423            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13424                    + userId + ":");
13425            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13426            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13427            scheduleWritePackageRestrictionsLocked(userId);
13428        }
13429    }
13430
13431    @Override
13432    public void replacePreferredActivity(IntentFilter filter, int match,
13433            ComponentName[] set, ComponentName activity, int userId) {
13434        if (filter.countActions() != 1) {
13435            throw new IllegalArgumentException(
13436                    "replacePreferredActivity expects filter to have only 1 action.");
13437        }
13438        if (filter.countDataAuthorities() != 0
13439                || filter.countDataPaths() != 0
13440                || filter.countDataSchemes() > 1
13441                || filter.countDataTypes() != 0) {
13442            throw new IllegalArgumentException(
13443                    "replacePreferredActivity expects filter to have no data authorities, " +
13444                    "paths, or types; and at most one scheme.");
13445        }
13446
13447        final int callingUid = Binder.getCallingUid();
13448        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13449        synchronized (mPackages) {
13450            if (mContext.checkCallingOrSelfPermission(
13451                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13452                    != PackageManager.PERMISSION_GRANTED) {
13453                if (getUidTargetSdkVersionLockedLPr(callingUid)
13454                        < Build.VERSION_CODES.FROYO) {
13455                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13456                            + Binder.getCallingUid());
13457                    return;
13458                }
13459                mContext.enforceCallingOrSelfPermission(
13460                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13461            }
13462
13463            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13464            if (pir != null) {
13465                // Get all of the existing entries that exactly match this filter.
13466                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13467                if (existing != null && existing.size() == 1) {
13468                    PreferredActivity cur = existing.get(0);
13469                    if (DEBUG_PREFERRED) {
13470                        Slog.i(TAG, "Checking replace of preferred:");
13471                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13472                        if (!cur.mPref.mAlways) {
13473                            Slog.i(TAG, "  -- CUR; not mAlways!");
13474                        } else {
13475                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13476                            Slog.i(TAG, "  -- CUR: mSet="
13477                                    + Arrays.toString(cur.mPref.mSetComponents));
13478                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13479                            Slog.i(TAG, "  -- NEW: mMatch="
13480                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13481                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13482                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13483                        }
13484                    }
13485                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13486                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13487                            && cur.mPref.sameSet(set)) {
13488                        // Setting the preferred activity to what it happens to be already
13489                        if (DEBUG_PREFERRED) {
13490                            Slog.i(TAG, "Replacing with same preferred activity "
13491                                    + cur.mPref.mShortComponent + " for user "
13492                                    + userId + ":");
13493                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13494                        }
13495                        return;
13496                    }
13497                }
13498
13499                if (existing != null) {
13500                    if (DEBUG_PREFERRED) {
13501                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13502                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13503                    }
13504                    for (int i = 0; i < existing.size(); i++) {
13505                        PreferredActivity pa = existing.get(i);
13506                        if (DEBUG_PREFERRED) {
13507                            Slog.i(TAG, "Removing existing preferred activity "
13508                                    + pa.mPref.mComponent + ":");
13509                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13510                        }
13511                        pir.removeFilter(pa);
13512                    }
13513                }
13514            }
13515            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13516                    "Replacing preferred");
13517        }
13518    }
13519
13520    @Override
13521    public void clearPackagePreferredActivities(String packageName) {
13522        final int uid = Binder.getCallingUid();
13523        // writer
13524        synchronized (mPackages) {
13525            PackageParser.Package pkg = mPackages.get(packageName);
13526            if (pkg == null || pkg.applicationInfo.uid != uid) {
13527                if (mContext.checkCallingOrSelfPermission(
13528                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13529                        != PackageManager.PERMISSION_GRANTED) {
13530                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13531                            < Build.VERSION_CODES.FROYO) {
13532                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13533                                + Binder.getCallingUid());
13534                        return;
13535                    }
13536                    mContext.enforceCallingOrSelfPermission(
13537                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13538                }
13539            }
13540
13541            int user = UserHandle.getCallingUserId();
13542            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13543                scheduleWritePackageRestrictionsLocked(user);
13544            }
13545        }
13546    }
13547
13548    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13549    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13550        ArrayList<PreferredActivity> removed = null;
13551        boolean changed = false;
13552        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13553            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13554            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13555            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13556                continue;
13557            }
13558            Iterator<PreferredActivity> it = pir.filterIterator();
13559            while (it.hasNext()) {
13560                PreferredActivity pa = it.next();
13561                // Mark entry for removal only if it matches the package name
13562                // and the entry is of type "always".
13563                if (packageName == null ||
13564                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13565                                && pa.mPref.mAlways)) {
13566                    if (removed == null) {
13567                        removed = new ArrayList<PreferredActivity>();
13568                    }
13569                    removed.add(pa);
13570                }
13571            }
13572            if (removed != null) {
13573                for (int j=0; j<removed.size(); j++) {
13574                    PreferredActivity pa = removed.get(j);
13575                    pir.removeFilter(pa);
13576                }
13577                changed = true;
13578            }
13579        }
13580        return changed;
13581    }
13582
13583    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13584    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13585        if (userId == UserHandle.USER_ALL) {
13586            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13587                    sUserManager.getUserIds())) {
13588                for (int oneUserId : sUserManager.getUserIds()) {
13589                    scheduleWritePackageRestrictionsLocked(oneUserId);
13590                }
13591            }
13592        } else {
13593            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13594                scheduleWritePackageRestrictionsLocked(userId);
13595            }
13596        }
13597    }
13598
13599
13600    void clearDefaultBrowserIfNeeded(String packageName) {
13601        for (int oneUserId : sUserManager.getUserIds()) {
13602            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13603            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13604            if (packageName.equals(defaultBrowserPackageName)) {
13605                setDefaultBrowserPackageName(null, oneUserId);
13606            }
13607        }
13608    }
13609
13610    @Override
13611    public void resetPreferredActivities(int userId) {
13612        mContext.enforceCallingOrSelfPermission(
13613                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13614        // writer
13615        synchronized (mPackages) {
13616            clearPackagePreferredActivitiesLPw(null, userId);
13617            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13618            applyFactoryDefaultBrowserLPw(userId);
13619
13620            scheduleWritePackageRestrictionsLocked(userId);
13621        }
13622    }
13623
13624    @Override
13625    public int getPreferredActivities(List<IntentFilter> outFilters,
13626            List<ComponentName> outActivities, String packageName) {
13627
13628        int num = 0;
13629        final int userId = UserHandle.getCallingUserId();
13630        // reader
13631        synchronized (mPackages) {
13632            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13633            if (pir != null) {
13634                final Iterator<PreferredActivity> it = pir.filterIterator();
13635                while (it.hasNext()) {
13636                    final PreferredActivity pa = it.next();
13637                    if (packageName == null
13638                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13639                                    && pa.mPref.mAlways)) {
13640                        if (outFilters != null) {
13641                            outFilters.add(new IntentFilter(pa));
13642                        }
13643                        if (outActivities != null) {
13644                            outActivities.add(pa.mPref.mComponent);
13645                        }
13646                    }
13647                }
13648            }
13649        }
13650
13651        return num;
13652    }
13653
13654    @Override
13655    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13656            int userId) {
13657        int callingUid = Binder.getCallingUid();
13658        if (callingUid != Process.SYSTEM_UID) {
13659            throw new SecurityException(
13660                    "addPersistentPreferredActivity can only be run by the system");
13661        }
13662        if (filter.countActions() == 0) {
13663            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13664            return;
13665        }
13666        synchronized (mPackages) {
13667            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13668                    " :");
13669            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13670            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13671                    new PersistentPreferredActivity(filter, activity));
13672            scheduleWritePackageRestrictionsLocked(userId);
13673        }
13674    }
13675
13676    @Override
13677    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13678        int callingUid = Binder.getCallingUid();
13679        if (callingUid != Process.SYSTEM_UID) {
13680            throw new SecurityException(
13681                    "clearPackagePersistentPreferredActivities can only be run by the system");
13682        }
13683        ArrayList<PersistentPreferredActivity> removed = null;
13684        boolean changed = false;
13685        synchronized (mPackages) {
13686            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13687                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13688                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13689                        .valueAt(i);
13690                if (userId != thisUserId) {
13691                    continue;
13692                }
13693                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13694                while (it.hasNext()) {
13695                    PersistentPreferredActivity ppa = it.next();
13696                    // Mark entry for removal only if it matches the package name.
13697                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13698                        if (removed == null) {
13699                            removed = new ArrayList<PersistentPreferredActivity>();
13700                        }
13701                        removed.add(ppa);
13702                    }
13703                }
13704                if (removed != null) {
13705                    for (int j=0; j<removed.size(); j++) {
13706                        PersistentPreferredActivity ppa = removed.get(j);
13707                        ppir.removeFilter(ppa);
13708                    }
13709                    changed = true;
13710                }
13711            }
13712
13713            if (changed) {
13714                scheduleWritePackageRestrictionsLocked(userId);
13715            }
13716        }
13717    }
13718
13719    /**
13720     * Common machinery for picking apart a restored XML blob and passing
13721     * it to a caller-supplied functor to be applied to the running system.
13722     */
13723    private void restoreFromXml(XmlPullParser parser, int userId,
13724            String expectedStartTag, BlobXmlRestorer functor)
13725            throws IOException, XmlPullParserException {
13726        int type;
13727        while ((type = parser.next()) != XmlPullParser.START_TAG
13728                && type != XmlPullParser.END_DOCUMENT) {
13729        }
13730        if (type != XmlPullParser.START_TAG) {
13731            // oops didn't find a start tag?!
13732            if (DEBUG_BACKUP) {
13733                Slog.e(TAG, "Didn't find start tag during restore");
13734            }
13735            return;
13736        }
13737
13738        // this is supposed to be TAG_PREFERRED_BACKUP
13739        if (!expectedStartTag.equals(parser.getName())) {
13740            if (DEBUG_BACKUP) {
13741                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13742            }
13743            return;
13744        }
13745
13746        // skip interfering stuff, then we're aligned with the backing implementation
13747        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13748        functor.apply(parser, userId);
13749    }
13750
13751    private interface BlobXmlRestorer {
13752        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13753    }
13754
13755    /**
13756     * Non-Binder method, support for the backup/restore mechanism: write the
13757     * full set of preferred activities in its canonical XML format.  Returns the
13758     * XML output as a byte array, or null if there is none.
13759     */
13760    @Override
13761    public byte[] getPreferredActivityBackup(int userId) {
13762        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13763            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13764        }
13765
13766        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13767        try {
13768            final XmlSerializer serializer = new FastXmlSerializer();
13769            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13770            serializer.startDocument(null, true);
13771            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13772
13773            synchronized (mPackages) {
13774                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13775            }
13776
13777            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13778            serializer.endDocument();
13779            serializer.flush();
13780        } catch (Exception e) {
13781            if (DEBUG_BACKUP) {
13782                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13783            }
13784            return null;
13785        }
13786
13787        return dataStream.toByteArray();
13788    }
13789
13790    @Override
13791    public void restorePreferredActivities(byte[] backup, int userId) {
13792        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13793            throw new SecurityException("Only the system may call restorePreferredActivities()");
13794        }
13795
13796        try {
13797            final XmlPullParser parser = Xml.newPullParser();
13798            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13799            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13800                    new BlobXmlRestorer() {
13801                        @Override
13802                        public void apply(XmlPullParser parser, int userId)
13803                                throws XmlPullParserException, IOException {
13804                            synchronized (mPackages) {
13805                                mSettings.readPreferredActivitiesLPw(parser, userId);
13806                            }
13807                        }
13808                    } );
13809        } catch (Exception e) {
13810            if (DEBUG_BACKUP) {
13811                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13812            }
13813        }
13814    }
13815
13816    /**
13817     * Non-Binder method, support for the backup/restore mechanism: write the
13818     * default browser (etc) settings in its canonical XML format.  Returns the default
13819     * browser XML representation as a byte array, or null if there is none.
13820     */
13821    @Override
13822    public byte[] getDefaultAppsBackup(int userId) {
13823        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13824            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13825        }
13826
13827        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13828        try {
13829            final XmlSerializer serializer = new FastXmlSerializer();
13830            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13831            serializer.startDocument(null, true);
13832            serializer.startTag(null, TAG_DEFAULT_APPS);
13833
13834            synchronized (mPackages) {
13835                mSettings.writeDefaultAppsLPr(serializer, userId);
13836            }
13837
13838            serializer.endTag(null, TAG_DEFAULT_APPS);
13839            serializer.endDocument();
13840            serializer.flush();
13841        } catch (Exception e) {
13842            if (DEBUG_BACKUP) {
13843                Slog.e(TAG, "Unable to write default apps for backup", e);
13844            }
13845            return null;
13846        }
13847
13848        return dataStream.toByteArray();
13849    }
13850
13851    @Override
13852    public void restoreDefaultApps(byte[] backup, int userId) {
13853        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13854            throw new SecurityException("Only the system may call restoreDefaultApps()");
13855        }
13856
13857        try {
13858            final XmlPullParser parser = Xml.newPullParser();
13859            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13860            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13861                    new BlobXmlRestorer() {
13862                        @Override
13863                        public void apply(XmlPullParser parser, int userId)
13864                                throws XmlPullParserException, IOException {
13865                            synchronized (mPackages) {
13866                                mSettings.readDefaultAppsLPw(parser, userId);
13867                            }
13868                        }
13869                    } );
13870        } catch (Exception e) {
13871            if (DEBUG_BACKUP) {
13872                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13873            }
13874        }
13875    }
13876
13877    @Override
13878    public byte[] getIntentFilterVerificationBackup(int userId) {
13879        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13880            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13881        }
13882
13883        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13884        try {
13885            final XmlSerializer serializer = new FastXmlSerializer();
13886            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13887            serializer.startDocument(null, true);
13888            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13889
13890            synchronized (mPackages) {
13891                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13892            }
13893
13894            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13895            serializer.endDocument();
13896            serializer.flush();
13897        } catch (Exception e) {
13898            if (DEBUG_BACKUP) {
13899                Slog.e(TAG, "Unable to write default apps for backup", e);
13900            }
13901            return null;
13902        }
13903
13904        return dataStream.toByteArray();
13905    }
13906
13907    @Override
13908    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13909        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13910            throw new SecurityException("Only the system may call restorePreferredActivities()");
13911        }
13912
13913        try {
13914            final XmlPullParser parser = Xml.newPullParser();
13915            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13916            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13917                    new BlobXmlRestorer() {
13918                        @Override
13919                        public void apply(XmlPullParser parser, int userId)
13920                                throws XmlPullParserException, IOException {
13921                            synchronized (mPackages) {
13922                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13923                                mSettings.writeLPr();
13924                            }
13925                        }
13926                    } );
13927        } catch (Exception e) {
13928            if (DEBUG_BACKUP) {
13929                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13930            }
13931        }
13932    }
13933
13934    @Override
13935    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13936            int sourceUserId, int targetUserId, int flags) {
13937        mContext.enforceCallingOrSelfPermission(
13938                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13939        int callingUid = Binder.getCallingUid();
13940        enforceOwnerRights(ownerPackage, callingUid);
13941        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13942        if (intentFilter.countActions() == 0) {
13943            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13944            return;
13945        }
13946        synchronized (mPackages) {
13947            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13948                    ownerPackage, targetUserId, flags);
13949            CrossProfileIntentResolver resolver =
13950                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13951            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13952            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13953            if (existing != null) {
13954                int size = existing.size();
13955                for (int i = 0; i < size; i++) {
13956                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13957                        return;
13958                    }
13959                }
13960            }
13961            resolver.addFilter(newFilter);
13962            scheduleWritePackageRestrictionsLocked(sourceUserId);
13963        }
13964    }
13965
13966    @Override
13967    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13968        mContext.enforceCallingOrSelfPermission(
13969                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13970        int callingUid = Binder.getCallingUid();
13971        enforceOwnerRights(ownerPackage, callingUid);
13972        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13973        synchronized (mPackages) {
13974            CrossProfileIntentResolver resolver =
13975                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13976            ArraySet<CrossProfileIntentFilter> set =
13977                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13978            for (CrossProfileIntentFilter filter : set) {
13979                if (filter.getOwnerPackage().equals(ownerPackage)) {
13980                    resolver.removeFilter(filter);
13981                }
13982            }
13983            scheduleWritePackageRestrictionsLocked(sourceUserId);
13984        }
13985    }
13986
13987    // Enforcing that callingUid is owning pkg on userId
13988    private void enforceOwnerRights(String pkg, int callingUid) {
13989        // The system owns everything.
13990        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13991            return;
13992        }
13993        int callingUserId = UserHandle.getUserId(callingUid);
13994        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13995        if (pi == null) {
13996            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13997                    + callingUserId);
13998        }
13999        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14000            throw new SecurityException("Calling uid " + callingUid
14001                    + " does not own package " + pkg);
14002        }
14003    }
14004
14005    @Override
14006    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14007        Intent intent = new Intent(Intent.ACTION_MAIN);
14008        intent.addCategory(Intent.CATEGORY_HOME);
14009
14010        final int callingUserId = UserHandle.getCallingUserId();
14011        List<ResolveInfo> list = queryIntentActivities(intent, null,
14012                PackageManager.GET_META_DATA, callingUserId);
14013        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14014                true, false, false, callingUserId);
14015
14016        allHomeCandidates.clear();
14017        if (list != null) {
14018            for (ResolveInfo ri : list) {
14019                allHomeCandidates.add(ri);
14020            }
14021        }
14022        return (preferred == null || preferred.activityInfo == null)
14023                ? null
14024                : new ComponentName(preferred.activityInfo.packageName,
14025                        preferred.activityInfo.name);
14026    }
14027
14028    @Override
14029    public void setApplicationEnabledSetting(String appPackageName,
14030            int newState, int flags, int userId, String callingPackage) {
14031        if (!sUserManager.exists(userId)) return;
14032        if (callingPackage == null) {
14033            callingPackage = Integer.toString(Binder.getCallingUid());
14034        }
14035        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14036    }
14037
14038    @Override
14039    public void setComponentEnabledSetting(ComponentName componentName,
14040            int newState, int flags, int userId) {
14041        if (!sUserManager.exists(userId)) return;
14042        setEnabledSetting(componentName.getPackageName(),
14043                componentName.getClassName(), newState, flags, userId, null);
14044    }
14045
14046    private void setEnabledSetting(final String packageName, String className, int newState,
14047            final int flags, int userId, String callingPackage) {
14048        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14049              || newState == COMPONENT_ENABLED_STATE_ENABLED
14050              || newState == COMPONENT_ENABLED_STATE_DISABLED
14051              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14052              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14053            throw new IllegalArgumentException("Invalid new component state: "
14054                    + newState);
14055        }
14056        PackageSetting pkgSetting;
14057        final int uid = Binder.getCallingUid();
14058        final int permission = mContext.checkCallingOrSelfPermission(
14059                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14060        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14061        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14062        boolean sendNow = false;
14063        boolean isApp = (className == null);
14064        String componentName = isApp ? packageName : className;
14065        int packageUid = -1;
14066        ArrayList<String> components;
14067
14068        // writer
14069        synchronized (mPackages) {
14070            pkgSetting = mSettings.mPackages.get(packageName);
14071            if (pkgSetting == null) {
14072                if (className == null) {
14073                    throw new IllegalArgumentException(
14074                            "Unknown package: " + packageName);
14075                }
14076                throw new IllegalArgumentException(
14077                        "Unknown component: " + packageName
14078                        + "/" + className);
14079            }
14080            // Allow root and verify that userId is not being specified by a different user
14081            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14082                throw new SecurityException(
14083                        "Permission Denial: attempt to change component state from pid="
14084                        + Binder.getCallingPid()
14085                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14086            }
14087            if (className == null) {
14088                // We're dealing with an application/package level state change
14089                if (pkgSetting.getEnabled(userId) == newState) {
14090                    // Nothing to do
14091                    return;
14092                }
14093                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14094                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14095                    // Don't care about who enables an app.
14096                    callingPackage = null;
14097                }
14098                pkgSetting.setEnabled(newState, userId, callingPackage);
14099                // pkgSetting.pkg.mSetEnabled = newState;
14100            } else {
14101                // We're dealing with a component level state change
14102                // First, verify that this is a valid class name.
14103                PackageParser.Package pkg = pkgSetting.pkg;
14104                if (pkg == null || !pkg.hasComponentClassName(className)) {
14105                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14106                        throw new IllegalArgumentException("Component class " + className
14107                                + " does not exist in " + packageName);
14108                    } else {
14109                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14110                                + className + " does not exist in " + packageName);
14111                    }
14112                }
14113                switch (newState) {
14114                case COMPONENT_ENABLED_STATE_ENABLED:
14115                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14116                        return;
14117                    }
14118                    break;
14119                case COMPONENT_ENABLED_STATE_DISABLED:
14120                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14121                        return;
14122                    }
14123                    break;
14124                case COMPONENT_ENABLED_STATE_DEFAULT:
14125                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14126                        return;
14127                    }
14128                    break;
14129                default:
14130                    Slog.e(TAG, "Invalid new component state: " + newState);
14131                    return;
14132                }
14133            }
14134            scheduleWritePackageRestrictionsLocked(userId);
14135            components = mPendingBroadcasts.get(userId, packageName);
14136            final boolean newPackage = components == null;
14137            if (newPackage) {
14138                components = new ArrayList<String>();
14139            }
14140            if (!components.contains(componentName)) {
14141                components.add(componentName);
14142            }
14143            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14144                sendNow = true;
14145                // Purge entry from pending broadcast list if another one exists already
14146                // since we are sending one right away.
14147                mPendingBroadcasts.remove(userId, packageName);
14148            } else {
14149                if (newPackage) {
14150                    mPendingBroadcasts.put(userId, packageName, components);
14151                }
14152                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14153                    // Schedule a message
14154                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14155                }
14156            }
14157        }
14158
14159        long callingId = Binder.clearCallingIdentity();
14160        try {
14161            if (sendNow) {
14162                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14163                sendPackageChangedBroadcast(packageName,
14164                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14165            }
14166        } finally {
14167            Binder.restoreCallingIdentity(callingId);
14168        }
14169    }
14170
14171    private void sendPackageChangedBroadcast(String packageName,
14172            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14173        if (DEBUG_INSTALL)
14174            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14175                    + componentNames);
14176        Bundle extras = new Bundle(4);
14177        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14178        String nameList[] = new String[componentNames.size()];
14179        componentNames.toArray(nameList);
14180        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14181        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14182        extras.putInt(Intent.EXTRA_UID, packageUid);
14183        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14184                new int[] {UserHandle.getUserId(packageUid)});
14185    }
14186
14187    @Override
14188    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14189        if (!sUserManager.exists(userId)) return;
14190        final int uid = Binder.getCallingUid();
14191        final int permission = mContext.checkCallingOrSelfPermission(
14192                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14193        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14194        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14195        // writer
14196        synchronized (mPackages) {
14197            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14198                    allowedByPermission, uid, userId)) {
14199                scheduleWritePackageRestrictionsLocked(userId);
14200            }
14201        }
14202    }
14203
14204    @Override
14205    public String getInstallerPackageName(String packageName) {
14206        // reader
14207        synchronized (mPackages) {
14208            return mSettings.getInstallerPackageNameLPr(packageName);
14209        }
14210    }
14211
14212    @Override
14213    public int getApplicationEnabledSetting(String packageName, int userId) {
14214        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14215        int uid = Binder.getCallingUid();
14216        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14217        // reader
14218        synchronized (mPackages) {
14219            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14220        }
14221    }
14222
14223    @Override
14224    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14225        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14226        int uid = Binder.getCallingUid();
14227        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14228        // reader
14229        synchronized (mPackages) {
14230            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14231        }
14232    }
14233
14234    @Override
14235    public void enterSafeMode() {
14236        enforceSystemOrRoot("Only the system can request entering safe mode");
14237
14238        if (!mSystemReady) {
14239            mSafeMode = true;
14240        }
14241    }
14242
14243    @Override
14244    public void systemReady() {
14245        mSystemReady = true;
14246
14247        // Read the compatibilty setting when the system is ready.
14248        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14249                mContext.getContentResolver(),
14250                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14251        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14252        if (DEBUG_SETTINGS) {
14253            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14254        }
14255
14256        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14257
14258        synchronized (mPackages) {
14259            // Verify that all of the preferred activity components actually
14260            // exist.  It is possible for applications to be updated and at
14261            // that point remove a previously declared activity component that
14262            // had been set as a preferred activity.  We try to clean this up
14263            // the next time we encounter that preferred activity, but it is
14264            // possible for the user flow to never be able to return to that
14265            // situation so here we do a sanity check to make sure we haven't
14266            // left any junk around.
14267            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14268            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14269                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14270                removed.clear();
14271                for (PreferredActivity pa : pir.filterSet()) {
14272                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14273                        removed.add(pa);
14274                    }
14275                }
14276                if (removed.size() > 0) {
14277                    for (int r=0; r<removed.size(); r++) {
14278                        PreferredActivity pa = removed.get(r);
14279                        Slog.w(TAG, "Removing dangling preferred activity: "
14280                                + pa.mPref.mComponent);
14281                        pir.removeFilter(pa);
14282                    }
14283                    mSettings.writePackageRestrictionsLPr(
14284                            mSettings.mPreferredActivities.keyAt(i));
14285                }
14286            }
14287
14288            for (int userId : UserManagerService.getInstance().getUserIds()) {
14289                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14290                    grantPermissionsUserIds = ArrayUtils.appendInt(
14291                            grantPermissionsUserIds, userId);
14292                }
14293            }
14294        }
14295        sUserManager.systemReady();
14296
14297        // If we upgraded grant all default permissions before kicking off.
14298        for (int userId : grantPermissionsUserIds) {
14299            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14300        }
14301
14302        // Kick off any messages waiting for system ready
14303        if (mPostSystemReadyMessages != null) {
14304            for (Message msg : mPostSystemReadyMessages) {
14305                msg.sendToTarget();
14306            }
14307            mPostSystemReadyMessages = null;
14308        }
14309
14310        // Watch for external volumes that come and go over time
14311        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14312        storage.registerListener(mStorageListener);
14313
14314        mInstallerService.systemReady();
14315        mPackageDexOptimizer.systemReady();
14316    }
14317
14318    @Override
14319    public boolean isSafeMode() {
14320        return mSafeMode;
14321    }
14322
14323    @Override
14324    public boolean hasSystemUidErrors() {
14325        return mHasSystemUidErrors;
14326    }
14327
14328    static String arrayToString(int[] array) {
14329        StringBuffer buf = new StringBuffer(128);
14330        buf.append('[');
14331        if (array != null) {
14332            for (int i=0; i<array.length; i++) {
14333                if (i > 0) buf.append(", ");
14334                buf.append(array[i]);
14335            }
14336        }
14337        buf.append(']');
14338        return buf.toString();
14339    }
14340
14341    static class DumpState {
14342        public static final int DUMP_LIBS = 1 << 0;
14343        public static final int DUMP_FEATURES = 1 << 1;
14344        public static final int DUMP_RESOLVERS = 1 << 2;
14345        public static final int DUMP_PERMISSIONS = 1 << 3;
14346        public static final int DUMP_PACKAGES = 1 << 4;
14347        public static final int DUMP_SHARED_USERS = 1 << 5;
14348        public static final int DUMP_MESSAGES = 1 << 6;
14349        public static final int DUMP_PROVIDERS = 1 << 7;
14350        public static final int DUMP_VERIFIERS = 1 << 8;
14351        public static final int DUMP_PREFERRED = 1 << 9;
14352        public static final int DUMP_PREFERRED_XML = 1 << 10;
14353        public static final int DUMP_KEYSETS = 1 << 11;
14354        public static final int DUMP_VERSION = 1 << 12;
14355        public static final int DUMP_INSTALLS = 1 << 13;
14356        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14357        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14358
14359        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14360
14361        private int mTypes;
14362
14363        private int mOptions;
14364
14365        private boolean mTitlePrinted;
14366
14367        private SharedUserSetting mSharedUser;
14368
14369        public boolean isDumping(int type) {
14370            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14371                return true;
14372            }
14373
14374            return (mTypes & type) != 0;
14375        }
14376
14377        public void setDump(int type) {
14378            mTypes |= type;
14379        }
14380
14381        public boolean isOptionEnabled(int option) {
14382            return (mOptions & option) != 0;
14383        }
14384
14385        public void setOptionEnabled(int option) {
14386            mOptions |= option;
14387        }
14388
14389        public boolean onTitlePrinted() {
14390            final boolean printed = mTitlePrinted;
14391            mTitlePrinted = true;
14392            return printed;
14393        }
14394
14395        public boolean getTitlePrinted() {
14396            return mTitlePrinted;
14397        }
14398
14399        public void setTitlePrinted(boolean enabled) {
14400            mTitlePrinted = enabled;
14401        }
14402
14403        public SharedUserSetting getSharedUser() {
14404            return mSharedUser;
14405        }
14406
14407        public void setSharedUser(SharedUserSetting user) {
14408            mSharedUser = user;
14409        }
14410    }
14411
14412    @Override
14413    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14414        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14415                != PackageManager.PERMISSION_GRANTED) {
14416            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14417                    + Binder.getCallingPid()
14418                    + ", uid=" + Binder.getCallingUid()
14419                    + " without permission "
14420                    + android.Manifest.permission.DUMP);
14421            return;
14422        }
14423
14424        DumpState dumpState = new DumpState();
14425        boolean fullPreferred = false;
14426        boolean checkin = false;
14427
14428        String packageName = null;
14429        ArraySet<String> permissionNames = null;
14430
14431        int opti = 0;
14432        while (opti < args.length) {
14433            String opt = args[opti];
14434            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14435                break;
14436            }
14437            opti++;
14438
14439            if ("-a".equals(opt)) {
14440                // Right now we only know how to print all.
14441            } else if ("-h".equals(opt)) {
14442                pw.println("Package manager dump options:");
14443                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14444                pw.println("    --checkin: dump for a checkin");
14445                pw.println("    -f: print details of intent filters");
14446                pw.println("    -h: print this help");
14447                pw.println("  cmd may be one of:");
14448                pw.println("    l[ibraries]: list known shared libraries");
14449                pw.println("    f[ibraries]: list device features");
14450                pw.println("    k[eysets]: print known keysets");
14451                pw.println("    r[esolvers]: dump intent resolvers");
14452                pw.println("    perm[issions]: dump permissions");
14453                pw.println("    permission [name ...]: dump declaration and use of given permission");
14454                pw.println("    pref[erred]: print preferred package settings");
14455                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14456                pw.println("    prov[iders]: dump content providers");
14457                pw.println("    p[ackages]: dump installed packages");
14458                pw.println("    s[hared-users]: dump shared user IDs");
14459                pw.println("    m[essages]: print collected runtime messages");
14460                pw.println("    v[erifiers]: print package verifier info");
14461                pw.println("    version: print database version info");
14462                pw.println("    write: write current settings now");
14463                pw.println("    <package.name>: info about given package");
14464                pw.println("    installs: details about install sessions");
14465                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14466                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14467                return;
14468            } else if ("--checkin".equals(opt)) {
14469                checkin = true;
14470            } else if ("-f".equals(opt)) {
14471                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14472            } else {
14473                pw.println("Unknown argument: " + opt + "; use -h for help");
14474            }
14475        }
14476
14477        // Is the caller requesting to dump a particular piece of data?
14478        if (opti < args.length) {
14479            String cmd = args[opti];
14480            opti++;
14481            // Is this a package name?
14482            if ("android".equals(cmd) || cmd.contains(".")) {
14483                packageName = cmd;
14484                // When dumping a single package, we always dump all of its
14485                // filter information since the amount of data will be reasonable.
14486                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14487            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14488                dumpState.setDump(DumpState.DUMP_LIBS);
14489            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14490                dumpState.setDump(DumpState.DUMP_FEATURES);
14491            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14492                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14493            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14494                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14495            } else if ("permission".equals(cmd)) {
14496                if (opti >= args.length) {
14497                    pw.println("Error: permission requires permission name");
14498                    return;
14499                }
14500                permissionNames = new ArraySet<>();
14501                while (opti < args.length) {
14502                    permissionNames.add(args[opti]);
14503                    opti++;
14504                }
14505                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14506                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14507            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14508                dumpState.setDump(DumpState.DUMP_PREFERRED);
14509            } else if ("preferred-xml".equals(cmd)) {
14510                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14511                if (opti < args.length && "--full".equals(args[opti])) {
14512                    fullPreferred = true;
14513                    opti++;
14514                }
14515            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14516                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14517            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14518                dumpState.setDump(DumpState.DUMP_PACKAGES);
14519            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14520                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14521            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14522                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14523            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14524                dumpState.setDump(DumpState.DUMP_MESSAGES);
14525            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14526                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14527            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14528                    || "intent-filter-verifiers".equals(cmd)) {
14529                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14530            } else if ("version".equals(cmd)) {
14531                dumpState.setDump(DumpState.DUMP_VERSION);
14532            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14533                dumpState.setDump(DumpState.DUMP_KEYSETS);
14534            } else if ("installs".equals(cmd)) {
14535                dumpState.setDump(DumpState.DUMP_INSTALLS);
14536            } else if ("write".equals(cmd)) {
14537                synchronized (mPackages) {
14538                    mSettings.writeLPr();
14539                    pw.println("Settings written.");
14540                    return;
14541                }
14542            }
14543        }
14544
14545        if (checkin) {
14546            pw.println("vers,1");
14547        }
14548
14549        // reader
14550        synchronized (mPackages) {
14551            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14552                if (!checkin) {
14553                    if (dumpState.onTitlePrinted())
14554                        pw.println();
14555                    pw.println("Database versions:");
14556                    pw.print("  SDK Version:");
14557                    pw.print(" internal=");
14558                    pw.print(mSettings.mInternalSdkPlatform);
14559                    pw.print(" external=");
14560                    pw.println(mSettings.mExternalSdkPlatform);
14561                    pw.print("  DB Version:");
14562                    pw.print(" internal=");
14563                    pw.print(mSettings.mInternalDatabaseVersion);
14564                    pw.print(" external=");
14565                    pw.println(mSettings.mExternalDatabaseVersion);
14566                }
14567            }
14568
14569            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14570                if (!checkin) {
14571                    if (dumpState.onTitlePrinted())
14572                        pw.println();
14573                    pw.println("Verifiers:");
14574                    pw.print("  Required: ");
14575                    pw.print(mRequiredVerifierPackage);
14576                    pw.print(" (uid=");
14577                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14578                    pw.println(")");
14579                } else if (mRequiredVerifierPackage != null) {
14580                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14581                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14582                }
14583            }
14584
14585            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14586                    packageName == null) {
14587                if (mIntentFilterVerifierComponent != null) {
14588                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14589                    if (!checkin) {
14590                        if (dumpState.onTitlePrinted())
14591                            pw.println();
14592                        pw.println("Intent Filter Verifier:");
14593                        pw.print("  Using: ");
14594                        pw.print(verifierPackageName);
14595                        pw.print(" (uid=");
14596                        pw.print(getPackageUid(verifierPackageName, 0));
14597                        pw.println(")");
14598                    } else if (verifierPackageName != null) {
14599                        pw.print("ifv,"); pw.print(verifierPackageName);
14600                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14601                    }
14602                } else {
14603                    pw.println();
14604                    pw.println("No Intent Filter Verifier available!");
14605                }
14606            }
14607
14608            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14609                boolean printedHeader = false;
14610                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14611                while (it.hasNext()) {
14612                    String name = it.next();
14613                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14614                    if (!checkin) {
14615                        if (!printedHeader) {
14616                            if (dumpState.onTitlePrinted())
14617                                pw.println();
14618                            pw.println("Libraries:");
14619                            printedHeader = true;
14620                        }
14621                        pw.print("  ");
14622                    } else {
14623                        pw.print("lib,");
14624                    }
14625                    pw.print(name);
14626                    if (!checkin) {
14627                        pw.print(" -> ");
14628                    }
14629                    if (ent.path != null) {
14630                        if (!checkin) {
14631                            pw.print("(jar) ");
14632                            pw.print(ent.path);
14633                        } else {
14634                            pw.print(",jar,");
14635                            pw.print(ent.path);
14636                        }
14637                    } else {
14638                        if (!checkin) {
14639                            pw.print("(apk) ");
14640                            pw.print(ent.apk);
14641                        } else {
14642                            pw.print(",apk,");
14643                            pw.print(ent.apk);
14644                        }
14645                    }
14646                    pw.println();
14647                }
14648            }
14649
14650            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14651                if (dumpState.onTitlePrinted())
14652                    pw.println();
14653                if (!checkin) {
14654                    pw.println("Features:");
14655                }
14656                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14657                while (it.hasNext()) {
14658                    String name = it.next();
14659                    if (!checkin) {
14660                        pw.print("  ");
14661                    } else {
14662                        pw.print("feat,");
14663                    }
14664                    pw.println(name);
14665                }
14666            }
14667
14668            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14669                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14670                        : "Activity Resolver Table:", "  ", packageName,
14671                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14672                    dumpState.setTitlePrinted(true);
14673                }
14674                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14675                        : "Receiver Resolver Table:", "  ", packageName,
14676                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14677                    dumpState.setTitlePrinted(true);
14678                }
14679                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14680                        : "Service Resolver Table:", "  ", packageName,
14681                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14682                    dumpState.setTitlePrinted(true);
14683                }
14684                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14685                        : "Provider Resolver Table:", "  ", packageName,
14686                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14687                    dumpState.setTitlePrinted(true);
14688                }
14689            }
14690
14691            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14692                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14693                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14694                    int user = mSettings.mPreferredActivities.keyAt(i);
14695                    if (pir.dump(pw,
14696                            dumpState.getTitlePrinted()
14697                                ? "\nPreferred Activities User " + user + ":"
14698                                : "Preferred Activities User " + user + ":", "  ",
14699                            packageName, true, false)) {
14700                        dumpState.setTitlePrinted(true);
14701                    }
14702                }
14703            }
14704
14705            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14706                pw.flush();
14707                FileOutputStream fout = new FileOutputStream(fd);
14708                BufferedOutputStream str = new BufferedOutputStream(fout);
14709                XmlSerializer serializer = new FastXmlSerializer();
14710                try {
14711                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14712                    serializer.startDocument(null, true);
14713                    serializer.setFeature(
14714                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14715                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14716                    serializer.endDocument();
14717                    serializer.flush();
14718                } catch (IllegalArgumentException e) {
14719                    pw.println("Failed writing: " + e);
14720                } catch (IllegalStateException e) {
14721                    pw.println("Failed writing: " + e);
14722                } catch (IOException e) {
14723                    pw.println("Failed writing: " + e);
14724                }
14725            }
14726
14727            if (!checkin
14728                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14729                    && packageName == null) {
14730                pw.println();
14731                int count = mSettings.mPackages.size();
14732                if (count == 0) {
14733                    pw.println("No domain preferred apps!");
14734                    pw.println();
14735                } else {
14736                    final String prefix = "  ";
14737                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14738                    if (allPackageSettings.size() == 0) {
14739                        pw.println("No domain preferred apps!");
14740                        pw.println();
14741                    } else {
14742                        pw.println("Domain preferred apps status:");
14743                        pw.println();
14744                        count = 0;
14745                        for (PackageSetting ps : allPackageSettings) {
14746                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14747                            if (ivi == null || ivi.getPackageName() == null) continue;
14748                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14749                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14750                            pw.println(prefix + "Status: " + ivi.getStatusString());
14751                            pw.println();
14752                            count++;
14753                        }
14754                        if (count == 0) {
14755                            pw.println(prefix + "No domain preferred app status!");
14756                            pw.println();
14757                        }
14758                        for (int userId : sUserManager.getUserIds()) {
14759                            pw.println("Domain preferred apps for User " + userId + ":");
14760                            pw.println();
14761                            count = 0;
14762                            for (PackageSetting ps : allPackageSettings) {
14763                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14764                                if (ivi == null || ivi.getPackageName() == null) {
14765                                    continue;
14766                                }
14767                                final int status = ps.getDomainVerificationStatusForUser(userId);
14768                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14769                                    continue;
14770                                }
14771                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14772                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14773                                String statusStr = IntentFilterVerificationInfo.
14774                                        getStatusStringFromValue(status);
14775                                pw.println(prefix + "Status: " + statusStr);
14776                                pw.println();
14777                                count++;
14778                            }
14779                            if (count == 0) {
14780                                pw.println(prefix + "No domain preferred apps!");
14781                                pw.println();
14782                            }
14783                        }
14784                    }
14785                }
14786            }
14787
14788            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14789                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14790                if (packageName == null && permissionNames == null) {
14791                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14792                        if (iperm == 0) {
14793                            if (dumpState.onTitlePrinted())
14794                                pw.println();
14795                            pw.println("AppOp Permissions:");
14796                        }
14797                        pw.print("  AppOp Permission ");
14798                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14799                        pw.println(":");
14800                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14801                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14802                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14803                        }
14804                    }
14805                }
14806            }
14807
14808            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14809                boolean printedSomething = false;
14810                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14811                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14812                        continue;
14813                    }
14814                    if (!printedSomething) {
14815                        if (dumpState.onTitlePrinted())
14816                            pw.println();
14817                        pw.println("Registered ContentProviders:");
14818                        printedSomething = true;
14819                    }
14820                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14821                    pw.print("    "); pw.println(p.toString());
14822                }
14823                printedSomething = false;
14824                for (Map.Entry<String, PackageParser.Provider> entry :
14825                        mProvidersByAuthority.entrySet()) {
14826                    PackageParser.Provider p = entry.getValue();
14827                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14828                        continue;
14829                    }
14830                    if (!printedSomething) {
14831                        if (dumpState.onTitlePrinted())
14832                            pw.println();
14833                        pw.println("ContentProvider Authorities:");
14834                        printedSomething = true;
14835                    }
14836                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14837                    pw.print("    "); pw.println(p.toString());
14838                    if (p.info != null && p.info.applicationInfo != null) {
14839                        final String appInfo = p.info.applicationInfo.toString();
14840                        pw.print("      applicationInfo="); pw.println(appInfo);
14841                    }
14842                }
14843            }
14844
14845            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14846                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14847            }
14848
14849            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14850                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14851            }
14852
14853            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14854                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14855            }
14856
14857            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14858                // XXX should handle packageName != null by dumping only install data that
14859                // the given package is involved with.
14860                if (dumpState.onTitlePrinted()) pw.println();
14861                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14862            }
14863
14864            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14865                if (dumpState.onTitlePrinted()) pw.println();
14866                mSettings.dumpReadMessagesLPr(pw, dumpState);
14867
14868                pw.println();
14869                pw.println("Package warning messages:");
14870                BufferedReader in = null;
14871                String line = null;
14872                try {
14873                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14874                    while ((line = in.readLine()) != null) {
14875                        if (line.contains("ignored: updated version")) continue;
14876                        pw.println(line);
14877                    }
14878                } catch (IOException ignored) {
14879                } finally {
14880                    IoUtils.closeQuietly(in);
14881                }
14882            }
14883
14884            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14885                BufferedReader in = null;
14886                String line = null;
14887                try {
14888                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14889                    while ((line = in.readLine()) != null) {
14890                        if (line.contains("ignored: updated version")) continue;
14891                        pw.print("msg,");
14892                        pw.println(line);
14893                    }
14894                } catch (IOException ignored) {
14895                } finally {
14896                    IoUtils.closeQuietly(in);
14897                }
14898            }
14899        }
14900    }
14901
14902    // ------- apps on sdcard specific code -------
14903    static final boolean DEBUG_SD_INSTALL = false;
14904
14905    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14906
14907    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14908
14909    private boolean mMediaMounted = false;
14910
14911    static String getEncryptKey() {
14912        try {
14913            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14914                    SD_ENCRYPTION_KEYSTORE_NAME);
14915            if (sdEncKey == null) {
14916                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14917                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14918                if (sdEncKey == null) {
14919                    Slog.e(TAG, "Failed to create encryption keys");
14920                    return null;
14921                }
14922            }
14923            return sdEncKey;
14924        } catch (NoSuchAlgorithmException nsae) {
14925            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14926            return null;
14927        } catch (IOException ioe) {
14928            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14929            return null;
14930        }
14931    }
14932
14933    /*
14934     * Update media status on PackageManager.
14935     */
14936    @Override
14937    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14938        int callingUid = Binder.getCallingUid();
14939        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14940            throw new SecurityException("Media status can only be updated by the system");
14941        }
14942        // reader; this apparently protects mMediaMounted, but should probably
14943        // be a different lock in that case.
14944        synchronized (mPackages) {
14945            Log.i(TAG, "Updating external media status from "
14946                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14947                    + (mediaStatus ? "mounted" : "unmounted"));
14948            if (DEBUG_SD_INSTALL)
14949                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14950                        + ", mMediaMounted=" + mMediaMounted);
14951            if (mediaStatus == mMediaMounted) {
14952                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14953                        : 0, -1);
14954                mHandler.sendMessage(msg);
14955                return;
14956            }
14957            mMediaMounted = mediaStatus;
14958        }
14959        // Queue up an async operation since the package installation may take a
14960        // little while.
14961        mHandler.post(new Runnable() {
14962            public void run() {
14963                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14964            }
14965        });
14966    }
14967
14968    /**
14969     * Called by MountService when the initial ASECs to scan are available.
14970     * Should block until all the ASEC containers are finished being scanned.
14971     */
14972    public void scanAvailableAsecs() {
14973        updateExternalMediaStatusInner(true, false, false);
14974        if (mShouldRestoreconData) {
14975            SELinuxMMAC.setRestoreconDone();
14976            mShouldRestoreconData = false;
14977        }
14978    }
14979
14980    /*
14981     * Collect information of applications on external media, map them against
14982     * existing containers and update information based on current mount status.
14983     * Please note that we always have to report status if reportStatus has been
14984     * set to true especially when unloading packages.
14985     */
14986    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14987            boolean externalStorage) {
14988        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14989        int[] uidArr = EmptyArray.INT;
14990
14991        final String[] list = PackageHelper.getSecureContainerList();
14992        if (ArrayUtils.isEmpty(list)) {
14993            Log.i(TAG, "No secure containers found");
14994        } else {
14995            // Process list of secure containers and categorize them
14996            // as active or stale based on their package internal state.
14997
14998            // reader
14999            synchronized (mPackages) {
15000                for (String cid : list) {
15001                    // Leave stages untouched for now; installer service owns them
15002                    if (PackageInstallerService.isStageName(cid)) continue;
15003
15004                    if (DEBUG_SD_INSTALL)
15005                        Log.i(TAG, "Processing container " + cid);
15006                    String pkgName = getAsecPackageName(cid);
15007                    if (pkgName == null) {
15008                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15009                        continue;
15010                    }
15011                    if (DEBUG_SD_INSTALL)
15012                        Log.i(TAG, "Looking for pkg : " + pkgName);
15013
15014                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15015                    if (ps == null) {
15016                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15017                        continue;
15018                    }
15019
15020                    /*
15021                     * Skip packages that are not external if we're unmounting
15022                     * external storage.
15023                     */
15024                    if (externalStorage && !isMounted && !isExternal(ps)) {
15025                        continue;
15026                    }
15027
15028                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15029                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15030                    // The package status is changed only if the code path
15031                    // matches between settings and the container id.
15032                    if (ps.codePathString != null
15033                            && ps.codePathString.startsWith(args.getCodePath())) {
15034                        if (DEBUG_SD_INSTALL) {
15035                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15036                                    + " at code path: " + ps.codePathString);
15037                        }
15038
15039                        // We do have a valid package installed on sdcard
15040                        processCids.put(args, ps.codePathString);
15041                        final int uid = ps.appId;
15042                        if (uid != -1) {
15043                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15044                        }
15045                    } else {
15046                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15047                                + ps.codePathString);
15048                    }
15049                }
15050            }
15051
15052            Arrays.sort(uidArr);
15053        }
15054
15055        // Process packages with valid entries.
15056        if (isMounted) {
15057            if (DEBUG_SD_INSTALL)
15058                Log.i(TAG, "Loading packages");
15059            loadMediaPackages(processCids, uidArr);
15060            startCleaningPackages();
15061            mInstallerService.onSecureContainersAvailable();
15062        } else {
15063            if (DEBUG_SD_INSTALL)
15064                Log.i(TAG, "Unloading packages");
15065            unloadMediaPackages(processCids, uidArr, reportStatus);
15066        }
15067    }
15068
15069    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15070            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15071        final int size = infos.size();
15072        final String[] packageNames = new String[size];
15073        final int[] packageUids = new int[size];
15074        for (int i = 0; i < size; i++) {
15075            final ApplicationInfo info = infos.get(i);
15076            packageNames[i] = info.packageName;
15077            packageUids[i] = info.uid;
15078        }
15079        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15080                finishedReceiver);
15081    }
15082
15083    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15084            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15085        sendResourcesChangedBroadcast(mediaStatus, replacing,
15086                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15087    }
15088
15089    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15090            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15091        int size = pkgList.length;
15092        if (size > 0) {
15093            // Send broadcasts here
15094            Bundle extras = new Bundle();
15095            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15096            if (uidArr != null) {
15097                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15098            }
15099            if (replacing) {
15100                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15101            }
15102            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15103                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15104            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15105        }
15106    }
15107
15108   /*
15109     * Look at potentially valid container ids from processCids If package
15110     * information doesn't match the one on record or package scanning fails,
15111     * the cid is added to list of removeCids. We currently don't delete stale
15112     * containers.
15113     */
15114    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15115        ArrayList<String> pkgList = new ArrayList<String>();
15116        Set<AsecInstallArgs> keys = processCids.keySet();
15117
15118        for (AsecInstallArgs args : keys) {
15119            String codePath = processCids.get(args);
15120            if (DEBUG_SD_INSTALL)
15121                Log.i(TAG, "Loading container : " + args.cid);
15122            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15123            try {
15124                // Make sure there are no container errors first.
15125                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15126                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15127                            + " when installing from sdcard");
15128                    continue;
15129                }
15130                // Check code path here.
15131                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15132                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15133                            + " does not match one in settings " + codePath);
15134                    continue;
15135                }
15136                // Parse package
15137                int parseFlags = mDefParseFlags;
15138                if (args.isExternalAsec()) {
15139                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15140                }
15141                if (args.isFwdLocked()) {
15142                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15143                }
15144
15145                synchronized (mInstallLock) {
15146                    PackageParser.Package pkg = null;
15147                    try {
15148                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15149                    } catch (PackageManagerException e) {
15150                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15151                    }
15152                    // Scan the package
15153                    if (pkg != null) {
15154                        /*
15155                         * TODO why is the lock being held? doPostInstall is
15156                         * called in other places without the lock. This needs
15157                         * to be straightened out.
15158                         */
15159                        // writer
15160                        synchronized (mPackages) {
15161                            retCode = PackageManager.INSTALL_SUCCEEDED;
15162                            pkgList.add(pkg.packageName);
15163                            // Post process args
15164                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15165                                    pkg.applicationInfo.uid);
15166                        }
15167                    } else {
15168                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15169                    }
15170                }
15171
15172            } finally {
15173                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15174                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15175                }
15176            }
15177        }
15178        // writer
15179        synchronized (mPackages) {
15180            // If the platform SDK has changed since the last time we booted,
15181            // we need to re-grant app permission to catch any new ones that
15182            // appear. This is really a hack, and means that apps can in some
15183            // cases get permissions that the user didn't initially explicitly
15184            // allow... it would be nice to have some better way to handle
15185            // this situation.
15186            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15187            if (regrantPermissions)
15188                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15189                        + mSdkVersion + "; regranting permissions for external storage");
15190            mSettings.mExternalSdkPlatform = mSdkVersion;
15191
15192            // Make sure group IDs have been assigned, and any permission
15193            // changes in other apps are accounted for
15194            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15195                    | (regrantPermissions
15196                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15197                            : 0));
15198
15199            mSettings.updateExternalDatabaseVersion();
15200
15201            // can downgrade to reader
15202            // Persist settings
15203            mSettings.writeLPr();
15204        }
15205        // Send a broadcast to let everyone know we are done processing
15206        if (pkgList.size() > 0) {
15207            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15208        }
15209    }
15210
15211   /*
15212     * Utility method to unload a list of specified containers
15213     */
15214    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15215        // Just unmount all valid containers.
15216        for (AsecInstallArgs arg : cidArgs) {
15217            synchronized (mInstallLock) {
15218                arg.doPostDeleteLI(false);
15219           }
15220       }
15221   }
15222
15223    /*
15224     * Unload packages mounted on external media. This involves deleting package
15225     * data from internal structures, sending broadcasts about diabled packages,
15226     * gc'ing to free up references, unmounting all secure containers
15227     * corresponding to packages on external media, and posting a
15228     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15229     * that we always have to post this message if status has been requested no
15230     * matter what.
15231     */
15232    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15233            final boolean reportStatus) {
15234        if (DEBUG_SD_INSTALL)
15235            Log.i(TAG, "unloading media packages");
15236        ArrayList<String> pkgList = new ArrayList<String>();
15237        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15238        final Set<AsecInstallArgs> keys = processCids.keySet();
15239        for (AsecInstallArgs args : keys) {
15240            String pkgName = args.getPackageName();
15241            if (DEBUG_SD_INSTALL)
15242                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15243            // Delete package internally
15244            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15245            synchronized (mInstallLock) {
15246                boolean res = deletePackageLI(pkgName, null, false, null, null,
15247                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15248                if (res) {
15249                    pkgList.add(pkgName);
15250                } else {
15251                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15252                    failedList.add(args);
15253                }
15254            }
15255        }
15256
15257        // reader
15258        synchronized (mPackages) {
15259            // We didn't update the settings after removing each package;
15260            // write them now for all packages.
15261            mSettings.writeLPr();
15262        }
15263
15264        // We have to absolutely send UPDATED_MEDIA_STATUS only
15265        // after confirming that all the receivers processed the ordered
15266        // broadcast when packages get disabled, force a gc to clean things up.
15267        // and unload all the containers.
15268        if (pkgList.size() > 0) {
15269            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15270                    new IIntentReceiver.Stub() {
15271                public void performReceive(Intent intent, int resultCode, String data,
15272                        Bundle extras, boolean ordered, boolean sticky,
15273                        int sendingUser) throws RemoteException {
15274                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15275                            reportStatus ? 1 : 0, 1, keys);
15276                    mHandler.sendMessage(msg);
15277                }
15278            });
15279        } else {
15280            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15281                    keys);
15282            mHandler.sendMessage(msg);
15283        }
15284    }
15285
15286    private void loadPrivatePackages(VolumeInfo vol) {
15287        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15288        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15289        synchronized (mInstallLock) {
15290        synchronized (mPackages) {
15291            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15292            for (PackageSetting ps : packages) {
15293                final PackageParser.Package pkg;
15294                try {
15295                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15296                    loaded.add(pkg.applicationInfo);
15297                } catch (PackageManagerException e) {
15298                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15299                }
15300            }
15301
15302            // TODO: regrant any permissions that changed based since original install
15303
15304            mSettings.writeLPr();
15305        }
15306        }
15307
15308        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15309        sendResourcesChangedBroadcast(true, false, loaded, null);
15310    }
15311
15312    private void unloadPrivatePackages(VolumeInfo vol) {
15313        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15314        synchronized (mInstallLock) {
15315        synchronized (mPackages) {
15316            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15317            for (PackageSetting ps : packages) {
15318                if (ps.pkg == null) continue;
15319
15320                final ApplicationInfo info = ps.pkg.applicationInfo;
15321                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15322                if (deletePackageLI(ps.name, null, false, null, null,
15323                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15324                    unloaded.add(info);
15325                } else {
15326                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15327                }
15328            }
15329
15330            mSettings.writeLPr();
15331        }
15332        }
15333
15334        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15335        sendResourcesChangedBroadcast(false, false, unloaded, null);
15336    }
15337
15338    /**
15339     * Examine all users present on given mounted volume, and destroy data
15340     * belonging to users that are no longer valid, or whose user ID has been
15341     * recycled.
15342     */
15343    private void reconcileUsers(String volumeUuid) {
15344        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15345        if (ArrayUtils.isEmpty(files)) {
15346            Slog.d(TAG, "No users found on " + volumeUuid);
15347            return;
15348        }
15349
15350        for (File file : files) {
15351            if (!file.isDirectory()) continue;
15352
15353            final int userId;
15354            final UserInfo info;
15355            try {
15356                userId = Integer.parseInt(file.getName());
15357                info = sUserManager.getUserInfo(userId);
15358            } catch (NumberFormatException e) {
15359                Slog.w(TAG, "Invalid user directory " + file);
15360                continue;
15361            }
15362
15363            boolean destroyUser = false;
15364            if (info == null) {
15365                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15366                        + " because no matching user was found");
15367                destroyUser = true;
15368            } else {
15369                try {
15370                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15371                } catch (IOException e) {
15372                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15373                            + " because we failed to enforce serial number: " + e);
15374                    destroyUser = true;
15375                }
15376            }
15377
15378            if (destroyUser) {
15379                synchronized (mInstallLock) {
15380                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15381                }
15382            }
15383        }
15384
15385        final UserManager um = mContext.getSystemService(UserManager.class);
15386        for (UserInfo user : um.getUsers()) {
15387            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15388            if (userDir.exists()) continue;
15389
15390            try {
15391                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15392                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15393            } catch (IOException e) {
15394                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15395            }
15396        }
15397    }
15398
15399    /**
15400     * Examine all apps present on given mounted volume, and destroy apps that
15401     * aren't expected, either due to uninstallation or reinstallation on
15402     * another volume.
15403     */
15404    private void reconcileApps(String volumeUuid) {
15405        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15406        if (ArrayUtils.isEmpty(files)) {
15407            Slog.d(TAG, "No apps found on " + volumeUuid);
15408            return;
15409        }
15410
15411        for (File file : files) {
15412            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15413                    && !PackageInstallerService.isStageName(file.getName());
15414            if (!isPackage) {
15415                // Ignore entries which are not packages
15416                continue;
15417            }
15418
15419            boolean destroyApp = false;
15420            String packageName = null;
15421            try {
15422                final PackageLite pkg = PackageParser.parsePackageLite(file,
15423                        PackageParser.PARSE_MUST_BE_APK);
15424                packageName = pkg.packageName;
15425
15426                synchronized (mPackages) {
15427                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15428                    if (ps == null) {
15429                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15430                                + volumeUuid + " because we found no install record");
15431                        destroyApp = true;
15432                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15433                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15434                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15435                        destroyApp = true;
15436                    }
15437                }
15438
15439            } catch (PackageParserException e) {
15440                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15441                destroyApp = true;
15442            }
15443
15444            if (destroyApp) {
15445                synchronized (mInstallLock) {
15446                    if (packageName != null) {
15447                        removeDataDirsLI(volumeUuid, packageName);
15448                    }
15449                    if (file.isDirectory()) {
15450                        mInstaller.rmPackageDir(file.getAbsolutePath());
15451                    } else {
15452                        file.delete();
15453                    }
15454                }
15455            }
15456        }
15457    }
15458
15459    private void unfreezePackage(String packageName) {
15460        synchronized (mPackages) {
15461            final PackageSetting ps = mSettings.mPackages.get(packageName);
15462            if (ps != null) {
15463                ps.frozen = false;
15464            }
15465        }
15466    }
15467
15468    @Override
15469    public int movePackage(final String packageName, final String volumeUuid) {
15470        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15471
15472        final int moveId = mNextMoveId.getAndIncrement();
15473        try {
15474            movePackageInternal(packageName, volumeUuid, moveId);
15475        } catch (PackageManagerException e) {
15476            Slog.w(TAG, "Failed to move " + packageName, e);
15477            mMoveCallbacks.notifyStatusChanged(moveId,
15478                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15479        }
15480        return moveId;
15481    }
15482
15483    private void movePackageInternal(final String packageName, final String volumeUuid,
15484            final int moveId) throws PackageManagerException {
15485        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15486        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15487        final PackageManager pm = mContext.getPackageManager();
15488
15489        final boolean currentAsec;
15490        final String currentVolumeUuid;
15491        final File codeFile;
15492        final String installerPackageName;
15493        final String packageAbiOverride;
15494        final int appId;
15495        final String seinfo;
15496        final String label;
15497
15498        // reader
15499        synchronized (mPackages) {
15500            final PackageParser.Package pkg = mPackages.get(packageName);
15501            final PackageSetting ps = mSettings.mPackages.get(packageName);
15502            if (pkg == null || ps == null) {
15503                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15504            }
15505
15506            if (pkg.applicationInfo.isSystemApp()) {
15507                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15508                        "Cannot move system application");
15509            }
15510
15511            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15512                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15513                        "Package already moved to " + volumeUuid);
15514            }
15515
15516            final File probe = new File(pkg.codePath);
15517            final File probeOat = new File(probe, "oat");
15518            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15519                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15520                        "Move only supported for modern cluster style installs");
15521            }
15522
15523            if (ps.frozen) {
15524                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15525                        "Failed to move already frozen package");
15526            }
15527            ps.frozen = true;
15528
15529            currentAsec = pkg.applicationInfo.isForwardLocked()
15530                    || pkg.applicationInfo.isExternalAsec();
15531            currentVolumeUuid = ps.volumeUuid;
15532            codeFile = new File(pkg.codePath);
15533            installerPackageName = ps.installerPackageName;
15534            packageAbiOverride = ps.cpuAbiOverrideString;
15535            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15536            seinfo = pkg.applicationInfo.seinfo;
15537            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15538        }
15539
15540        // Now that we're guarded by frozen state, kill app during move
15541        killApplication(packageName, appId, "move pkg");
15542
15543        final Bundle extras = new Bundle();
15544        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15545        extras.putString(Intent.EXTRA_TITLE, label);
15546        mMoveCallbacks.notifyCreated(moveId, extras);
15547
15548        int installFlags;
15549        final boolean moveCompleteApp;
15550        final File measurePath;
15551
15552        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15553            installFlags = INSTALL_INTERNAL;
15554            moveCompleteApp = !currentAsec;
15555            measurePath = Environment.getDataAppDirectory(volumeUuid);
15556        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15557            installFlags = INSTALL_EXTERNAL;
15558            moveCompleteApp = false;
15559            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15560        } else {
15561            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15562            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15563                    || !volume.isMountedWritable()) {
15564                unfreezePackage(packageName);
15565                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15566                        "Move location not mounted private volume");
15567            }
15568
15569            Preconditions.checkState(!currentAsec);
15570
15571            installFlags = INSTALL_INTERNAL;
15572            moveCompleteApp = true;
15573            measurePath = Environment.getDataAppDirectory(volumeUuid);
15574        }
15575
15576        final PackageStats stats = new PackageStats(null, -1);
15577        synchronized (mInstaller) {
15578            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15579                unfreezePackage(packageName);
15580                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15581                        "Failed to measure package size");
15582            }
15583        }
15584
15585        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15586                + stats.dataSize);
15587
15588        final long startFreeBytes = measurePath.getFreeSpace();
15589        final long sizeBytes;
15590        if (moveCompleteApp) {
15591            sizeBytes = stats.codeSize + stats.dataSize;
15592        } else {
15593            sizeBytes = stats.codeSize;
15594        }
15595
15596        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15597            unfreezePackage(packageName);
15598            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15599                    "Not enough free space to move");
15600        }
15601
15602        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15603
15604        final CountDownLatch installedLatch = new CountDownLatch(1);
15605        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15606            @Override
15607            public void onUserActionRequired(Intent intent) throws RemoteException {
15608                throw new IllegalStateException();
15609            }
15610
15611            @Override
15612            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15613                    Bundle extras) throws RemoteException {
15614                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15615                        + PackageManager.installStatusToString(returnCode, msg));
15616
15617                installedLatch.countDown();
15618
15619                // Regardless of success or failure of the move operation,
15620                // always unfreeze the package
15621                unfreezePackage(packageName);
15622
15623                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15624                switch (status) {
15625                    case PackageInstaller.STATUS_SUCCESS:
15626                        mMoveCallbacks.notifyStatusChanged(moveId,
15627                                PackageManager.MOVE_SUCCEEDED);
15628                        break;
15629                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15630                        mMoveCallbacks.notifyStatusChanged(moveId,
15631                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15632                        break;
15633                    default:
15634                        mMoveCallbacks.notifyStatusChanged(moveId,
15635                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15636                        break;
15637                }
15638            }
15639        };
15640
15641        final MoveInfo move;
15642        if (moveCompleteApp) {
15643            // Kick off a thread to report progress estimates
15644            new Thread() {
15645                @Override
15646                public void run() {
15647                    while (true) {
15648                        try {
15649                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15650                                break;
15651                            }
15652                        } catch (InterruptedException ignored) {
15653                        }
15654
15655                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15656                        final int progress = 10 + (int) MathUtils.constrain(
15657                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15658                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15659                    }
15660                }
15661            }.start();
15662
15663            final String dataAppName = codeFile.getName();
15664            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15665                    dataAppName, appId, seinfo);
15666        } else {
15667            move = null;
15668        }
15669
15670        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15671
15672        final Message msg = mHandler.obtainMessage(INIT_COPY);
15673        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15674        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15675                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15676        mHandler.sendMessage(msg);
15677    }
15678
15679    @Override
15680    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15681        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15682
15683        final int realMoveId = mNextMoveId.getAndIncrement();
15684        final Bundle extras = new Bundle();
15685        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15686        mMoveCallbacks.notifyCreated(realMoveId, extras);
15687
15688        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15689            @Override
15690            public void onCreated(int moveId, Bundle extras) {
15691                // Ignored
15692            }
15693
15694            @Override
15695            public void onStatusChanged(int moveId, int status, long estMillis) {
15696                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15697            }
15698        };
15699
15700        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15701        storage.setPrimaryStorageUuid(volumeUuid, callback);
15702        return realMoveId;
15703    }
15704
15705    @Override
15706    public int getMoveStatus(int moveId) {
15707        mContext.enforceCallingOrSelfPermission(
15708                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15709        return mMoveCallbacks.mLastStatus.get(moveId);
15710    }
15711
15712    @Override
15713    public void registerMoveCallback(IPackageMoveObserver callback) {
15714        mContext.enforceCallingOrSelfPermission(
15715                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15716        mMoveCallbacks.register(callback);
15717    }
15718
15719    @Override
15720    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15721        mContext.enforceCallingOrSelfPermission(
15722                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15723        mMoveCallbacks.unregister(callback);
15724    }
15725
15726    @Override
15727    public boolean setInstallLocation(int loc) {
15728        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15729                null);
15730        if (getInstallLocation() == loc) {
15731            return true;
15732        }
15733        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15734                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15735            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15736                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15737            return true;
15738        }
15739        return false;
15740   }
15741
15742    @Override
15743    public int getInstallLocation() {
15744        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15745                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15746                PackageHelper.APP_INSTALL_AUTO);
15747    }
15748
15749    /** Called by UserManagerService */
15750    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15751        mDirtyUsers.remove(userHandle);
15752        mSettings.removeUserLPw(userHandle);
15753        mPendingBroadcasts.remove(userHandle);
15754        if (mInstaller != null) {
15755            // Technically, we shouldn't be doing this with the package lock
15756            // held.  However, this is very rare, and there is already so much
15757            // other disk I/O going on, that we'll let it slide for now.
15758            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15759            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15760                final String volumeUuid = vol.getFsUuid();
15761                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15762                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15763            }
15764        }
15765        mUserNeedsBadging.delete(userHandle);
15766        removeUnusedPackagesLILPw(userManager, userHandle);
15767    }
15768
15769    /**
15770     * We're removing userHandle and would like to remove any downloaded packages
15771     * that are no longer in use by any other user.
15772     * @param userHandle the user being removed
15773     */
15774    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15775        final boolean DEBUG_CLEAN_APKS = false;
15776        int [] users = userManager.getUserIdsLPr();
15777        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15778        while (psit.hasNext()) {
15779            PackageSetting ps = psit.next();
15780            if (ps.pkg == null) {
15781                continue;
15782            }
15783            final String packageName = ps.pkg.packageName;
15784            // Skip over if system app
15785            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15786                continue;
15787            }
15788            if (DEBUG_CLEAN_APKS) {
15789                Slog.i(TAG, "Checking package " + packageName);
15790            }
15791            boolean keep = false;
15792            for (int i = 0; i < users.length; i++) {
15793                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15794                    keep = true;
15795                    if (DEBUG_CLEAN_APKS) {
15796                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15797                                + users[i]);
15798                    }
15799                    break;
15800                }
15801            }
15802            if (!keep) {
15803                if (DEBUG_CLEAN_APKS) {
15804                    Slog.i(TAG, "  Removing package " + packageName);
15805                }
15806                mHandler.post(new Runnable() {
15807                    public void run() {
15808                        deletePackageX(packageName, userHandle, 0);
15809                    } //end run
15810                });
15811            }
15812        }
15813    }
15814
15815    /** Called by UserManagerService */
15816    void createNewUserLILPw(int userHandle) {
15817        if (mInstaller != null) {
15818            mInstaller.createUserConfig(userHandle);
15819            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15820            applyFactoryDefaultBrowserLPw(userHandle);
15821        }
15822    }
15823
15824    void newUserCreatedLILPw(final int userHandle) {
15825        // We cannot grant the default permissions with a lock held as
15826        // we query providers from other components for default handlers
15827        // such as enabled IMEs, etc.
15828        mHandler.post(new Runnable() {
15829            @Override
15830            public void run() {
15831                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15832            }
15833        });
15834    }
15835
15836    @Override
15837    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15838        mContext.enforceCallingOrSelfPermission(
15839                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15840                "Only package verification agents can read the verifier device identity");
15841
15842        synchronized (mPackages) {
15843            return mSettings.getVerifierDeviceIdentityLPw();
15844        }
15845    }
15846
15847    @Override
15848    public void setPermissionEnforced(String permission, boolean enforced) {
15849        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15850        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15851            synchronized (mPackages) {
15852                if (mSettings.mReadExternalStorageEnforced == null
15853                        || mSettings.mReadExternalStorageEnforced != enforced) {
15854                    mSettings.mReadExternalStorageEnforced = enforced;
15855                    mSettings.writeLPr();
15856                }
15857            }
15858            // kill any non-foreground processes so we restart them and
15859            // grant/revoke the GID.
15860            final IActivityManager am = ActivityManagerNative.getDefault();
15861            if (am != null) {
15862                final long token = Binder.clearCallingIdentity();
15863                try {
15864                    am.killProcessesBelowForeground("setPermissionEnforcement");
15865                } catch (RemoteException e) {
15866                } finally {
15867                    Binder.restoreCallingIdentity(token);
15868                }
15869            }
15870        } else {
15871            throw new IllegalArgumentException("No selective enforcement for " + permission);
15872        }
15873    }
15874
15875    @Override
15876    @Deprecated
15877    public boolean isPermissionEnforced(String permission) {
15878        return true;
15879    }
15880
15881    @Override
15882    public boolean isStorageLow() {
15883        final long token = Binder.clearCallingIdentity();
15884        try {
15885            final DeviceStorageMonitorInternal
15886                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15887            if (dsm != null) {
15888                return dsm.isMemoryLow();
15889            } else {
15890                return false;
15891            }
15892        } finally {
15893            Binder.restoreCallingIdentity(token);
15894        }
15895    }
15896
15897    @Override
15898    public IPackageInstaller getPackageInstaller() {
15899        return mInstallerService;
15900    }
15901
15902    private boolean userNeedsBadging(int userId) {
15903        int index = mUserNeedsBadging.indexOfKey(userId);
15904        if (index < 0) {
15905            final UserInfo userInfo;
15906            final long token = Binder.clearCallingIdentity();
15907            try {
15908                userInfo = sUserManager.getUserInfo(userId);
15909            } finally {
15910                Binder.restoreCallingIdentity(token);
15911            }
15912            final boolean b;
15913            if (userInfo != null && userInfo.isManagedProfile()) {
15914                b = true;
15915            } else {
15916                b = false;
15917            }
15918            mUserNeedsBadging.put(userId, b);
15919            return b;
15920        }
15921        return mUserNeedsBadging.valueAt(index);
15922    }
15923
15924    @Override
15925    public KeySet getKeySetByAlias(String packageName, String alias) {
15926        if (packageName == null || alias == null) {
15927            return null;
15928        }
15929        synchronized(mPackages) {
15930            final PackageParser.Package pkg = mPackages.get(packageName);
15931            if (pkg == null) {
15932                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15933                throw new IllegalArgumentException("Unknown package: " + packageName);
15934            }
15935            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15936            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15937        }
15938    }
15939
15940    @Override
15941    public KeySet getSigningKeySet(String packageName) {
15942        if (packageName == null) {
15943            return null;
15944        }
15945        synchronized(mPackages) {
15946            final PackageParser.Package pkg = mPackages.get(packageName);
15947            if (pkg == null) {
15948                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15949                throw new IllegalArgumentException("Unknown package: " + packageName);
15950            }
15951            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15952                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15953                throw new SecurityException("May not access signing KeySet of other apps.");
15954            }
15955            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15956            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15957        }
15958    }
15959
15960    @Override
15961    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15962        if (packageName == null || ks == null) {
15963            return false;
15964        }
15965        synchronized(mPackages) {
15966            final PackageParser.Package pkg = mPackages.get(packageName);
15967            if (pkg == null) {
15968                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15969                throw new IllegalArgumentException("Unknown package: " + packageName);
15970            }
15971            IBinder ksh = ks.getToken();
15972            if (ksh instanceof KeySetHandle) {
15973                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15974                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15975            }
15976            return false;
15977        }
15978    }
15979
15980    @Override
15981    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15982        if (packageName == null || ks == null) {
15983            return false;
15984        }
15985        synchronized(mPackages) {
15986            final PackageParser.Package pkg = mPackages.get(packageName);
15987            if (pkg == null) {
15988                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15989                throw new IllegalArgumentException("Unknown package: " + packageName);
15990            }
15991            IBinder ksh = ks.getToken();
15992            if (ksh instanceof KeySetHandle) {
15993                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15994                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15995            }
15996            return false;
15997        }
15998    }
15999
16000    public void getUsageStatsIfNoPackageUsageInfo() {
16001        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16002            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16003            if (usm == null) {
16004                throw new IllegalStateException("UsageStatsManager must be initialized");
16005            }
16006            long now = System.currentTimeMillis();
16007            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16008            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16009                String packageName = entry.getKey();
16010                PackageParser.Package pkg = mPackages.get(packageName);
16011                if (pkg == null) {
16012                    continue;
16013                }
16014                UsageStats usage = entry.getValue();
16015                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16016                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16017            }
16018        }
16019    }
16020
16021    /**
16022     * Check and throw if the given before/after packages would be considered a
16023     * downgrade.
16024     */
16025    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16026            throws PackageManagerException {
16027        if (after.versionCode < before.mVersionCode) {
16028            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16029                    "Update version code " + after.versionCode + " is older than current "
16030                    + before.mVersionCode);
16031        } else if (after.versionCode == before.mVersionCode) {
16032            if (after.baseRevisionCode < before.baseRevisionCode) {
16033                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16034                        "Update base revision code " + after.baseRevisionCode
16035                        + " is older than current " + before.baseRevisionCode);
16036            }
16037
16038            if (!ArrayUtils.isEmpty(after.splitNames)) {
16039                for (int i = 0; i < after.splitNames.length; i++) {
16040                    final String splitName = after.splitNames[i];
16041                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16042                    if (j != -1) {
16043                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16044                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16045                                    "Update split " + splitName + " revision code "
16046                                    + after.splitRevisionCodes[i] + " is older than current "
16047                                    + before.splitRevisionCodes[j]);
16048                        }
16049                    }
16050                }
16051            }
16052        }
16053    }
16054
16055    private static class MoveCallbacks extends Handler {
16056        private static final int MSG_CREATED = 1;
16057        private static final int MSG_STATUS_CHANGED = 2;
16058
16059        private final RemoteCallbackList<IPackageMoveObserver>
16060                mCallbacks = new RemoteCallbackList<>();
16061
16062        private final SparseIntArray mLastStatus = new SparseIntArray();
16063
16064        public MoveCallbacks(Looper looper) {
16065            super(looper);
16066        }
16067
16068        public void register(IPackageMoveObserver callback) {
16069            mCallbacks.register(callback);
16070        }
16071
16072        public void unregister(IPackageMoveObserver callback) {
16073            mCallbacks.unregister(callback);
16074        }
16075
16076        @Override
16077        public void handleMessage(Message msg) {
16078            final SomeArgs args = (SomeArgs) msg.obj;
16079            final int n = mCallbacks.beginBroadcast();
16080            for (int i = 0; i < n; i++) {
16081                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16082                try {
16083                    invokeCallback(callback, msg.what, args);
16084                } catch (RemoteException ignored) {
16085                }
16086            }
16087            mCallbacks.finishBroadcast();
16088            args.recycle();
16089        }
16090
16091        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16092                throws RemoteException {
16093            switch (what) {
16094                case MSG_CREATED: {
16095                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16096                    break;
16097                }
16098                case MSG_STATUS_CHANGED: {
16099                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16100                    break;
16101                }
16102            }
16103        }
16104
16105        private void notifyCreated(int moveId, Bundle extras) {
16106            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16107
16108            final SomeArgs args = SomeArgs.obtain();
16109            args.argi1 = moveId;
16110            args.arg2 = extras;
16111            obtainMessage(MSG_CREATED, args).sendToTarget();
16112        }
16113
16114        private void notifyStatusChanged(int moveId, int status) {
16115            notifyStatusChanged(moveId, status, -1);
16116        }
16117
16118        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16119            Slog.v(TAG, "Move " + moveId + " status " + status);
16120
16121            final SomeArgs args = SomeArgs.obtain();
16122            args.argi1 = moveId;
16123            args.argi2 = status;
16124            args.arg3 = estMillis;
16125            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16126
16127            synchronized (mLastStatus) {
16128                mLastStatus.put(moveId, status);
16129            }
16130        }
16131    }
16132
16133    private final class OnPermissionChangeListeners extends Handler {
16134        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16135
16136        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16137                new RemoteCallbackList<>();
16138
16139        public OnPermissionChangeListeners(Looper looper) {
16140            super(looper);
16141        }
16142
16143        @Override
16144        public void handleMessage(Message msg) {
16145            switch (msg.what) {
16146                case MSG_ON_PERMISSIONS_CHANGED: {
16147                    final int uid = msg.arg1;
16148                    handleOnPermissionsChanged(uid);
16149                } break;
16150            }
16151        }
16152
16153        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16154            mPermissionListeners.register(listener);
16155
16156        }
16157
16158        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16159            mPermissionListeners.unregister(listener);
16160        }
16161
16162        public void onPermissionsChanged(int uid) {
16163            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16164                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16165            }
16166        }
16167
16168        private void handleOnPermissionsChanged(int uid) {
16169            final int count = mPermissionListeners.beginBroadcast();
16170            try {
16171                for (int i = 0; i < count; i++) {
16172                    IOnPermissionsChangeListener callback = mPermissionListeners
16173                            .getBroadcastItem(i);
16174                    try {
16175                        callback.onPermissionsChanged(uid);
16176                    } catch (RemoteException e) {
16177                        Log.e(TAG, "Permission listener is dead", e);
16178                    }
16179                }
16180            } finally {
16181                mPermissionListeners.finishBroadcast();
16182            }
16183        }
16184    }
16185
16186    private class PackageManagerInternalImpl extends PackageManagerInternal {
16187        @Override
16188        public void setLocationPackagesProvider(PackagesProvider provider) {
16189            synchronized (mPackages) {
16190                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16191            }
16192        }
16193
16194        @Override
16195        public void setImePackagesProvider(PackagesProvider provider) {
16196            synchronized (mPackages) {
16197                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16198            }
16199        }
16200
16201        @Override
16202        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16203            synchronized (mPackages) {
16204                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16205            }
16206        }
16207
16208        @Override
16209        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16210            synchronized (mPackages) {
16211                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16212            }
16213        }
16214
16215        @Override
16216        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16217            synchronized (mPackages) {
16218                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16219            }
16220        }
16221
16222        @Override
16223        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16224            synchronized (mPackages) {
16225                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16226            }
16227        }
16228
16229        @Override
16230        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16231            synchronized (mPackages) {
16232                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16233                        packageName, userId);
16234            }
16235        }
16236
16237        @Override
16238        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16239            synchronized (mPackages) {
16240                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16241                        packageName, userId);
16242            }
16243        }
16244    }
16245
16246    @Override
16247    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16248        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16249        synchronized (mPackages) {
16250            final long identity = Binder.clearCallingIdentity();
16251            try {
16252                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16253                        packageNames, userId);
16254            } finally {
16255                Binder.restoreCallingIdentity(identity);
16256            }
16257        }
16258    }
16259
16260    private static void enforceSystemOrPhoneCaller(String tag) {
16261        int callingUid = Binder.getCallingUid();
16262        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16263            throw new SecurityException(
16264                    "Cannot call " + tag + " from UID " + callingUid);
16265        }
16266    }
16267}
16268