PackageManagerService.java revision 5e181938c4de87e9535e8295a8dbf06f99631834
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Binder;
147import android.os.Build;
148import android.os.Bundle;
149import android.os.Debug;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.StorageEventListener;
170import android.os.storage.StorageManager;
171import android.os.storage.VolumeInfo;
172import android.os.storage.VolumeRecord;
173import android.security.KeyStore;
174import android.security.SystemKeyStore;
175import android.system.ErrnoException;
176import android.system.Os;
177import android.system.StructStat;
178import android.text.TextUtils;
179import android.text.format.DateUtils;
180import android.util.ArrayMap;
181import android.util.ArraySet;
182import android.util.AtomicFile;
183import android.util.DisplayMetrics;
184import android.util.EventLog;
185import android.util.ExceptionUtils;
186import android.util.Log;
187import android.util.LogPrinter;
188import android.util.MathUtils;
189import android.util.PrintStreamPrinter;
190import android.util.Slog;
191import android.util.SparseArray;
192import android.util.SparseBooleanArray;
193import android.util.SparseIntArray;
194import android.util.Xml;
195import android.view.Display;
196
197import dalvik.system.DexFile;
198import dalvik.system.VMRuntime;
199
200import libcore.io.IoUtils;
201import libcore.util.EmptyArray;
202
203import com.android.internal.R;
204import com.android.internal.annotations.GuardedBy;
205import com.android.internal.app.IMediaContainerService;
206import com.android.internal.app.ResolverActivity;
207import com.android.internal.content.NativeLibraryHelper;
208import com.android.internal.content.PackageHelper;
209import com.android.internal.os.IParcelFileDescriptorFactory;
210import com.android.internal.os.SomeArgs;
211import com.android.internal.os.Zygote;
212import com.android.internal.util.ArrayUtils;
213import com.android.internal.util.FastPrintWriter;
214import com.android.internal.util.FastXmlSerializer;
215import com.android.internal.util.IndentingPrintWriter;
216import com.android.internal.util.Preconditions;
217import com.android.server.EventLogTags;
218import com.android.server.FgThread;
219import com.android.server.IntentResolver;
220import com.android.server.LocalServices;
221import com.android.server.ServiceThread;
222import com.android.server.SystemConfig;
223import com.android.server.Watchdog;
224import com.android.server.pm.PermissionsState.PermissionState;
225import com.android.server.pm.Settings.DatabaseVersion;
226import com.android.server.storage.DeviceStorageMonitorInternal;
227
228import org.xmlpull.v1.XmlPullParser;
229import org.xmlpull.v1.XmlPullParserException;
230import org.xmlpull.v1.XmlSerializer;
231
232import java.io.BufferedInputStream;
233import java.io.BufferedOutputStream;
234import java.io.BufferedReader;
235import java.io.ByteArrayInputStream;
236import java.io.ByteArrayOutputStream;
237import java.io.File;
238import java.io.FileDescriptor;
239import java.io.FileNotFoundException;
240import java.io.FileOutputStream;
241import java.io.FileReader;
242import java.io.FilenameFilter;
243import java.io.IOException;
244import java.io.InputStream;
245import java.io.PrintWriter;
246import java.nio.charset.StandardCharsets;
247import java.security.NoSuchAlgorithmException;
248import java.security.PublicKey;
249import java.security.cert.CertificateEncodingException;
250import java.security.cert.CertificateException;
251import java.text.SimpleDateFormat;
252import java.util.ArrayList;
253import java.util.Arrays;
254import java.util.Collection;
255import java.util.Collections;
256import java.util.Comparator;
257import java.util.Date;
258import java.util.Iterator;
259import java.util.List;
260import java.util.Map;
261import java.util.Objects;
262import java.util.Set;
263import java.util.concurrent.CountDownLatch;
264import java.util.concurrent.TimeUnit;
265import java.util.concurrent.atomic.AtomicBoolean;
266import java.util.concurrent.atomic.AtomicInteger;
267import java.util.concurrent.atomic.AtomicLong;
268
269/**
270 * Keep track of all those .apks everywhere.
271 *
272 * This is very central to the platform's security; please run the unit
273 * tests whenever making modifications here:
274 *
275runtest -c android.content.pm.PackageManagerTests frameworks-core
276 *
277 * {@hide}
278 */
279public class PackageManagerService extends IPackageManager.Stub {
280    static final String TAG = "PackageManager";
281    static final boolean DEBUG_SETTINGS = false;
282    static final boolean DEBUG_PREFERRED = false;
283    static final boolean DEBUG_UPGRADE = false;
284    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
285    private static final boolean DEBUG_BACKUP = true;
286    private static final boolean DEBUG_INSTALL = false;
287    private static final boolean DEBUG_REMOVE = false;
288    private static final boolean DEBUG_BROADCASTS = false;
289    private static final boolean DEBUG_SHOW_INFO = false;
290    private static final boolean DEBUG_PACKAGE_INFO = false;
291    private static final boolean DEBUG_INTENT_MATCHING = false;
292    private static final boolean DEBUG_PACKAGE_SCANNING = false;
293    private static final boolean DEBUG_VERIFY = false;
294    private static final boolean DEBUG_DEXOPT = false;
295    private static final boolean DEBUG_ABI_SELECTION = false;
296
297    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
298
299    private static final int RADIO_UID = Process.PHONE_UID;
300    private static final int LOG_UID = Process.LOG_UID;
301    private static final int NFC_UID = Process.NFC_UID;
302    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
303    private static final int SHELL_UID = Process.SHELL_UID;
304
305    // Cap the size of permission trees that 3rd party apps can define
306    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
307
308    // Suffix used during package installation when copying/moving
309    // package apks to install directory.
310    private static final String INSTALL_PACKAGE_SUFFIX = "-";
311
312    static final int SCAN_NO_DEX = 1<<1;
313    static final int SCAN_FORCE_DEX = 1<<2;
314    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
315    static final int SCAN_NEW_INSTALL = 1<<4;
316    static final int SCAN_NO_PATHS = 1<<5;
317    static final int SCAN_UPDATE_TIME = 1<<6;
318    static final int SCAN_DEFER_DEX = 1<<7;
319    static final int SCAN_BOOTING = 1<<8;
320    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
321    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
322    static final int SCAN_REQUIRE_KNOWN = 1<<12;
323    static final int SCAN_MOVE = 1<<13;
324    static final int SCAN_INITIAL = 1<<14;
325
326    static final int REMOVE_CHATTY = 1<<16;
327
328    private static final int[] EMPTY_INT_ARRAY = new int[0];
329
330    /**
331     * Timeout (in milliseconds) after which the watchdog should declare that
332     * our handler thread is wedged.  The usual default for such things is one
333     * minute but we sometimes do very lengthy I/O operations on this thread,
334     * such as installing multi-gigabyte applications, so ours needs to be longer.
335     */
336    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
337
338    /**
339     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
340     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
341     * settings entry if available, otherwise we use the hardcoded default.  If it's been
342     * more than this long since the last fstrim, we force one during the boot sequence.
343     *
344     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
345     * one gets run at the next available charging+idle time.  This final mandatory
346     * no-fstrim check kicks in only of the other scheduling criteria is never met.
347     */
348    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
349
350    /**
351     * Whether verification is enabled by default.
352     */
353    private static final boolean DEFAULT_VERIFY_ENABLE = true;
354
355    /**
356     * The default maximum time to wait for the verification agent to return in
357     * milliseconds.
358     */
359    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
360
361    /**
362     * The default response for package verification timeout.
363     *
364     * This can be either PackageManager.VERIFICATION_ALLOW or
365     * PackageManager.VERIFICATION_REJECT.
366     */
367    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
368
369    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
370
371    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
372            DEFAULT_CONTAINER_PACKAGE,
373            "com.android.defcontainer.DefaultContainerService");
374
375    private static final String KILL_APP_REASON_GIDS_CHANGED =
376            "permission grant or revoke changed gids";
377
378    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
379            "permissions revoked";
380
381    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
382
383    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
384
385    /** Permission grant: not grant the permission. */
386    private static final int GRANT_DENIED = 1;
387
388    /** Permission grant: grant the permission as an install permission. */
389    private static final int GRANT_INSTALL = 2;
390
391    /** Permission grant: grant the permission as an install permission for a legacy app. */
392    private static final int GRANT_INSTALL_LEGACY = 3;
393
394    /** Permission grant: grant the permission as a runtime one. */
395    private static final int GRANT_RUNTIME = 4;
396
397    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
398    private static final int GRANT_UPGRADE = 5;
399
400    /** Canonical intent used to identify what counts as a "web browser" app */
401    private static final Intent sBrowserIntent;
402    static {
403        sBrowserIntent = new Intent();
404        sBrowserIntent.setAction(Intent.ACTION_VIEW);
405        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
406        sBrowserIntent.setData(Uri.parse("http:"));
407    }
408
409    final ServiceThread mHandlerThread;
410
411    final PackageHandler mHandler;
412
413    /**
414     * Messages for {@link #mHandler} that need to wait for system ready before
415     * being dispatched.
416     */
417    private ArrayList<Message> mPostSystemReadyMessages;
418
419    final int mSdkVersion = Build.VERSION.SDK_INT;
420
421    final Context mContext;
422    final boolean mFactoryTest;
423    final boolean mOnlyCore;
424    final boolean mLazyDexOpt;
425    final long mDexOptLRUThresholdInMills;
426    final DisplayMetrics mMetrics;
427    final int mDefParseFlags;
428    final String[] mSeparateProcesses;
429    final boolean mIsUpgrade;
430
431    // This is where all application persistent data goes.
432    final File mAppDataDir;
433
434    // This is where all application persistent data goes for secondary users.
435    final File mUserAppDataDir;
436
437    /** The location for ASEC container files on internal storage. */
438    final String mAsecInternalPath;
439
440    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
441    // LOCK HELD.  Can be called with mInstallLock held.
442    @GuardedBy("mInstallLock")
443    final Installer mInstaller;
444
445    /** Directory where installed third-party apps stored */
446    final File mAppInstallDir;
447
448    /**
449     * Directory to which applications installed internally have their
450     * 32 bit native libraries copied.
451     */
452    private File mAppLib32InstallDir;
453
454    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
455    // apps.
456    final File mDrmAppPrivateInstallDir;
457
458    // ----------------------------------------------------------------
459
460    // Lock for state used when installing and doing other long running
461    // operations.  Methods that must be called with this lock held have
462    // the suffix "LI".
463    final Object mInstallLock = new Object();
464
465    // ----------------------------------------------------------------
466
467    // Keys are String (package name), values are Package.  This also serves
468    // as the lock for the global state.  Methods that must be called with
469    // this lock held have the prefix "LP".
470    @GuardedBy("mPackages")
471    final ArrayMap<String, PackageParser.Package> mPackages =
472            new ArrayMap<String, PackageParser.Package>();
473
474    // Tracks available target package names -> overlay package paths.
475    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
476        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
477
478    /**
479     * Tracks new system packages [receiving in an OTA] that we expect to
480     * find updated user-installed versions. Keys are package name, values
481     * are package location.
482     */
483    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
484
485    final Settings mSettings;
486    boolean mRestoredSettings;
487
488    // System configuration read by SystemConfig.
489    final int[] mGlobalGids;
490    final SparseArray<ArraySet<String>> mSystemPermissions;
491    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
492
493    // If mac_permissions.xml was found for seinfo labeling.
494    boolean mFoundPolicyFile;
495
496    // If a recursive restorecon of /data/data/<pkg> is needed.
497    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
498
499    public static final class SharedLibraryEntry {
500        public final String path;
501        public final String apk;
502
503        SharedLibraryEntry(String _path, String _apk) {
504            path = _path;
505            apk = _apk;
506        }
507    }
508
509    // Currently known shared libraries.
510    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
511            new ArrayMap<String, SharedLibraryEntry>();
512
513    // All available activities, for your resolving pleasure.
514    final ActivityIntentResolver mActivities =
515            new ActivityIntentResolver();
516
517    // All available receivers, for your resolving pleasure.
518    final ActivityIntentResolver mReceivers =
519            new ActivityIntentResolver();
520
521    // All available services, for your resolving pleasure.
522    final ServiceIntentResolver mServices = new ServiceIntentResolver();
523
524    // All available providers, for your resolving pleasure.
525    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
526
527    // Mapping from provider base names (first directory in content URI codePath)
528    // to the provider information.
529    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
530            new ArrayMap<String, PackageParser.Provider>();
531
532    // Mapping from instrumentation class names to info about them.
533    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
534            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
535
536    // Mapping from permission names to info about them.
537    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
538            new ArrayMap<String, PackageParser.PermissionGroup>();
539
540    // Packages whose data we have transfered into another package, thus
541    // should no longer exist.
542    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
543
544    // Broadcast actions that are only available to the system.
545    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
546
547    /** List of packages waiting for verification. */
548    final SparseArray<PackageVerificationState> mPendingVerification
549            = new SparseArray<PackageVerificationState>();
550
551    /** Set of packages associated with each app op permission. */
552    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
553
554    final PackageInstallerService mInstallerService;
555
556    private final PackageDexOptimizer mPackageDexOptimizer;
557
558    private AtomicInteger mNextMoveId = new AtomicInteger();
559    private final MoveCallbacks mMoveCallbacks;
560
561    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
562
563    // Cache of users who need badging.
564    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
565
566    /** Token for keys in mPendingVerification. */
567    private int mPendingVerificationToken = 0;
568
569    volatile boolean mSystemReady;
570    volatile boolean mSafeMode;
571    volatile boolean mHasSystemUidErrors;
572
573    ApplicationInfo mAndroidApplication;
574    final ActivityInfo mResolveActivity = new ActivityInfo();
575    final ResolveInfo mResolveInfo = new ResolveInfo();
576    ComponentName mResolveComponentName;
577    PackageParser.Package mPlatformPackage;
578    ComponentName mCustomResolverComponentName;
579
580    boolean mResolverReplaced = false;
581
582    private final ComponentName mIntentFilterVerifierComponent;
583    private int mIntentFilterVerificationToken = 0;
584
585    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
586            = new SparseArray<IntentFilterVerificationState>();
587
588    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
589            new DefaultPermissionGrantPolicy(this);
590
591    private static class IFVerificationParams {
592        PackageParser.Package pkg;
593        boolean replacing;
594        int userId;
595        int verifierUid;
596
597        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
598                int _userId, int _verifierUid) {
599            pkg = _pkg;
600            replacing = _replacing;
601            userId = _userId;
602            replacing = _replacing;
603            verifierUid = _verifierUid;
604        }
605    }
606
607    private interface IntentFilterVerifier<T extends IntentFilter> {
608        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
609                                               T filter, String packageName);
610        void startVerifications(int userId);
611        void receiveVerificationResponse(int verificationId);
612    }
613
614    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
615        private Context mContext;
616        private ComponentName mIntentFilterVerifierComponent;
617        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
618
619        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
620            mContext = context;
621            mIntentFilterVerifierComponent = verifierComponent;
622        }
623
624        private String getDefaultScheme() {
625            return IntentFilter.SCHEME_HTTPS;
626        }
627
628        @Override
629        public void startVerifications(int userId) {
630            // Launch verifications requests
631            int count = mCurrentIntentFilterVerifications.size();
632            for (int n=0; n<count; n++) {
633                int verificationId = mCurrentIntentFilterVerifications.get(n);
634                final IntentFilterVerificationState ivs =
635                        mIntentFilterVerificationStates.get(verificationId);
636
637                String packageName = ivs.getPackageName();
638
639                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
640                final int filterCount = filters.size();
641                ArraySet<String> domainsSet = new ArraySet<>();
642                for (int m=0; m<filterCount; m++) {
643                    PackageParser.ActivityIntentInfo filter = filters.get(m);
644                    domainsSet.addAll(filter.getHostsList());
645                }
646                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
647                synchronized (mPackages) {
648                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
649                            packageName, domainsList) != null) {
650                        scheduleWriteSettingsLocked();
651                    }
652                }
653                sendVerificationRequest(userId, verificationId, ivs);
654            }
655            mCurrentIntentFilterVerifications.clear();
656        }
657
658        private void sendVerificationRequest(int userId, int verificationId,
659                IntentFilterVerificationState ivs) {
660
661            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
662            verificationIntent.putExtra(
663                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
664                    verificationId);
665            verificationIntent.putExtra(
666                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
667                    getDefaultScheme());
668            verificationIntent.putExtra(
669                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
670                    ivs.getHostsString());
671            verificationIntent.putExtra(
672                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
673                    ivs.getPackageName());
674            verificationIntent.setComponent(mIntentFilterVerifierComponent);
675            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
676
677            UserHandle user = new UserHandle(userId);
678            mContext.sendBroadcastAsUser(verificationIntent, user);
679            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
680                    "Sending IntentFilter verification broadcast");
681        }
682
683        public void receiveVerificationResponse(int verificationId) {
684            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
685
686            final boolean verified = ivs.isVerified();
687
688            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
689            final int count = filters.size();
690            if (DEBUG_DOMAIN_VERIFICATION) {
691                Slog.i(TAG, "Received verification response " + verificationId
692                        + " for " + count + " filters, verified=" + verified);
693            }
694            for (int n=0; n<count; n++) {
695                PackageParser.ActivityIntentInfo filter = filters.get(n);
696                filter.setVerified(verified);
697
698                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
699                        + " verified with result:" + verified + " and hosts:"
700                        + ivs.getHostsString());
701            }
702
703            mIntentFilterVerificationStates.remove(verificationId);
704
705            final String packageName = ivs.getPackageName();
706            IntentFilterVerificationInfo ivi = null;
707
708            synchronized (mPackages) {
709                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
710            }
711            if (ivi == null) {
712                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
713                        + verificationId + " packageName:" + packageName);
714                return;
715            }
716            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
717                    "Updating IntentFilterVerificationInfo for package " + packageName
718                            +" verificationId:" + verificationId);
719
720            synchronized (mPackages) {
721                if (verified) {
722                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
723                } else {
724                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
725                }
726                scheduleWriteSettingsLocked();
727
728                final int userId = ivs.getUserId();
729                if (userId != UserHandle.USER_ALL) {
730                    final int userStatus =
731                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
732
733                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
734                    boolean needUpdate = false;
735
736                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
737                    // already been set by the User thru the Disambiguation dialog
738                    switch (userStatus) {
739                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
740                            if (verified) {
741                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
742                            } else {
743                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
744                            }
745                            needUpdate = true;
746                            break;
747
748                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
749                            if (verified) {
750                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
751                                needUpdate = true;
752                            }
753                            break;
754
755                        default:
756                            // Nothing to do
757                    }
758
759                    if (needUpdate) {
760                        mSettings.updateIntentFilterVerificationStatusLPw(
761                                packageName, updatedStatus, userId);
762                        scheduleWritePackageRestrictionsLocked(userId);
763                    }
764                }
765            }
766        }
767
768        @Override
769        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
770                    ActivityIntentInfo filter, String packageName) {
771            if (!hasValidDomains(filter)) {
772                return false;
773            }
774            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
775            if (ivs == null) {
776                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
777                        packageName);
778            }
779            if (DEBUG_DOMAIN_VERIFICATION) {
780                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
781            }
782            ivs.addFilter(filter);
783            return true;
784        }
785
786        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
787                int userId, int verificationId, String packageName) {
788            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
789                    verifierUid, userId, packageName);
790            ivs.setPendingState();
791            synchronized (mPackages) {
792                mIntentFilterVerificationStates.append(verificationId, ivs);
793                mCurrentIntentFilterVerifications.add(verificationId);
794            }
795            return ivs;
796        }
797    }
798
799    private static boolean hasValidDomains(ActivityIntentInfo filter) {
800        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
801                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
802        if (!hasHTTPorHTTPS) {
803            return false;
804        }
805        return true;
806    }
807
808    private IntentFilterVerifier mIntentFilterVerifier;
809
810    // Set of pending broadcasts for aggregating enable/disable of components.
811    static class PendingPackageBroadcasts {
812        // for each user id, a map of <package name -> components within that package>
813        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
814
815        public PendingPackageBroadcasts() {
816            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
817        }
818
819        public ArrayList<String> get(int userId, String packageName) {
820            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
821            return packages.get(packageName);
822        }
823
824        public void put(int userId, String packageName, ArrayList<String> components) {
825            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
826            packages.put(packageName, components);
827        }
828
829        public void remove(int userId, String packageName) {
830            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
831            if (packages != null) {
832                packages.remove(packageName);
833            }
834        }
835
836        public void remove(int userId) {
837            mUidMap.remove(userId);
838        }
839
840        public int userIdCount() {
841            return mUidMap.size();
842        }
843
844        public int userIdAt(int n) {
845            return mUidMap.keyAt(n);
846        }
847
848        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
849            return mUidMap.get(userId);
850        }
851
852        public int size() {
853            // total number of pending broadcast entries across all userIds
854            int num = 0;
855            for (int i = 0; i< mUidMap.size(); i++) {
856                num += mUidMap.valueAt(i).size();
857            }
858            return num;
859        }
860
861        public void clear() {
862            mUidMap.clear();
863        }
864
865        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
866            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
867            if (map == null) {
868                map = new ArrayMap<String, ArrayList<String>>();
869                mUidMap.put(userId, map);
870            }
871            return map;
872        }
873    }
874    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
875
876    // Service Connection to remote media container service to copy
877    // package uri's from external media onto secure containers
878    // or internal storage.
879    private IMediaContainerService mContainerService = null;
880
881    static final int SEND_PENDING_BROADCAST = 1;
882    static final int MCS_BOUND = 3;
883    static final int END_COPY = 4;
884    static final int INIT_COPY = 5;
885    static final int MCS_UNBIND = 6;
886    static final int START_CLEANING_PACKAGE = 7;
887    static final int FIND_INSTALL_LOC = 8;
888    static final int POST_INSTALL = 9;
889    static final int MCS_RECONNECT = 10;
890    static final int MCS_GIVE_UP = 11;
891    static final int UPDATED_MEDIA_STATUS = 12;
892    static final int WRITE_SETTINGS = 13;
893    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
894    static final int PACKAGE_VERIFIED = 15;
895    static final int CHECK_PENDING_VERIFICATION = 16;
896    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
897    static final int INTENT_FILTER_VERIFIED = 18;
898
899    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
900
901    // Delay time in millisecs
902    static final int BROADCAST_DELAY = 10 * 1000;
903
904    static UserManagerService sUserManager;
905
906    // Stores a list of users whose package restrictions file needs to be updated
907    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
908
909    final private DefaultContainerConnection mDefContainerConn =
910            new DefaultContainerConnection();
911    class DefaultContainerConnection implements ServiceConnection {
912        public void onServiceConnected(ComponentName name, IBinder service) {
913            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
914            IMediaContainerService imcs =
915                IMediaContainerService.Stub.asInterface(service);
916            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
917        }
918
919        public void onServiceDisconnected(ComponentName name) {
920            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
921        }
922    }
923
924    // Recordkeeping of restore-after-install operations that are currently in flight
925    // between the Package Manager and the Backup Manager
926    class PostInstallData {
927        public InstallArgs args;
928        public PackageInstalledInfo res;
929
930        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
931            args = _a;
932            res = _r;
933        }
934    }
935
936    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
937    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
938
939    // XML tags for backup/restore of various bits of state
940    private static final String TAG_PREFERRED_BACKUP = "pa";
941    private static final String TAG_DEFAULT_APPS = "da";
942    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
943
944    final String mRequiredVerifierPackage;
945    final String mRequiredInstallerPackage;
946
947    private final PackageUsage mPackageUsage = new PackageUsage();
948
949    private class PackageUsage {
950        private static final int WRITE_INTERVAL
951            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
952
953        private final Object mFileLock = new Object();
954        private final AtomicLong mLastWritten = new AtomicLong(0);
955        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
956
957        private boolean mIsHistoricalPackageUsageAvailable = true;
958
959        boolean isHistoricalPackageUsageAvailable() {
960            return mIsHistoricalPackageUsageAvailable;
961        }
962
963        void write(boolean force) {
964            if (force) {
965                writeInternal();
966                return;
967            }
968            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
969                && !DEBUG_DEXOPT) {
970                return;
971            }
972            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
973                new Thread("PackageUsage_DiskWriter") {
974                    @Override
975                    public void run() {
976                        try {
977                            writeInternal();
978                        } finally {
979                            mBackgroundWriteRunning.set(false);
980                        }
981                    }
982                }.start();
983            }
984        }
985
986        private void writeInternal() {
987            synchronized (mPackages) {
988                synchronized (mFileLock) {
989                    AtomicFile file = getFile();
990                    FileOutputStream f = null;
991                    try {
992                        f = file.startWrite();
993                        BufferedOutputStream out = new BufferedOutputStream(f);
994                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
995                        StringBuilder sb = new StringBuilder();
996                        for (PackageParser.Package pkg : mPackages.values()) {
997                            if (pkg.mLastPackageUsageTimeInMills == 0) {
998                                continue;
999                            }
1000                            sb.setLength(0);
1001                            sb.append(pkg.packageName);
1002                            sb.append(' ');
1003                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1004                            sb.append('\n');
1005                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1006                        }
1007                        out.flush();
1008                        file.finishWrite(f);
1009                    } catch (IOException e) {
1010                        if (f != null) {
1011                            file.failWrite(f);
1012                        }
1013                        Log.e(TAG, "Failed to write package usage times", e);
1014                    }
1015                }
1016            }
1017            mLastWritten.set(SystemClock.elapsedRealtime());
1018        }
1019
1020        void readLP() {
1021            synchronized (mFileLock) {
1022                AtomicFile file = getFile();
1023                BufferedInputStream in = null;
1024                try {
1025                    in = new BufferedInputStream(file.openRead());
1026                    StringBuffer sb = new StringBuffer();
1027                    while (true) {
1028                        String packageName = readToken(in, sb, ' ');
1029                        if (packageName == null) {
1030                            break;
1031                        }
1032                        String timeInMillisString = readToken(in, sb, '\n');
1033                        if (timeInMillisString == null) {
1034                            throw new IOException("Failed to find last usage time for package "
1035                                                  + packageName);
1036                        }
1037                        PackageParser.Package pkg = mPackages.get(packageName);
1038                        if (pkg == null) {
1039                            continue;
1040                        }
1041                        long timeInMillis;
1042                        try {
1043                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1044                        } catch (NumberFormatException e) {
1045                            throw new IOException("Failed to parse " + timeInMillisString
1046                                                  + " as a long.", e);
1047                        }
1048                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1049                    }
1050                } catch (FileNotFoundException expected) {
1051                    mIsHistoricalPackageUsageAvailable = false;
1052                } catch (IOException e) {
1053                    Log.w(TAG, "Failed to read package usage times", e);
1054                } finally {
1055                    IoUtils.closeQuietly(in);
1056                }
1057            }
1058            mLastWritten.set(SystemClock.elapsedRealtime());
1059        }
1060
1061        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1062                throws IOException {
1063            sb.setLength(0);
1064            while (true) {
1065                int ch = in.read();
1066                if (ch == -1) {
1067                    if (sb.length() == 0) {
1068                        return null;
1069                    }
1070                    throw new IOException("Unexpected EOF");
1071                }
1072                if (ch == endOfToken) {
1073                    return sb.toString();
1074                }
1075                sb.append((char)ch);
1076            }
1077        }
1078
1079        private AtomicFile getFile() {
1080            File dataDir = Environment.getDataDirectory();
1081            File systemDir = new File(dataDir, "system");
1082            File fname = new File(systemDir, "package-usage.list");
1083            return new AtomicFile(fname);
1084        }
1085    }
1086
1087    class PackageHandler extends Handler {
1088        private boolean mBound = false;
1089        final ArrayList<HandlerParams> mPendingInstalls =
1090            new ArrayList<HandlerParams>();
1091
1092        private boolean connectToService() {
1093            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1094                    " DefaultContainerService");
1095            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1096            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1097            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1098                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1099                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1100                mBound = true;
1101                return true;
1102            }
1103            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1104            return false;
1105        }
1106
1107        private void disconnectService() {
1108            mContainerService = null;
1109            mBound = false;
1110            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1111            mContext.unbindService(mDefContainerConn);
1112            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113        }
1114
1115        PackageHandler(Looper looper) {
1116            super(looper);
1117        }
1118
1119        public void handleMessage(Message msg) {
1120            try {
1121                doHandleMessage(msg);
1122            } finally {
1123                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1124            }
1125        }
1126
1127        void doHandleMessage(Message msg) {
1128            switch (msg.what) {
1129                case INIT_COPY: {
1130                    HandlerParams params = (HandlerParams) msg.obj;
1131                    int idx = mPendingInstalls.size();
1132                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1133                    // If a bind was already initiated we dont really
1134                    // need to do anything. The pending install
1135                    // will be processed later on.
1136                    if (!mBound) {
1137                        // If this is the only one pending we might
1138                        // have to bind to the service again.
1139                        if (!connectToService()) {
1140                            Slog.e(TAG, "Failed to bind to media container service");
1141                            params.serviceError();
1142                            return;
1143                        } else {
1144                            // Once we bind to the service, the first
1145                            // pending request will be processed.
1146                            mPendingInstalls.add(idx, params);
1147                        }
1148                    } else {
1149                        mPendingInstalls.add(idx, params);
1150                        // Already bound to the service. Just make
1151                        // sure we trigger off processing the first request.
1152                        if (idx == 0) {
1153                            mHandler.sendEmptyMessage(MCS_BOUND);
1154                        }
1155                    }
1156                    break;
1157                }
1158                case MCS_BOUND: {
1159                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1160                    if (msg.obj != null) {
1161                        mContainerService = (IMediaContainerService) msg.obj;
1162                    }
1163                    if (mContainerService == null) {
1164                        if (!mBound) {
1165                            // Something seriously wrong since we are not bound and we are not
1166                            // waiting for connection. Bail out.
1167                            Slog.e(TAG, "Cannot bind to media container service");
1168                            for (HandlerParams params : mPendingInstalls) {
1169                                // Indicate service bind error
1170                                params.serviceError();
1171                            }
1172                            mPendingInstalls.clear();
1173                        } else {
1174                            Slog.w(TAG, "Waiting to connect to media container service");
1175                        }
1176                    } else if (mPendingInstalls.size() > 0) {
1177                        HandlerParams params = mPendingInstalls.get(0);
1178                        if (params != null) {
1179                            if (params.startCopy()) {
1180                                // We are done...  look for more work or to
1181                                // go idle.
1182                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1183                                        "Checking for more work or unbind...");
1184                                // Delete pending install
1185                                if (mPendingInstalls.size() > 0) {
1186                                    mPendingInstalls.remove(0);
1187                                }
1188                                if (mPendingInstalls.size() == 0) {
1189                                    if (mBound) {
1190                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1191                                                "Posting delayed MCS_UNBIND");
1192                                        removeMessages(MCS_UNBIND);
1193                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1194                                        // Unbind after a little delay, to avoid
1195                                        // continual thrashing.
1196                                        sendMessageDelayed(ubmsg, 10000);
1197                                    }
1198                                } else {
1199                                    // There are more pending requests in queue.
1200                                    // Just post MCS_BOUND message to trigger processing
1201                                    // of next pending install.
1202                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1203                                            "Posting MCS_BOUND for next work");
1204                                    mHandler.sendEmptyMessage(MCS_BOUND);
1205                                }
1206                            }
1207                        }
1208                    } else {
1209                        // Should never happen ideally.
1210                        Slog.w(TAG, "Empty queue");
1211                    }
1212                    break;
1213                }
1214                case MCS_RECONNECT: {
1215                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1216                    if (mPendingInstalls.size() > 0) {
1217                        if (mBound) {
1218                            disconnectService();
1219                        }
1220                        if (!connectToService()) {
1221                            Slog.e(TAG, "Failed to bind to media container service");
1222                            for (HandlerParams params : mPendingInstalls) {
1223                                // Indicate service bind error
1224                                params.serviceError();
1225                            }
1226                            mPendingInstalls.clear();
1227                        }
1228                    }
1229                    break;
1230                }
1231                case MCS_UNBIND: {
1232                    // If there is no actual work left, then time to unbind.
1233                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1234
1235                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1236                        if (mBound) {
1237                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1238
1239                            disconnectService();
1240                        }
1241                    } else if (mPendingInstalls.size() > 0) {
1242                        // There are more pending requests in queue.
1243                        // Just post MCS_BOUND message to trigger processing
1244                        // of next pending install.
1245                        mHandler.sendEmptyMessage(MCS_BOUND);
1246                    }
1247
1248                    break;
1249                }
1250                case MCS_GIVE_UP: {
1251                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1252                    mPendingInstalls.remove(0);
1253                    break;
1254                }
1255                case SEND_PENDING_BROADCAST: {
1256                    String packages[];
1257                    ArrayList<String> components[];
1258                    int size = 0;
1259                    int uids[];
1260                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1261                    synchronized (mPackages) {
1262                        if (mPendingBroadcasts == null) {
1263                            return;
1264                        }
1265                        size = mPendingBroadcasts.size();
1266                        if (size <= 0) {
1267                            // Nothing to be done. Just return
1268                            return;
1269                        }
1270                        packages = new String[size];
1271                        components = new ArrayList[size];
1272                        uids = new int[size];
1273                        int i = 0;  // filling out the above arrays
1274
1275                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1276                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1277                            Iterator<Map.Entry<String, ArrayList<String>>> it
1278                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1279                                            .entrySet().iterator();
1280                            while (it.hasNext() && i < size) {
1281                                Map.Entry<String, ArrayList<String>> ent = it.next();
1282                                packages[i] = ent.getKey();
1283                                components[i] = ent.getValue();
1284                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1285                                uids[i] = (ps != null)
1286                                        ? UserHandle.getUid(packageUserId, ps.appId)
1287                                        : -1;
1288                                i++;
1289                            }
1290                        }
1291                        size = i;
1292                        mPendingBroadcasts.clear();
1293                    }
1294                    // Send broadcasts
1295                    for (int i = 0; i < size; i++) {
1296                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1297                    }
1298                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1299                    break;
1300                }
1301                case START_CLEANING_PACKAGE: {
1302                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1303                    final String packageName = (String)msg.obj;
1304                    final int userId = msg.arg1;
1305                    final boolean andCode = msg.arg2 != 0;
1306                    synchronized (mPackages) {
1307                        if (userId == UserHandle.USER_ALL) {
1308                            int[] users = sUserManager.getUserIds();
1309                            for (int user : users) {
1310                                mSettings.addPackageToCleanLPw(
1311                                        new PackageCleanItem(user, packageName, andCode));
1312                            }
1313                        } else {
1314                            mSettings.addPackageToCleanLPw(
1315                                    new PackageCleanItem(userId, packageName, andCode));
1316                        }
1317                    }
1318                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1319                    startCleaningPackages();
1320                } break;
1321                case POST_INSTALL: {
1322                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1323                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1324                    mRunningInstalls.delete(msg.arg1);
1325                    boolean deleteOld = false;
1326
1327                    if (data != null) {
1328                        InstallArgs args = data.args;
1329                        PackageInstalledInfo res = data.res;
1330
1331                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1332                            final String packageName = res.pkg.applicationInfo.packageName;
1333                            res.removedInfo.sendBroadcast(false, true, false);
1334                            Bundle extras = new Bundle(1);
1335                            extras.putInt(Intent.EXTRA_UID, res.uid);
1336
1337                            // Now that we successfully installed the package, grant runtime
1338                            // permissions if requested before broadcasting the install.
1339                            if ((args.installFlags
1340                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1341                                grantRequestedRuntimePermissions(res.pkg,
1342                                        args.user.getIdentifier());
1343                            }
1344
1345                            // Determine the set of users who are adding this
1346                            // package for the first time vs. those who are seeing
1347                            // an update.
1348                            int[] firstUsers;
1349                            int[] updateUsers = new int[0];
1350                            if (res.origUsers == null || res.origUsers.length == 0) {
1351                                firstUsers = res.newUsers;
1352                            } else {
1353                                firstUsers = new int[0];
1354                                for (int i=0; i<res.newUsers.length; i++) {
1355                                    int user = res.newUsers[i];
1356                                    boolean isNew = true;
1357                                    for (int j=0; j<res.origUsers.length; j++) {
1358                                        if (res.origUsers[j] == user) {
1359                                            isNew = false;
1360                                            break;
1361                                        }
1362                                    }
1363                                    if (isNew) {
1364                                        int[] newFirst = new int[firstUsers.length+1];
1365                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1366                                                firstUsers.length);
1367                                        newFirst[firstUsers.length] = user;
1368                                        firstUsers = newFirst;
1369                                    } else {
1370                                        int[] newUpdate = new int[updateUsers.length+1];
1371                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1372                                                updateUsers.length);
1373                                        newUpdate[updateUsers.length] = user;
1374                                        updateUsers = newUpdate;
1375                                    }
1376                                }
1377                            }
1378                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1379                                    packageName, extras, null, null, firstUsers);
1380                            final boolean update = res.removedInfo.removedPackage != null;
1381                            if (update) {
1382                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1383                            }
1384                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1385                                    packageName, extras, null, null, updateUsers);
1386                            if (update) {
1387                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1388                                        packageName, extras, null, null, updateUsers);
1389                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1390                                        null, null, packageName, null, updateUsers);
1391
1392                                // treat asec-hosted packages like removable media on upgrade
1393                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1394                                    if (DEBUG_INSTALL) {
1395                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1396                                                + " is ASEC-hosted -> AVAILABLE");
1397                                    }
1398                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1399                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1400                                    pkgList.add(packageName);
1401                                    sendResourcesChangedBroadcast(true, true,
1402                                            pkgList,uidArray, null);
1403                                }
1404                            }
1405                            if (res.removedInfo.args != null) {
1406                                // Remove the replaced package's older resources safely now
1407                                deleteOld = true;
1408                            }
1409
1410                            // If this app is a browser and it's newly-installed for some
1411                            // users, clear any default-browser state in those users
1412                            if (firstUsers.length > 0) {
1413                                // the app's nature doesn't depend on the user, so we can just
1414                                // check its browser nature in any user and generalize.
1415                                if (packageIsBrowser(packageName, firstUsers[0])) {
1416                                    synchronized (mPackages) {
1417                                        for (int userId : firstUsers) {
1418                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1419                                        }
1420                                    }
1421                                }
1422                            }
1423                            // Log current value of "unknown sources" setting
1424                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1425                                getUnknownSourcesSettings());
1426                        }
1427                        // Force a gc to clear up things
1428                        Runtime.getRuntime().gc();
1429                        // We delete after a gc for applications  on sdcard.
1430                        if (deleteOld) {
1431                            synchronized (mInstallLock) {
1432                                res.removedInfo.args.doPostDeleteLI(true);
1433                            }
1434                        }
1435                        if (args.observer != null) {
1436                            try {
1437                                Bundle extras = extrasForInstallResult(res);
1438                                args.observer.onPackageInstalled(res.name, res.returnCode,
1439                                        res.returnMsg, extras);
1440                            } catch (RemoteException e) {
1441                                Slog.i(TAG, "Observer no longer exists.");
1442                            }
1443                        }
1444                    } else {
1445                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1446                    }
1447                } break;
1448                case UPDATED_MEDIA_STATUS: {
1449                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1450                    boolean reportStatus = msg.arg1 == 1;
1451                    boolean doGc = msg.arg2 == 1;
1452                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1453                    if (doGc) {
1454                        // Force a gc to clear up stale containers.
1455                        Runtime.getRuntime().gc();
1456                    }
1457                    if (msg.obj != null) {
1458                        @SuppressWarnings("unchecked")
1459                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1460                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1461                        // Unload containers
1462                        unloadAllContainers(args);
1463                    }
1464                    if (reportStatus) {
1465                        try {
1466                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1467                            PackageHelper.getMountService().finishMediaUpdate();
1468                        } catch (RemoteException e) {
1469                            Log.e(TAG, "MountService not running?");
1470                        }
1471                    }
1472                } break;
1473                case WRITE_SETTINGS: {
1474                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1475                    synchronized (mPackages) {
1476                        removeMessages(WRITE_SETTINGS);
1477                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1478                        mSettings.writeLPr();
1479                        mDirtyUsers.clear();
1480                    }
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1482                } break;
1483                case WRITE_PACKAGE_RESTRICTIONS: {
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1485                    synchronized (mPackages) {
1486                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1487                        for (int userId : mDirtyUsers) {
1488                            mSettings.writePackageRestrictionsLPr(userId);
1489                        }
1490                        mDirtyUsers.clear();
1491                    }
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1493                } break;
1494                case CHECK_PENDING_VERIFICATION: {
1495                    final int verificationId = msg.arg1;
1496                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1497
1498                    if ((state != null) && !state.timeoutExtended()) {
1499                        final InstallArgs args = state.getInstallArgs();
1500                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1501
1502                        Slog.i(TAG, "Verification timed out for " + originUri);
1503                        mPendingVerification.remove(verificationId);
1504
1505                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1506
1507                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1508                            Slog.i(TAG, "Continuing with installation of " + originUri);
1509                            state.setVerifierResponse(Binder.getCallingUid(),
1510                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1511                            broadcastPackageVerified(verificationId, originUri,
1512                                    PackageManager.VERIFICATION_ALLOW,
1513                                    state.getInstallArgs().getUser());
1514                            try {
1515                                ret = args.copyApk(mContainerService, true);
1516                            } catch (RemoteException e) {
1517                                Slog.e(TAG, "Could not contact the ContainerService");
1518                            }
1519                        } else {
1520                            broadcastPackageVerified(verificationId, originUri,
1521                                    PackageManager.VERIFICATION_REJECT,
1522                                    state.getInstallArgs().getUser());
1523                        }
1524
1525                        processPendingInstall(args, ret);
1526                        mHandler.sendEmptyMessage(MCS_UNBIND);
1527                    }
1528                    break;
1529                }
1530                case PACKAGE_VERIFIED: {
1531                    final int verificationId = msg.arg1;
1532
1533                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1534                    if (state == null) {
1535                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1536                        break;
1537                    }
1538
1539                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1540
1541                    state.setVerifierResponse(response.callerUid, response.code);
1542
1543                    if (state.isVerificationComplete()) {
1544                        mPendingVerification.remove(verificationId);
1545
1546                        final InstallArgs args = state.getInstallArgs();
1547                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1548
1549                        int ret;
1550                        if (state.isInstallAllowed()) {
1551                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1552                            broadcastPackageVerified(verificationId, originUri,
1553                                    response.code, state.getInstallArgs().getUser());
1554                            try {
1555                                ret = args.copyApk(mContainerService, true);
1556                            } catch (RemoteException e) {
1557                                Slog.e(TAG, "Could not contact the ContainerService");
1558                            }
1559                        } else {
1560                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1561                        }
1562
1563                        processPendingInstall(args, ret);
1564
1565                        mHandler.sendEmptyMessage(MCS_UNBIND);
1566                    }
1567
1568                    break;
1569                }
1570                case START_INTENT_FILTER_VERIFICATIONS: {
1571                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1572                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1573                            params.replacing, params.pkg);
1574                    break;
1575                }
1576                case INTENT_FILTER_VERIFIED: {
1577                    final int verificationId = msg.arg1;
1578
1579                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1580                            verificationId);
1581                    if (state == null) {
1582                        Slog.w(TAG, "Invalid IntentFilter verification token "
1583                                + verificationId + " received");
1584                        break;
1585                    }
1586
1587                    final int userId = state.getUserId();
1588
1589                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1590                            "Processing IntentFilter verification with token:"
1591                            + verificationId + " and userId:" + userId);
1592
1593                    final IntentFilterVerificationResponse response =
1594                            (IntentFilterVerificationResponse) msg.obj;
1595
1596                    state.setVerifierResponse(response.callerUid, response.code);
1597
1598                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1599                            "IntentFilter verification with token:" + verificationId
1600                            + " and userId:" + userId
1601                            + " is settings verifier response with response code:"
1602                            + response.code);
1603
1604                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1605                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1606                                + response.getFailedDomainsString());
1607                    }
1608
1609                    if (state.isVerificationComplete()) {
1610                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1611                    } else {
1612                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1613                                "IntentFilter verification with token:" + verificationId
1614                                + " was not said to be complete");
1615                    }
1616
1617                    break;
1618                }
1619            }
1620        }
1621    }
1622
1623    private StorageEventListener mStorageListener = new StorageEventListener() {
1624        @Override
1625        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1626            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1627                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1628                    final String volumeUuid = vol.getFsUuid();
1629
1630                    // Clean up any users or apps that were removed or recreated
1631                    // while this volume was missing
1632                    reconcileUsers(volumeUuid);
1633                    reconcileApps(volumeUuid);
1634
1635                    // Clean up any install sessions that expired or were
1636                    // cancelled while this volume was missing
1637                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1638
1639                    loadPrivatePackages(vol);
1640
1641                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1642                    unloadPrivatePackages(vol);
1643                }
1644            }
1645
1646            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1647                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1648                    updateExternalMediaStatus(true, false);
1649                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1650                    updateExternalMediaStatus(false, false);
1651                }
1652            }
1653        }
1654
1655        @Override
1656        public void onVolumeForgotten(String fsUuid) {
1657            // Remove any apps installed on the forgotten volume
1658            synchronized (mPackages) {
1659                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1660                for (PackageSetting ps : packages) {
1661                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1662                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1663                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1664                }
1665
1666                mSettings.writeLPr();
1667            }
1668        }
1669    };
1670
1671    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1672        if (userId >= UserHandle.USER_OWNER) {
1673            grantRequestedRuntimePermissionsForUser(pkg, userId);
1674        } else if (userId == UserHandle.USER_ALL) {
1675            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1676                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1677            }
1678        }
1679
1680        // We could have touched GID membership, so flush out packages.list
1681        synchronized (mPackages) {
1682            mSettings.writePackageListLPr();
1683        }
1684    }
1685
1686    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1687        SettingBase sb = (SettingBase) pkg.mExtras;
1688        if (sb == null) {
1689            return;
1690        }
1691
1692        PermissionsState permissionsState = sb.getPermissionsState();
1693
1694        for (String permission : pkg.requestedPermissions) {
1695            BasePermission bp = mSettings.mPermissions.get(permission);
1696            if (bp != null && bp.isRuntime()) {
1697                permissionsState.grantRuntimePermission(bp, userId);
1698            }
1699        }
1700    }
1701
1702    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1703        Bundle extras = null;
1704        switch (res.returnCode) {
1705            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1706                extras = new Bundle();
1707                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1708                        res.origPermission);
1709                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1710                        res.origPackage);
1711                break;
1712            }
1713            case PackageManager.INSTALL_SUCCEEDED: {
1714                extras = new Bundle();
1715                extras.putBoolean(Intent.EXTRA_REPLACING,
1716                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1717                break;
1718            }
1719        }
1720        return extras;
1721    }
1722
1723    void scheduleWriteSettingsLocked() {
1724        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1725            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1726        }
1727    }
1728
1729    void scheduleWritePackageRestrictionsLocked(int userId) {
1730        if (!sUserManager.exists(userId)) return;
1731        mDirtyUsers.add(userId);
1732        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1733            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1734        }
1735    }
1736
1737    public static PackageManagerService main(Context context, Installer installer,
1738            boolean factoryTest, boolean onlyCore) {
1739        PackageManagerService m = new PackageManagerService(context, installer,
1740                factoryTest, onlyCore);
1741        ServiceManager.addService("package", m);
1742        return m;
1743    }
1744
1745    static String[] splitString(String str, char sep) {
1746        int count = 1;
1747        int i = 0;
1748        while ((i=str.indexOf(sep, i)) >= 0) {
1749            count++;
1750            i++;
1751        }
1752
1753        String[] res = new String[count];
1754        i=0;
1755        count = 0;
1756        int lastI=0;
1757        while ((i=str.indexOf(sep, i)) >= 0) {
1758            res[count] = str.substring(lastI, i);
1759            count++;
1760            i++;
1761            lastI = i;
1762        }
1763        res[count] = str.substring(lastI, str.length());
1764        return res;
1765    }
1766
1767    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1768        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1769                Context.DISPLAY_SERVICE);
1770        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1771    }
1772
1773    public PackageManagerService(Context context, Installer installer,
1774            boolean factoryTest, boolean onlyCore) {
1775        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1776                SystemClock.uptimeMillis());
1777
1778        if (mSdkVersion <= 0) {
1779            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1780        }
1781
1782        mContext = context;
1783        mFactoryTest = factoryTest;
1784        mOnlyCore = onlyCore;
1785        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1786        mMetrics = new DisplayMetrics();
1787        mSettings = new Settings(mPackages);
1788        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1789                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1790        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1791                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1792        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1793                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1794        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1795                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1796        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1797                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1798        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1799                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1800
1801        // TODO: add a property to control this?
1802        long dexOptLRUThresholdInMinutes;
1803        if (mLazyDexOpt) {
1804            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1805        } else {
1806            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1807        }
1808        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1809
1810        String separateProcesses = SystemProperties.get("debug.separate_processes");
1811        if (separateProcesses != null && separateProcesses.length() > 0) {
1812            if ("*".equals(separateProcesses)) {
1813                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1814                mSeparateProcesses = null;
1815                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1816            } else {
1817                mDefParseFlags = 0;
1818                mSeparateProcesses = separateProcesses.split(",");
1819                Slog.w(TAG, "Running with debug.separate_processes: "
1820                        + separateProcesses);
1821            }
1822        } else {
1823            mDefParseFlags = 0;
1824            mSeparateProcesses = null;
1825        }
1826
1827        mInstaller = installer;
1828        mPackageDexOptimizer = new PackageDexOptimizer(this);
1829        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1830
1831        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1832                FgThread.get().getLooper());
1833
1834        getDefaultDisplayMetrics(context, mMetrics);
1835
1836        SystemConfig systemConfig = SystemConfig.getInstance();
1837        mGlobalGids = systemConfig.getGlobalGids();
1838        mSystemPermissions = systemConfig.getSystemPermissions();
1839        mAvailableFeatures = systemConfig.getAvailableFeatures();
1840
1841        synchronized (mInstallLock) {
1842        // writer
1843        synchronized (mPackages) {
1844            mHandlerThread = new ServiceThread(TAG,
1845                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1846            mHandlerThread.start();
1847            mHandler = new PackageHandler(mHandlerThread.getLooper());
1848            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1849
1850            File dataDir = Environment.getDataDirectory();
1851            mAppDataDir = new File(dataDir, "data");
1852            mAppInstallDir = new File(dataDir, "app");
1853            mAppLib32InstallDir = new File(dataDir, "app-lib");
1854            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1855            mUserAppDataDir = new File(dataDir, "user");
1856            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1857
1858            sUserManager = new UserManagerService(context, this,
1859                    mInstallLock, mPackages);
1860
1861            // Propagate permission configuration in to package manager.
1862            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1863                    = systemConfig.getPermissions();
1864            for (int i=0; i<permConfig.size(); i++) {
1865                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1866                BasePermission bp = mSettings.mPermissions.get(perm.name);
1867                if (bp == null) {
1868                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1869                    mSettings.mPermissions.put(perm.name, bp);
1870                }
1871                if (perm.gids != null) {
1872                    bp.setGids(perm.gids, perm.perUser);
1873                }
1874            }
1875
1876            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1877            for (int i=0; i<libConfig.size(); i++) {
1878                mSharedLibraries.put(libConfig.keyAt(i),
1879                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1880            }
1881
1882            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1883
1884            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1885                    mSdkVersion, mOnlyCore);
1886
1887            String customResolverActivity = Resources.getSystem().getString(
1888                    R.string.config_customResolverActivity);
1889            if (TextUtils.isEmpty(customResolverActivity)) {
1890                customResolverActivity = null;
1891            } else {
1892                mCustomResolverComponentName = ComponentName.unflattenFromString(
1893                        customResolverActivity);
1894            }
1895
1896            long startTime = SystemClock.uptimeMillis();
1897
1898            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1899                    startTime);
1900
1901            // Set flag to monitor and not change apk file paths when
1902            // scanning install directories.
1903            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1904
1905            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1906
1907            /**
1908             * Add everything in the in the boot class path to the
1909             * list of process files because dexopt will have been run
1910             * if necessary during zygote startup.
1911             */
1912            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1913            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1914
1915            if (bootClassPath != null) {
1916                String[] bootClassPathElements = splitString(bootClassPath, ':');
1917                for (String element : bootClassPathElements) {
1918                    alreadyDexOpted.add(element);
1919                }
1920            } else {
1921                Slog.w(TAG, "No BOOTCLASSPATH found!");
1922            }
1923
1924            if (systemServerClassPath != null) {
1925                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1926                for (String element : systemServerClassPathElements) {
1927                    alreadyDexOpted.add(element);
1928                }
1929            } else {
1930                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1931            }
1932
1933            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1934            final String[] dexCodeInstructionSets =
1935                    getDexCodeInstructionSets(
1936                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1937
1938            /**
1939             * Ensure all external libraries have had dexopt run on them.
1940             */
1941            if (mSharedLibraries.size() > 0) {
1942                // NOTE: For now, we're compiling these system "shared libraries"
1943                // (and framework jars) into all available architectures. It's possible
1944                // to compile them only when we come across an app that uses them (there's
1945                // already logic for that in scanPackageLI) but that adds some complexity.
1946                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1947                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1948                        final String lib = libEntry.path;
1949                        if (lib == null) {
1950                            continue;
1951                        }
1952
1953                        try {
1954                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1955                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1956                                alreadyDexOpted.add(lib);
1957                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1958                            }
1959                        } catch (FileNotFoundException e) {
1960                            Slog.w(TAG, "Library not found: " + lib);
1961                        } catch (IOException e) {
1962                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1963                                    + e.getMessage());
1964                        }
1965                    }
1966                }
1967            }
1968
1969            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1970
1971            // Gross hack for now: we know this file doesn't contain any
1972            // code, so don't dexopt it to avoid the resulting log spew.
1973            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1974
1975            // Gross hack for now: we know this file is only part of
1976            // the boot class path for art, so don't dexopt it to
1977            // avoid the resulting log spew.
1978            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1979
1980            /**
1981             * There are a number of commands implemented in Java, which
1982             * we currently need to do the dexopt on so that they can be
1983             * run from a non-root shell.
1984             */
1985            String[] frameworkFiles = frameworkDir.list();
1986            if (frameworkFiles != null) {
1987                // TODO: We could compile these only for the most preferred ABI. We should
1988                // first double check that the dex files for these commands are not referenced
1989                // by other system apps.
1990                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1991                    for (int i=0; i<frameworkFiles.length; i++) {
1992                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1993                        String path = libPath.getPath();
1994                        // Skip the file if we already did it.
1995                        if (alreadyDexOpted.contains(path)) {
1996                            continue;
1997                        }
1998                        // Skip the file if it is not a type we want to dexopt.
1999                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2000                            continue;
2001                        }
2002                        try {
2003                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2004                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2005                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2006                            }
2007                        } catch (FileNotFoundException e) {
2008                            Slog.w(TAG, "Jar not found: " + path);
2009                        } catch (IOException e) {
2010                            Slog.w(TAG, "Exception reading jar: " + path, e);
2011                        }
2012                    }
2013                }
2014            }
2015
2016            // Collect vendor overlay packages.
2017            // (Do this before scanning any apps.)
2018            // For security and version matching reason, only consider
2019            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2020            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2021            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2022                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2023
2024            // Find base frameworks (resource packages without code).
2025            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2026                    | PackageParser.PARSE_IS_SYSTEM_DIR
2027                    | PackageParser.PARSE_IS_PRIVILEGED,
2028                    scanFlags | SCAN_NO_DEX, 0);
2029
2030            // Collected privileged system packages.
2031            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2032            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2033                    | PackageParser.PARSE_IS_SYSTEM_DIR
2034                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2035
2036            // Collect ordinary system packages.
2037            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2038            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2039                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2040
2041            // Collect all vendor packages.
2042            File vendorAppDir = new File("/vendor/app");
2043            try {
2044                vendorAppDir = vendorAppDir.getCanonicalFile();
2045            } catch (IOException e) {
2046                // failed to look up canonical path, continue with original one
2047            }
2048            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2049                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2050
2051            // Collect all OEM packages.
2052            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2053            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2054                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2055
2056            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2057            mInstaller.moveFiles();
2058
2059            // Prune any system packages that no longer exist.
2060            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2061            if (!mOnlyCore) {
2062                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2063                while (psit.hasNext()) {
2064                    PackageSetting ps = psit.next();
2065
2066                    /*
2067                     * If this is not a system app, it can't be a
2068                     * disable system app.
2069                     */
2070                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2071                        continue;
2072                    }
2073
2074                    /*
2075                     * If the package is scanned, it's not erased.
2076                     */
2077                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2078                    if (scannedPkg != null) {
2079                        /*
2080                         * If the system app is both scanned and in the
2081                         * disabled packages list, then it must have been
2082                         * added via OTA. Remove it from the currently
2083                         * scanned package so the previously user-installed
2084                         * application can be scanned.
2085                         */
2086                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2087                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2088                                    + ps.name + "; removing system app.  Last known codePath="
2089                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2090                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2091                                    + scannedPkg.mVersionCode);
2092                            removePackageLI(ps, true);
2093                            mExpectingBetter.put(ps.name, ps.codePath);
2094                        }
2095
2096                        continue;
2097                    }
2098
2099                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2100                        psit.remove();
2101                        logCriticalInfo(Log.WARN, "System package " + ps.name
2102                                + " no longer exists; wiping its data");
2103                        removeDataDirsLI(null, ps.name);
2104                    } else {
2105                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2106                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2107                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2108                        }
2109                    }
2110                }
2111            }
2112
2113            //look for any incomplete package installations
2114            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2115            //clean up list
2116            for(int i = 0; i < deletePkgsList.size(); i++) {
2117                //clean up here
2118                cleanupInstallFailedPackage(deletePkgsList.get(i));
2119            }
2120            //delete tmp files
2121            deleteTempPackageFiles();
2122
2123            // Remove any shared userIDs that have no associated packages
2124            mSettings.pruneSharedUsersLPw();
2125
2126            if (!mOnlyCore) {
2127                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2128                        SystemClock.uptimeMillis());
2129                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2130
2131                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2132                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2133
2134                /**
2135                 * Remove disable package settings for any updated system
2136                 * apps that were removed via an OTA. If they're not a
2137                 * previously-updated app, remove them completely.
2138                 * Otherwise, just revoke their system-level permissions.
2139                 */
2140                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2141                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2142                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2143
2144                    String msg;
2145                    if (deletedPkg == null) {
2146                        msg = "Updated system package " + deletedAppName
2147                                + " no longer exists; wiping its data";
2148                        removeDataDirsLI(null, deletedAppName);
2149                    } else {
2150                        msg = "Updated system app + " + deletedAppName
2151                                + " no longer present; removing system privileges for "
2152                                + deletedAppName;
2153
2154                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2155
2156                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2157                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2158                    }
2159                    logCriticalInfo(Log.WARN, msg);
2160                }
2161
2162                /**
2163                 * Make sure all system apps that we expected to appear on
2164                 * the userdata partition actually showed up. If they never
2165                 * appeared, crawl back and revive the system version.
2166                 */
2167                for (int i = 0; i < mExpectingBetter.size(); i++) {
2168                    final String packageName = mExpectingBetter.keyAt(i);
2169                    if (!mPackages.containsKey(packageName)) {
2170                        final File scanFile = mExpectingBetter.valueAt(i);
2171
2172                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2173                                + " but never showed up; reverting to system");
2174
2175                        final int reparseFlags;
2176                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2177                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2178                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2179                                    | PackageParser.PARSE_IS_PRIVILEGED;
2180                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2181                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2182                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2183                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2184                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2185                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2186                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2187                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2188                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2189                        } else {
2190                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2191                            continue;
2192                        }
2193
2194                        mSettings.enableSystemPackageLPw(packageName);
2195
2196                        try {
2197                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2198                        } catch (PackageManagerException e) {
2199                            Slog.e(TAG, "Failed to parse original system package: "
2200                                    + e.getMessage());
2201                        }
2202                    }
2203                }
2204            }
2205            mExpectingBetter.clear();
2206
2207            // Now that we know all of the shared libraries, update all clients to have
2208            // the correct library paths.
2209            updateAllSharedLibrariesLPw();
2210
2211            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2212                // NOTE: We ignore potential failures here during a system scan (like
2213                // the rest of the commands above) because there's precious little we
2214                // can do about it. A settings error is reported, though.
2215                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2216                        false /* force dexopt */, false /* defer dexopt */);
2217            }
2218
2219            // Now that we know all the packages we are keeping,
2220            // read and update their last usage times.
2221            mPackageUsage.readLP();
2222
2223            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2224                    SystemClock.uptimeMillis());
2225            Slog.i(TAG, "Time to scan packages: "
2226                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2227                    + " seconds");
2228
2229            // If the platform SDK has changed since the last time we booted,
2230            // we need to re-grant app permission to catch any new ones that
2231            // appear.  This is really a hack, and means that apps can in some
2232            // cases get permissions that the user didn't initially explicitly
2233            // allow...  it would be nice to have some better way to handle
2234            // this situation.
2235            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2236                    != mSdkVersion;
2237            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2238                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2239                    + "; regranting permissions for internal storage");
2240            mSettings.mInternalSdkPlatform = mSdkVersion;
2241
2242            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2243                    | (regrantPermissions
2244                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2245                            : 0));
2246
2247            // If this is the first boot, and it is a normal boot, then
2248            // we need to initialize the default preferred apps.
2249            if (!mRestoredSettings && !onlyCore) {
2250                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2251                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2252                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2253            }
2254
2255            // If this is first boot after an OTA, and a normal boot, then
2256            // we need to clear code cache directories.
2257            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2258            if (mIsUpgrade && !onlyCore) {
2259                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2260                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2261                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2262                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2263                }
2264                mSettings.mFingerprint = Build.FINGERPRINT;
2265            }
2266
2267            checkDefaultBrowser();
2268
2269            // All the changes are done during package scanning.
2270            mSettings.updateInternalDatabaseVersion();
2271
2272            // can downgrade to reader
2273            mSettings.writeLPr();
2274
2275            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2276                    SystemClock.uptimeMillis());
2277
2278            mRequiredVerifierPackage = getRequiredVerifierLPr();
2279            mRequiredInstallerPackage = getRequiredInstallerLPr();
2280
2281            mInstallerService = new PackageInstallerService(context, this);
2282
2283            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2284            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2285                    mIntentFilterVerifierComponent);
2286
2287        } // synchronized (mPackages)
2288        } // synchronized (mInstallLock)
2289
2290        // Now after opening every single application zip, make sure they
2291        // are all flushed.  Not really needed, but keeps things nice and
2292        // tidy.
2293        Runtime.getRuntime().gc();
2294
2295        // Expose private service for system components to use.
2296        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2297    }
2298
2299    @Override
2300    public boolean isFirstBoot() {
2301        return !mRestoredSettings;
2302    }
2303
2304    @Override
2305    public boolean isOnlyCoreApps() {
2306        return mOnlyCore;
2307    }
2308
2309    @Override
2310    public boolean isUpgrade() {
2311        return mIsUpgrade;
2312    }
2313
2314    private String getRequiredVerifierLPr() {
2315        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2316        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2317                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2318
2319        String requiredVerifier = null;
2320
2321        final int N = receivers.size();
2322        for (int i = 0; i < N; i++) {
2323            final ResolveInfo info = receivers.get(i);
2324
2325            if (info.activityInfo == null) {
2326                continue;
2327            }
2328
2329            final String packageName = info.activityInfo.packageName;
2330
2331            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2332                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2333                continue;
2334            }
2335
2336            if (requiredVerifier != null) {
2337                throw new RuntimeException("There can be only one required verifier");
2338            }
2339
2340            requiredVerifier = packageName;
2341        }
2342
2343        return requiredVerifier;
2344    }
2345
2346    private String getRequiredInstallerLPr() {
2347        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2348        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2349        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2350
2351        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2352                PACKAGE_MIME_TYPE, 0, 0);
2353
2354        String requiredInstaller = null;
2355
2356        final int N = installers.size();
2357        for (int i = 0; i < N; i++) {
2358            final ResolveInfo info = installers.get(i);
2359            final String packageName = info.activityInfo.packageName;
2360
2361            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2362                continue;
2363            }
2364
2365            if (requiredInstaller != null) {
2366                throw new RuntimeException("There must be one required installer");
2367            }
2368
2369            requiredInstaller = packageName;
2370        }
2371
2372        if (requiredInstaller == null) {
2373            throw new RuntimeException("There must be one required installer");
2374        }
2375
2376        return requiredInstaller;
2377    }
2378
2379    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2380        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2381        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2382                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2383
2384        ComponentName verifierComponentName = null;
2385
2386        int priority = -1000;
2387        final int N = receivers.size();
2388        for (int i = 0; i < N; i++) {
2389            final ResolveInfo info = receivers.get(i);
2390
2391            if (info.activityInfo == null) {
2392                continue;
2393            }
2394
2395            final String packageName = info.activityInfo.packageName;
2396
2397            final PackageSetting ps = mSettings.mPackages.get(packageName);
2398            if (ps == null) {
2399                continue;
2400            }
2401
2402            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2403                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2404                continue;
2405            }
2406
2407            // Select the IntentFilterVerifier with the highest priority
2408            if (priority < info.priority) {
2409                priority = info.priority;
2410                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2411                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2412                        + verifierComponentName + " with priority: " + info.priority);
2413            }
2414        }
2415
2416        return verifierComponentName;
2417    }
2418
2419    private void primeDomainVerificationsLPw(int userId) {
2420        if (DEBUG_DOMAIN_VERIFICATION) {
2421            Slog.d(TAG, "Priming domain verifications in user " + userId);
2422        }
2423
2424        SystemConfig systemConfig = SystemConfig.getInstance();
2425        ArraySet<String> packages = systemConfig.getLinkedApps();
2426        ArraySet<String> domains = new ArraySet<String>();
2427
2428        for (String packageName : packages) {
2429            PackageParser.Package pkg = mPackages.get(packageName);
2430            if (pkg != null) {
2431                if (!pkg.isSystemApp()) {
2432                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2433                    continue;
2434                }
2435
2436                domains.clear();
2437                for (PackageParser.Activity a : pkg.activities) {
2438                    for (ActivityIntentInfo filter : a.intents) {
2439                        if (hasValidDomains(filter)) {
2440                            domains.addAll(filter.getHostsList());
2441                        }
2442                    }
2443                }
2444
2445                if (domains.size() > 0) {
2446                    if (DEBUG_DOMAIN_VERIFICATION) {
2447                        Slog.v(TAG, "      + " + packageName);
2448                    }
2449                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2450                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2451                    // and then 'always' in the per-user state actually used for intent resolution.
2452                    final IntentFilterVerificationInfo ivi;
2453                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2454                            new ArrayList<String>(domains));
2455                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2456                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2457                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2458                } else {
2459                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2460                            + "' does not handle web links");
2461                }
2462            } else {
2463                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2464            }
2465        }
2466
2467        scheduleWritePackageRestrictionsLocked(userId);
2468        scheduleWriteSettingsLocked();
2469    }
2470
2471    private void applyFactoryDefaultBrowserLPw(int userId) {
2472        // The default browser app's package name is stored in a string resource,
2473        // with a product-specific overlay used for vendor customization.
2474        String browserPkg = mContext.getResources().getString(
2475                com.android.internal.R.string.default_browser);
2476        if (!TextUtils.isEmpty(browserPkg)) {
2477            // non-empty string => required to be a known package
2478            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2479            if (ps == null) {
2480                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2481                browserPkg = null;
2482            } else {
2483                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2484            }
2485        }
2486
2487        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2488        // default.  If there's more than one, just leave everything alone.
2489        if (browserPkg == null) {
2490            calculateDefaultBrowserLPw(userId);
2491        }
2492    }
2493
2494    private void calculateDefaultBrowserLPw(int userId) {
2495        List<String> allBrowsers = resolveAllBrowserApps(userId);
2496        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2497        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2498    }
2499
2500    private List<String> resolveAllBrowserApps(int userId) {
2501        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2502        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2503                PackageManager.MATCH_ALL, userId);
2504
2505        final int count = list.size();
2506        List<String> result = new ArrayList<String>(count);
2507        for (int i=0; i<count; i++) {
2508            ResolveInfo info = list.get(i);
2509            if (info.activityInfo == null
2510                    || !info.handleAllWebDataURI
2511                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2512                    || result.contains(info.activityInfo.packageName)) {
2513                continue;
2514            }
2515            result.add(info.activityInfo.packageName);
2516        }
2517
2518        return result;
2519    }
2520
2521    private boolean packageIsBrowser(String packageName, int userId) {
2522        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2523                PackageManager.MATCH_ALL, userId);
2524        final int N = list.size();
2525        for (int i = 0; i < N; i++) {
2526            ResolveInfo info = list.get(i);
2527            if (packageName.equals(info.activityInfo.packageName)) {
2528                return true;
2529            }
2530        }
2531        return false;
2532    }
2533
2534    private void checkDefaultBrowser() {
2535        final int myUserId = UserHandle.myUserId();
2536        final String packageName = getDefaultBrowserPackageName(myUserId);
2537        if (packageName != null) {
2538            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2539            if (info == null) {
2540                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2541                synchronized (mPackages) {
2542                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2543                }
2544            }
2545        }
2546    }
2547
2548    @Override
2549    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2550            throws RemoteException {
2551        try {
2552            return super.onTransact(code, data, reply, flags);
2553        } catch (RuntimeException e) {
2554            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2555                Slog.wtf(TAG, "Package Manager Crash", e);
2556            }
2557            throw e;
2558        }
2559    }
2560
2561    void cleanupInstallFailedPackage(PackageSetting ps) {
2562        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2563
2564        removeDataDirsLI(ps.volumeUuid, ps.name);
2565        if (ps.codePath != null) {
2566            if (ps.codePath.isDirectory()) {
2567                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2568            } else {
2569                ps.codePath.delete();
2570            }
2571        }
2572        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2573            if (ps.resourcePath.isDirectory()) {
2574                FileUtils.deleteContents(ps.resourcePath);
2575            }
2576            ps.resourcePath.delete();
2577        }
2578        mSettings.removePackageLPw(ps.name);
2579    }
2580
2581    static int[] appendInts(int[] cur, int[] add) {
2582        if (add == null) return cur;
2583        if (cur == null) return add;
2584        final int N = add.length;
2585        for (int i=0; i<N; i++) {
2586            cur = appendInt(cur, add[i]);
2587        }
2588        return cur;
2589    }
2590
2591    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2592        if (!sUserManager.exists(userId)) return null;
2593        final PackageSetting ps = (PackageSetting) p.mExtras;
2594        if (ps == null) {
2595            return null;
2596        }
2597
2598        final PermissionsState permissionsState = ps.getPermissionsState();
2599
2600        final int[] gids = permissionsState.computeGids(userId);
2601        final Set<String> permissions = permissionsState.getPermissions(userId);
2602        final PackageUserState state = ps.readUserState(userId);
2603
2604        return PackageParser.generatePackageInfo(p, gids, flags,
2605                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2606    }
2607
2608    @Override
2609    public boolean isPackageFrozen(String packageName) {
2610        synchronized (mPackages) {
2611            final PackageSetting ps = mSettings.mPackages.get(packageName);
2612            if (ps != null) {
2613                return ps.frozen;
2614            }
2615        }
2616        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2617        return true;
2618    }
2619
2620    @Override
2621    public boolean isPackageAvailable(String packageName, int userId) {
2622        if (!sUserManager.exists(userId)) return false;
2623        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2624        synchronized (mPackages) {
2625            PackageParser.Package p = mPackages.get(packageName);
2626            if (p != null) {
2627                final PackageSetting ps = (PackageSetting) p.mExtras;
2628                if (ps != null) {
2629                    final PackageUserState state = ps.readUserState(userId);
2630                    if (state != null) {
2631                        return PackageParser.isAvailable(state);
2632                    }
2633                }
2634            }
2635        }
2636        return false;
2637    }
2638
2639    @Override
2640    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2641        if (!sUserManager.exists(userId)) return null;
2642        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2643        // reader
2644        synchronized (mPackages) {
2645            PackageParser.Package p = mPackages.get(packageName);
2646            if (DEBUG_PACKAGE_INFO)
2647                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2648            if (p != null) {
2649                return generatePackageInfo(p, flags, userId);
2650            }
2651            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2652                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2653            }
2654        }
2655        return null;
2656    }
2657
2658    @Override
2659    public String[] currentToCanonicalPackageNames(String[] names) {
2660        String[] out = new String[names.length];
2661        // reader
2662        synchronized (mPackages) {
2663            for (int i=names.length-1; i>=0; i--) {
2664                PackageSetting ps = mSettings.mPackages.get(names[i]);
2665                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2666            }
2667        }
2668        return out;
2669    }
2670
2671    @Override
2672    public String[] canonicalToCurrentPackageNames(String[] names) {
2673        String[] out = new String[names.length];
2674        // reader
2675        synchronized (mPackages) {
2676            for (int i=names.length-1; i>=0; i--) {
2677                String cur = mSettings.mRenamedPackages.get(names[i]);
2678                out[i] = cur != null ? cur : names[i];
2679            }
2680        }
2681        return out;
2682    }
2683
2684    @Override
2685    public int getPackageUid(String packageName, int userId) {
2686        if (!sUserManager.exists(userId)) return -1;
2687        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2688
2689        // reader
2690        synchronized (mPackages) {
2691            PackageParser.Package p = mPackages.get(packageName);
2692            if(p != null) {
2693                return UserHandle.getUid(userId, p.applicationInfo.uid);
2694            }
2695            PackageSetting ps = mSettings.mPackages.get(packageName);
2696            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2697                return -1;
2698            }
2699            p = ps.pkg;
2700            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2701        }
2702    }
2703
2704    @Override
2705    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2706        if (!sUserManager.exists(userId)) {
2707            return null;
2708        }
2709
2710        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2711                "getPackageGids");
2712
2713        // reader
2714        synchronized (mPackages) {
2715            PackageParser.Package p = mPackages.get(packageName);
2716            if (DEBUG_PACKAGE_INFO) {
2717                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2718            }
2719            if (p != null) {
2720                PackageSetting ps = (PackageSetting) p.mExtras;
2721                return ps.getPermissionsState().computeGids(userId);
2722            }
2723        }
2724
2725        return null;
2726    }
2727
2728    @Override
2729    public int getMountExternalMode(int uid) {
2730        if (Process.isIsolated(uid)) {
2731            return Zygote.MOUNT_EXTERNAL_NONE;
2732        } else {
2733            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2734                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2735            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2736                return Zygote.MOUNT_EXTERNAL_WRITE;
2737            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2738                return Zygote.MOUNT_EXTERNAL_READ;
2739            } else {
2740                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2741            }
2742        }
2743    }
2744
2745    static PermissionInfo generatePermissionInfo(
2746            BasePermission bp, int flags) {
2747        if (bp.perm != null) {
2748            return PackageParser.generatePermissionInfo(bp.perm, flags);
2749        }
2750        PermissionInfo pi = new PermissionInfo();
2751        pi.name = bp.name;
2752        pi.packageName = bp.sourcePackage;
2753        pi.nonLocalizedLabel = bp.name;
2754        pi.protectionLevel = bp.protectionLevel;
2755        return pi;
2756    }
2757
2758    @Override
2759    public PermissionInfo getPermissionInfo(String name, int flags) {
2760        // reader
2761        synchronized (mPackages) {
2762            final BasePermission p = mSettings.mPermissions.get(name);
2763            if (p != null) {
2764                return generatePermissionInfo(p, flags);
2765            }
2766            return null;
2767        }
2768    }
2769
2770    @Override
2771    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2772        // reader
2773        synchronized (mPackages) {
2774            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2775            for (BasePermission p : mSettings.mPermissions.values()) {
2776                if (group == null) {
2777                    if (p.perm == null || p.perm.info.group == null) {
2778                        out.add(generatePermissionInfo(p, flags));
2779                    }
2780                } else {
2781                    if (p.perm != null && group.equals(p.perm.info.group)) {
2782                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2783                    }
2784                }
2785            }
2786
2787            if (out.size() > 0) {
2788                return out;
2789            }
2790            return mPermissionGroups.containsKey(group) ? out : null;
2791        }
2792    }
2793
2794    @Override
2795    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2796        // reader
2797        synchronized (mPackages) {
2798            return PackageParser.generatePermissionGroupInfo(
2799                    mPermissionGroups.get(name), flags);
2800        }
2801    }
2802
2803    @Override
2804    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2805        // reader
2806        synchronized (mPackages) {
2807            final int N = mPermissionGroups.size();
2808            ArrayList<PermissionGroupInfo> out
2809                    = new ArrayList<PermissionGroupInfo>(N);
2810            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2811                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2812            }
2813            return out;
2814        }
2815    }
2816
2817    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2818            int userId) {
2819        if (!sUserManager.exists(userId)) return null;
2820        PackageSetting ps = mSettings.mPackages.get(packageName);
2821        if (ps != null) {
2822            if (ps.pkg == null) {
2823                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2824                        flags, userId);
2825                if (pInfo != null) {
2826                    return pInfo.applicationInfo;
2827                }
2828                return null;
2829            }
2830            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2831                    ps.readUserState(userId), userId);
2832        }
2833        return null;
2834    }
2835
2836    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2837            int userId) {
2838        if (!sUserManager.exists(userId)) return null;
2839        PackageSetting ps = mSettings.mPackages.get(packageName);
2840        if (ps != null) {
2841            PackageParser.Package pkg = ps.pkg;
2842            if (pkg == null) {
2843                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2844                    return null;
2845                }
2846                // Only data remains, so we aren't worried about code paths
2847                pkg = new PackageParser.Package(packageName);
2848                pkg.applicationInfo.packageName = packageName;
2849                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2850                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2851                pkg.applicationInfo.dataDir = Environment
2852                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2853                        .getAbsolutePath();
2854                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2855                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2856            }
2857            return generatePackageInfo(pkg, flags, userId);
2858        }
2859        return null;
2860    }
2861
2862    @Override
2863    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2864        if (!sUserManager.exists(userId)) return null;
2865        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2866        // writer
2867        synchronized (mPackages) {
2868            PackageParser.Package p = mPackages.get(packageName);
2869            if (DEBUG_PACKAGE_INFO) Log.v(
2870                    TAG, "getApplicationInfo " + packageName
2871                    + ": " + p);
2872            if (p != null) {
2873                PackageSetting ps = mSettings.mPackages.get(packageName);
2874                if (ps == null) return null;
2875                // Note: isEnabledLP() does not apply here - always return info
2876                return PackageParser.generateApplicationInfo(
2877                        p, flags, ps.readUserState(userId), userId);
2878            }
2879            if ("android".equals(packageName)||"system".equals(packageName)) {
2880                return mAndroidApplication;
2881            }
2882            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2883                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2884            }
2885        }
2886        return null;
2887    }
2888
2889    @Override
2890    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2891            final IPackageDataObserver observer) {
2892        mContext.enforceCallingOrSelfPermission(
2893                android.Manifest.permission.CLEAR_APP_CACHE, null);
2894        // Queue up an async operation since clearing cache may take a little while.
2895        mHandler.post(new Runnable() {
2896            public void run() {
2897                mHandler.removeCallbacks(this);
2898                int retCode = -1;
2899                synchronized (mInstallLock) {
2900                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2901                    if (retCode < 0) {
2902                        Slog.w(TAG, "Couldn't clear application caches");
2903                    }
2904                }
2905                if (observer != null) {
2906                    try {
2907                        observer.onRemoveCompleted(null, (retCode >= 0));
2908                    } catch (RemoteException e) {
2909                        Slog.w(TAG, "RemoveException when invoking call back");
2910                    }
2911                }
2912            }
2913        });
2914    }
2915
2916    @Override
2917    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2918            final IntentSender pi) {
2919        mContext.enforceCallingOrSelfPermission(
2920                android.Manifest.permission.CLEAR_APP_CACHE, null);
2921        // Queue up an async operation since clearing cache may take a little while.
2922        mHandler.post(new Runnable() {
2923            public void run() {
2924                mHandler.removeCallbacks(this);
2925                int retCode = -1;
2926                synchronized (mInstallLock) {
2927                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2928                    if (retCode < 0) {
2929                        Slog.w(TAG, "Couldn't clear application caches");
2930                    }
2931                }
2932                if(pi != null) {
2933                    try {
2934                        // Callback via pending intent
2935                        int code = (retCode >= 0) ? 1 : 0;
2936                        pi.sendIntent(null, code, null,
2937                                null, null);
2938                    } catch (SendIntentException e1) {
2939                        Slog.i(TAG, "Failed to send pending intent");
2940                    }
2941                }
2942            }
2943        });
2944    }
2945
2946    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2947        synchronized (mInstallLock) {
2948            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2949                throw new IOException("Failed to free enough space");
2950            }
2951        }
2952    }
2953
2954    @Override
2955    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2956        if (!sUserManager.exists(userId)) return null;
2957        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2958        synchronized (mPackages) {
2959            PackageParser.Activity a = mActivities.mActivities.get(component);
2960
2961            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2962            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2963                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2964                if (ps == null) return null;
2965                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2966                        userId);
2967            }
2968            if (mResolveComponentName.equals(component)) {
2969                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2970                        new PackageUserState(), userId);
2971            }
2972        }
2973        return null;
2974    }
2975
2976    @Override
2977    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2978            String resolvedType) {
2979        synchronized (mPackages) {
2980            PackageParser.Activity a = mActivities.mActivities.get(component);
2981            if (a == null) {
2982                return false;
2983            }
2984            for (int i=0; i<a.intents.size(); i++) {
2985                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2986                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2987                    return true;
2988                }
2989            }
2990            return false;
2991        }
2992    }
2993
2994    @Override
2995    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2996        if (!sUserManager.exists(userId)) return null;
2997        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2998        synchronized (mPackages) {
2999            PackageParser.Activity a = mReceivers.mActivities.get(component);
3000            if (DEBUG_PACKAGE_INFO) Log.v(
3001                TAG, "getReceiverInfo " + component + ": " + a);
3002            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3003                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3004                if (ps == null) return null;
3005                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3006                        userId);
3007            }
3008        }
3009        return null;
3010    }
3011
3012    @Override
3013    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3014        if (!sUserManager.exists(userId)) return null;
3015        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3016        synchronized (mPackages) {
3017            PackageParser.Service s = mServices.mServices.get(component);
3018            if (DEBUG_PACKAGE_INFO) Log.v(
3019                TAG, "getServiceInfo " + component + ": " + s);
3020            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3021                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3022                if (ps == null) return null;
3023                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3024                        userId);
3025            }
3026        }
3027        return null;
3028    }
3029
3030    @Override
3031    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3032        if (!sUserManager.exists(userId)) return null;
3033        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3034        synchronized (mPackages) {
3035            PackageParser.Provider p = mProviders.mProviders.get(component);
3036            if (DEBUG_PACKAGE_INFO) Log.v(
3037                TAG, "getProviderInfo " + component + ": " + p);
3038            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3039                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3040                if (ps == null) return null;
3041                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3042                        userId);
3043            }
3044        }
3045        return null;
3046    }
3047
3048    @Override
3049    public String[] getSystemSharedLibraryNames() {
3050        Set<String> libSet;
3051        synchronized (mPackages) {
3052            libSet = mSharedLibraries.keySet();
3053            int size = libSet.size();
3054            if (size > 0) {
3055                String[] libs = new String[size];
3056                libSet.toArray(libs);
3057                return libs;
3058            }
3059        }
3060        return null;
3061    }
3062
3063    /**
3064     * @hide
3065     */
3066    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3067        synchronized (mPackages) {
3068            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3069            if (lib != null && lib.apk != null) {
3070                return mPackages.get(lib.apk);
3071            }
3072        }
3073        return null;
3074    }
3075
3076    @Override
3077    public FeatureInfo[] getSystemAvailableFeatures() {
3078        Collection<FeatureInfo> featSet;
3079        synchronized (mPackages) {
3080            featSet = mAvailableFeatures.values();
3081            int size = featSet.size();
3082            if (size > 0) {
3083                FeatureInfo[] features = new FeatureInfo[size+1];
3084                featSet.toArray(features);
3085                FeatureInfo fi = new FeatureInfo();
3086                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3087                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3088                features[size] = fi;
3089                return features;
3090            }
3091        }
3092        return null;
3093    }
3094
3095    @Override
3096    public boolean hasSystemFeature(String name) {
3097        synchronized (mPackages) {
3098            return mAvailableFeatures.containsKey(name);
3099        }
3100    }
3101
3102    private void checkValidCaller(int uid, int userId) {
3103        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3104            return;
3105
3106        throw new SecurityException("Caller uid=" + uid
3107                + " is not privileged to communicate with user=" + userId);
3108    }
3109
3110    @Override
3111    public int checkPermission(String permName, String pkgName, int userId) {
3112        if (!sUserManager.exists(userId)) {
3113            return PackageManager.PERMISSION_DENIED;
3114        }
3115
3116        synchronized (mPackages) {
3117            final PackageParser.Package p = mPackages.get(pkgName);
3118            if (p != null && p.mExtras != null) {
3119                final PackageSetting ps = (PackageSetting) p.mExtras;
3120                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3121                    return PackageManager.PERMISSION_GRANTED;
3122                }
3123            }
3124        }
3125
3126        return PackageManager.PERMISSION_DENIED;
3127    }
3128
3129    @Override
3130    public int checkUidPermission(String permName, int uid) {
3131        final int userId = UserHandle.getUserId(uid);
3132
3133        if (!sUserManager.exists(userId)) {
3134            return PackageManager.PERMISSION_DENIED;
3135        }
3136
3137        synchronized (mPackages) {
3138            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3139            if (obj != null) {
3140                final SettingBase ps = (SettingBase) obj;
3141                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3142                    return PackageManager.PERMISSION_GRANTED;
3143                }
3144            } else {
3145                ArraySet<String> perms = mSystemPermissions.get(uid);
3146                if (perms != null && perms.contains(permName)) {
3147                    return PackageManager.PERMISSION_GRANTED;
3148                }
3149            }
3150        }
3151
3152        return PackageManager.PERMISSION_DENIED;
3153    }
3154
3155    @Override
3156    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3157        if (UserHandle.getCallingUserId() != userId) {
3158            mContext.enforceCallingPermission(
3159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3160                    "isPermissionRevokedByPolicy for user " + userId);
3161        }
3162
3163        if (checkPermission(permission, packageName, userId)
3164                == PackageManager.PERMISSION_GRANTED) {
3165            return false;
3166        }
3167
3168        final long identity = Binder.clearCallingIdentity();
3169        try {
3170            final int flags = getPermissionFlags(permission, packageName, userId);
3171            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3172        } finally {
3173            Binder.restoreCallingIdentity(identity);
3174        }
3175    }
3176
3177    /**
3178     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3179     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3180     * @param checkShell TODO(yamasani):
3181     * @param message the message to log on security exception
3182     */
3183    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3184            boolean checkShell, String message) {
3185        if (userId < 0) {
3186            throw new IllegalArgumentException("Invalid userId " + userId);
3187        }
3188        if (checkShell) {
3189            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3190        }
3191        if (userId == UserHandle.getUserId(callingUid)) return;
3192        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3193            if (requireFullPermission) {
3194                mContext.enforceCallingOrSelfPermission(
3195                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3196            } else {
3197                try {
3198                    mContext.enforceCallingOrSelfPermission(
3199                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3200                } catch (SecurityException se) {
3201                    mContext.enforceCallingOrSelfPermission(
3202                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3203                }
3204            }
3205        }
3206    }
3207
3208    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3209        if (callingUid == Process.SHELL_UID) {
3210            if (userHandle >= 0
3211                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3212                throw new SecurityException("Shell does not have permission to access user "
3213                        + userHandle);
3214            } else if (userHandle < 0) {
3215                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3216                        + Debug.getCallers(3));
3217            }
3218        }
3219    }
3220
3221    private BasePermission findPermissionTreeLP(String permName) {
3222        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3223            if (permName.startsWith(bp.name) &&
3224                    permName.length() > bp.name.length() &&
3225                    permName.charAt(bp.name.length()) == '.') {
3226                return bp;
3227            }
3228        }
3229        return null;
3230    }
3231
3232    private BasePermission checkPermissionTreeLP(String permName) {
3233        if (permName != null) {
3234            BasePermission bp = findPermissionTreeLP(permName);
3235            if (bp != null) {
3236                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3237                    return bp;
3238                }
3239                throw new SecurityException("Calling uid "
3240                        + Binder.getCallingUid()
3241                        + " is not allowed to add to permission tree "
3242                        + bp.name + " owned by uid " + bp.uid);
3243            }
3244        }
3245        throw new SecurityException("No permission tree found for " + permName);
3246    }
3247
3248    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3249        if (s1 == null) {
3250            return s2 == null;
3251        }
3252        if (s2 == null) {
3253            return false;
3254        }
3255        if (s1.getClass() != s2.getClass()) {
3256            return false;
3257        }
3258        return s1.equals(s2);
3259    }
3260
3261    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3262        if (pi1.icon != pi2.icon) return false;
3263        if (pi1.logo != pi2.logo) return false;
3264        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3265        if (!compareStrings(pi1.name, pi2.name)) return false;
3266        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3267        // We'll take care of setting this one.
3268        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3269        // These are not currently stored in settings.
3270        //if (!compareStrings(pi1.group, pi2.group)) return false;
3271        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3272        //if (pi1.labelRes != pi2.labelRes) return false;
3273        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3274        return true;
3275    }
3276
3277    int permissionInfoFootprint(PermissionInfo info) {
3278        int size = info.name.length();
3279        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3280        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3281        return size;
3282    }
3283
3284    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3285        int size = 0;
3286        for (BasePermission perm : mSettings.mPermissions.values()) {
3287            if (perm.uid == tree.uid) {
3288                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3289            }
3290        }
3291        return size;
3292    }
3293
3294    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3295        // We calculate the max size of permissions defined by this uid and throw
3296        // if that plus the size of 'info' would exceed our stated maximum.
3297        if (tree.uid != Process.SYSTEM_UID) {
3298            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3299            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3300                throw new SecurityException("Permission tree size cap exceeded");
3301            }
3302        }
3303    }
3304
3305    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3306        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3307            throw new SecurityException("Label must be specified in permission");
3308        }
3309        BasePermission tree = checkPermissionTreeLP(info.name);
3310        BasePermission bp = mSettings.mPermissions.get(info.name);
3311        boolean added = bp == null;
3312        boolean changed = true;
3313        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3314        if (added) {
3315            enforcePermissionCapLocked(info, tree);
3316            bp = new BasePermission(info.name, tree.sourcePackage,
3317                    BasePermission.TYPE_DYNAMIC);
3318        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3319            throw new SecurityException(
3320                    "Not allowed to modify non-dynamic permission "
3321                    + info.name);
3322        } else {
3323            if (bp.protectionLevel == fixedLevel
3324                    && bp.perm.owner.equals(tree.perm.owner)
3325                    && bp.uid == tree.uid
3326                    && comparePermissionInfos(bp.perm.info, info)) {
3327                changed = false;
3328            }
3329        }
3330        bp.protectionLevel = fixedLevel;
3331        info = new PermissionInfo(info);
3332        info.protectionLevel = fixedLevel;
3333        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3334        bp.perm.info.packageName = tree.perm.info.packageName;
3335        bp.uid = tree.uid;
3336        if (added) {
3337            mSettings.mPermissions.put(info.name, bp);
3338        }
3339        if (changed) {
3340            if (!async) {
3341                mSettings.writeLPr();
3342            } else {
3343                scheduleWriteSettingsLocked();
3344            }
3345        }
3346        return added;
3347    }
3348
3349    @Override
3350    public boolean addPermission(PermissionInfo info) {
3351        synchronized (mPackages) {
3352            return addPermissionLocked(info, false);
3353        }
3354    }
3355
3356    @Override
3357    public boolean addPermissionAsync(PermissionInfo info) {
3358        synchronized (mPackages) {
3359            return addPermissionLocked(info, true);
3360        }
3361    }
3362
3363    @Override
3364    public void removePermission(String name) {
3365        synchronized (mPackages) {
3366            checkPermissionTreeLP(name);
3367            BasePermission bp = mSettings.mPermissions.get(name);
3368            if (bp != null) {
3369                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3370                    throw new SecurityException(
3371                            "Not allowed to modify non-dynamic permission "
3372                            + name);
3373                }
3374                mSettings.mPermissions.remove(name);
3375                mSettings.writeLPr();
3376            }
3377        }
3378    }
3379
3380    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3381            BasePermission bp) {
3382        int index = pkg.requestedPermissions.indexOf(bp.name);
3383        if (index == -1) {
3384            throw new SecurityException("Package " + pkg.packageName
3385                    + " has not requested permission " + bp.name);
3386        }
3387        if (!bp.isRuntime()) {
3388            throw new SecurityException("Permission " + bp.name
3389                    + " is not a changeable permission type");
3390        }
3391    }
3392
3393    @Override
3394    public void grantRuntimePermission(String packageName, String name, final int userId) {
3395        if (!sUserManager.exists(userId)) {
3396            Log.e(TAG, "No such user:" + userId);
3397            return;
3398        }
3399
3400        mContext.enforceCallingOrSelfPermission(
3401                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3402                "grantRuntimePermission");
3403
3404        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3405                "grantRuntimePermission");
3406
3407        final int uid;
3408        final SettingBase sb;
3409
3410        synchronized (mPackages) {
3411            final PackageParser.Package pkg = mPackages.get(packageName);
3412            if (pkg == null) {
3413                throw new IllegalArgumentException("Unknown package: " + packageName);
3414            }
3415
3416            final BasePermission bp = mSettings.mPermissions.get(name);
3417            if (bp == null) {
3418                throw new IllegalArgumentException("Unknown permission: " + name);
3419            }
3420
3421            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3422
3423            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3424            sb = (SettingBase) pkg.mExtras;
3425            if (sb == null) {
3426                throw new IllegalArgumentException("Unknown package: " + packageName);
3427            }
3428
3429            final PermissionsState permissionsState = sb.getPermissionsState();
3430
3431            final int flags = permissionsState.getPermissionFlags(name, userId);
3432            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3433                throw new SecurityException("Cannot grant system fixed permission: "
3434                        + name + " for package: " + packageName);
3435            }
3436
3437            final int result = permissionsState.grantRuntimePermission(bp, userId);
3438            switch (result) {
3439                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3440                    return;
3441                }
3442
3443                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3444                    mHandler.post(new Runnable() {
3445                        @Override
3446                        public void run() {
3447                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3448                        }
3449                    });
3450                } break;
3451            }
3452
3453            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3454
3455            // Not critical if that is lost - app has to request again.
3456            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3457        }
3458
3459        // Only need to do this if user is initialized. Otherwise it's a new user
3460        // and there are no processes running as the user yet and there's no need
3461        // to make an expensive call to remount processes for the changed permissions.
3462        if (READ_EXTERNAL_STORAGE.equals(name)
3463                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3464            final long token = Binder.clearCallingIdentity();
3465            try {
3466                if (sUserManager.isInitialized(userId)) {
3467                    final StorageManager storage = mContext.getSystemService(StorageManager.class);
3468                    storage.remountUid(uid);
3469                }
3470            } finally {
3471                Binder.restoreCallingIdentity(token);
3472            }
3473        }
3474    }
3475
3476    @Override
3477    public void revokeRuntimePermission(String packageName, String name, int userId) {
3478        if (!sUserManager.exists(userId)) {
3479            Log.e(TAG, "No such user:" + userId);
3480            return;
3481        }
3482
3483        mContext.enforceCallingOrSelfPermission(
3484                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3485                "revokeRuntimePermission");
3486
3487        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3488                "revokeRuntimePermission");
3489
3490        final SettingBase sb;
3491
3492        synchronized (mPackages) {
3493            final PackageParser.Package pkg = mPackages.get(packageName);
3494            if (pkg == null) {
3495                throw new IllegalArgumentException("Unknown package: " + packageName);
3496            }
3497
3498            final BasePermission bp = mSettings.mPermissions.get(name);
3499            if (bp == null) {
3500                throw new IllegalArgumentException("Unknown permission: " + name);
3501            }
3502
3503            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3504
3505            sb = (SettingBase) pkg.mExtras;
3506            if (sb == null) {
3507                throw new IllegalArgumentException("Unknown package: " + packageName);
3508            }
3509
3510            final PermissionsState permissionsState = sb.getPermissionsState();
3511
3512            final int flags = permissionsState.getPermissionFlags(name, userId);
3513            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3514                throw new SecurityException("Cannot revoke system fixed permission: "
3515                        + name + " for package: " + packageName);
3516            }
3517
3518            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3519                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3520                return;
3521            }
3522
3523            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3524
3525            // Critical, after this call app should never have the permission.
3526            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3527        }
3528
3529        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3530    }
3531
3532    @Override
3533    public void resetRuntimePermissions() {
3534        mContext.enforceCallingOrSelfPermission(
3535                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3536                "revokeRuntimePermission");
3537
3538        int callingUid = Binder.getCallingUid();
3539        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3540            mContext.enforceCallingOrSelfPermission(
3541                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3542                    "resetRuntimePermissions");
3543        }
3544
3545        final int[] userIds;
3546
3547        synchronized (mPackages) {
3548            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3549            final int userCount = UserManagerService.getInstance().getUserIds().length;
3550            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3551        }
3552
3553        for (int userId : userIds) {
3554            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3555        }
3556    }
3557
3558    @Override
3559    public int getPermissionFlags(String name, String packageName, int userId) {
3560        if (!sUserManager.exists(userId)) {
3561            return 0;
3562        }
3563
3564        mContext.enforceCallingOrSelfPermission(
3565                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3566                "getPermissionFlags");
3567
3568        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3569                "getPermissionFlags");
3570
3571        synchronized (mPackages) {
3572            final PackageParser.Package pkg = mPackages.get(packageName);
3573            if (pkg == null) {
3574                throw new IllegalArgumentException("Unknown package: " + packageName);
3575            }
3576
3577            final BasePermission bp = mSettings.mPermissions.get(name);
3578            if (bp == null) {
3579                throw new IllegalArgumentException("Unknown permission: " + name);
3580            }
3581
3582            SettingBase sb = (SettingBase) pkg.mExtras;
3583            if (sb == null) {
3584                throw new IllegalArgumentException("Unknown package: " + packageName);
3585            }
3586
3587            PermissionsState permissionsState = sb.getPermissionsState();
3588            return permissionsState.getPermissionFlags(name, userId);
3589        }
3590    }
3591
3592    @Override
3593    public void updatePermissionFlags(String name, String packageName, int flagMask,
3594            int flagValues, int userId) {
3595        if (!sUserManager.exists(userId)) {
3596            return;
3597        }
3598
3599        mContext.enforceCallingOrSelfPermission(
3600                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3601                "updatePermissionFlags");
3602
3603        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3604                "updatePermissionFlags");
3605
3606        // Only the system can change system fixed flags.
3607        if (getCallingUid() != Process.SYSTEM_UID) {
3608            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3609            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3610        }
3611
3612        synchronized (mPackages) {
3613            final PackageParser.Package pkg = mPackages.get(packageName);
3614            if (pkg == null) {
3615                throw new IllegalArgumentException("Unknown package: " + packageName);
3616            }
3617
3618            final BasePermission bp = mSettings.mPermissions.get(name);
3619            if (bp == null) {
3620                throw new IllegalArgumentException("Unknown permission: " + name);
3621            }
3622
3623            SettingBase sb = (SettingBase) pkg.mExtras;
3624            if (sb == null) {
3625                throw new IllegalArgumentException("Unknown package: " + packageName);
3626            }
3627
3628            PermissionsState permissionsState = sb.getPermissionsState();
3629
3630            // Only the package manager can change flags for system component permissions.
3631            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3632            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3633                return;
3634            }
3635
3636            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3637
3638            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3639                // Install and runtime permissions are stored in different places,
3640                // so figure out what permission changed and persist the change.
3641                if (permissionsState.getInstallPermissionState(name) != null) {
3642                    scheduleWriteSettingsLocked();
3643                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3644                        || hadState) {
3645                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3646                }
3647            }
3648        }
3649    }
3650
3651    /**
3652     * Update the permission flags for all packages and runtime permissions of a user in order
3653     * to allow device or profile owner to remove POLICY_FIXED.
3654     */
3655    @Override
3656    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3657        if (!sUserManager.exists(userId)) {
3658            return;
3659        }
3660
3661        mContext.enforceCallingOrSelfPermission(
3662                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3663                "updatePermissionFlagsForAllApps");
3664
3665        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3666                "updatePermissionFlagsForAllApps");
3667
3668        // Only the system can change system fixed flags.
3669        if (getCallingUid() != Process.SYSTEM_UID) {
3670            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3671            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3672        }
3673
3674        synchronized (mPackages) {
3675            boolean changed = false;
3676            final int packageCount = mPackages.size();
3677            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3678                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3679                SettingBase sb = (SettingBase) pkg.mExtras;
3680                if (sb == null) {
3681                    continue;
3682                }
3683                PermissionsState permissionsState = sb.getPermissionsState();
3684                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3685                        userId, flagMask, flagValues);
3686            }
3687            if (changed) {
3688                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3689            }
3690        }
3691    }
3692
3693    @Override
3694    public boolean shouldShowRequestPermissionRationale(String permissionName,
3695            String packageName, int userId) {
3696        if (UserHandle.getCallingUserId() != userId) {
3697            mContext.enforceCallingPermission(
3698                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3699                    "canShowRequestPermissionRationale for user " + userId);
3700        }
3701
3702        final int uid = getPackageUid(packageName, userId);
3703        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3704            return false;
3705        }
3706
3707        if (checkPermission(permissionName, packageName, userId)
3708                == PackageManager.PERMISSION_GRANTED) {
3709            return false;
3710        }
3711
3712        final int flags;
3713
3714        final long identity = Binder.clearCallingIdentity();
3715        try {
3716            flags = getPermissionFlags(permissionName,
3717                    packageName, userId);
3718        } finally {
3719            Binder.restoreCallingIdentity(identity);
3720        }
3721
3722        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3723                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3724                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3725
3726        if ((flags & fixedFlags) != 0) {
3727            return false;
3728        }
3729
3730        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3731    }
3732
3733    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3734        BasePermission bp = mSettings.mPermissions.get(permission);
3735        if (bp == null) {
3736            throw new SecurityException("Missing " + permission + " permission");
3737        }
3738
3739        SettingBase sb = (SettingBase) pkg.mExtras;
3740        PermissionsState permissionsState = sb.getPermissionsState();
3741
3742        if (permissionsState.grantInstallPermission(bp) !=
3743                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3744            scheduleWriteSettingsLocked();
3745        }
3746    }
3747
3748    @Override
3749    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3750        mContext.enforceCallingOrSelfPermission(
3751                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3752                "addOnPermissionsChangeListener");
3753
3754        synchronized (mPackages) {
3755            mOnPermissionChangeListeners.addListenerLocked(listener);
3756        }
3757    }
3758
3759    @Override
3760    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3761        synchronized (mPackages) {
3762            mOnPermissionChangeListeners.removeListenerLocked(listener);
3763        }
3764    }
3765
3766    @Override
3767    public boolean isProtectedBroadcast(String actionName) {
3768        synchronized (mPackages) {
3769            return mProtectedBroadcasts.contains(actionName);
3770        }
3771    }
3772
3773    @Override
3774    public int checkSignatures(String pkg1, String pkg2) {
3775        synchronized (mPackages) {
3776            final PackageParser.Package p1 = mPackages.get(pkg1);
3777            final PackageParser.Package p2 = mPackages.get(pkg2);
3778            if (p1 == null || p1.mExtras == null
3779                    || p2 == null || p2.mExtras == null) {
3780                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3781            }
3782            return compareSignatures(p1.mSignatures, p2.mSignatures);
3783        }
3784    }
3785
3786    @Override
3787    public int checkUidSignatures(int uid1, int uid2) {
3788        // Map to base uids.
3789        uid1 = UserHandle.getAppId(uid1);
3790        uid2 = UserHandle.getAppId(uid2);
3791        // reader
3792        synchronized (mPackages) {
3793            Signature[] s1;
3794            Signature[] s2;
3795            Object obj = mSettings.getUserIdLPr(uid1);
3796            if (obj != null) {
3797                if (obj instanceof SharedUserSetting) {
3798                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3799                } else if (obj instanceof PackageSetting) {
3800                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3801                } else {
3802                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3803                }
3804            } else {
3805                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3806            }
3807            obj = mSettings.getUserIdLPr(uid2);
3808            if (obj != null) {
3809                if (obj instanceof SharedUserSetting) {
3810                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3811                } else if (obj instanceof PackageSetting) {
3812                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3813                } else {
3814                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3815                }
3816            } else {
3817                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3818            }
3819            return compareSignatures(s1, s2);
3820        }
3821    }
3822
3823    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3824        final long identity = Binder.clearCallingIdentity();
3825        try {
3826            if (sb instanceof SharedUserSetting) {
3827                SharedUserSetting sus = (SharedUserSetting) sb;
3828                final int packageCount = sus.packages.size();
3829                for (int i = 0; i < packageCount; i++) {
3830                    PackageSetting susPs = sus.packages.valueAt(i);
3831                    if (userId == UserHandle.USER_ALL) {
3832                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3833                    } else {
3834                        final int uid = UserHandle.getUid(userId, susPs.appId);
3835                        killUid(uid, reason);
3836                    }
3837                }
3838            } else if (sb instanceof PackageSetting) {
3839                PackageSetting ps = (PackageSetting) sb;
3840                if (userId == UserHandle.USER_ALL) {
3841                    killApplication(ps.pkg.packageName, ps.appId, reason);
3842                } else {
3843                    final int uid = UserHandle.getUid(userId, ps.appId);
3844                    killUid(uid, reason);
3845                }
3846            }
3847        } finally {
3848            Binder.restoreCallingIdentity(identity);
3849        }
3850    }
3851
3852    private static void killUid(int uid, String reason) {
3853        IActivityManager am = ActivityManagerNative.getDefault();
3854        if (am != null) {
3855            try {
3856                am.killUid(uid, reason);
3857            } catch (RemoteException e) {
3858                /* ignore - same process */
3859            }
3860        }
3861    }
3862
3863    /**
3864     * Compares two sets of signatures. Returns:
3865     * <br />
3866     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3867     * <br />
3868     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3869     * <br />
3870     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3871     * <br />
3872     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3873     * <br />
3874     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3875     */
3876    static int compareSignatures(Signature[] s1, Signature[] s2) {
3877        if (s1 == null) {
3878            return s2 == null
3879                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3880                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3881        }
3882
3883        if (s2 == null) {
3884            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3885        }
3886
3887        if (s1.length != s2.length) {
3888            return PackageManager.SIGNATURE_NO_MATCH;
3889        }
3890
3891        // Since both signature sets are of size 1, we can compare without HashSets.
3892        if (s1.length == 1) {
3893            return s1[0].equals(s2[0]) ?
3894                    PackageManager.SIGNATURE_MATCH :
3895                    PackageManager.SIGNATURE_NO_MATCH;
3896        }
3897
3898        ArraySet<Signature> set1 = new ArraySet<Signature>();
3899        for (Signature sig : s1) {
3900            set1.add(sig);
3901        }
3902        ArraySet<Signature> set2 = new ArraySet<Signature>();
3903        for (Signature sig : s2) {
3904            set2.add(sig);
3905        }
3906        // Make sure s2 contains all signatures in s1.
3907        if (set1.equals(set2)) {
3908            return PackageManager.SIGNATURE_MATCH;
3909        }
3910        return PackageManager.SIGNATURE_NO_MATCH;
3911    }
3912
3913    /**
3914     * If the database version for this type of package (internal storage or
3915     * external storage) is less than the version where package signatures
3916     * were updated, return true.
3917     */
3918    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3919        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3920                DatabaseVersion.SIGNATURE_END_ENTITY))
3921                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3922                        DatabaseVersion.SIGNATURE_END_ENTITY));
3923    }
3924
3925    /**
3926     * Used for backward compatibility to make sure any packages with
3927     * certificate chains get upgraded to the new style. {@code existingSigs}
3928     * will be in the old format (since they were stored on disk from before the
3929     * system upgrade) and {@code scannedSigs} will be in the newer format.
3930     */
3931    private int compareSignaturesCompat(PackageSignatures existingSigs,
3932            PackageParser.Package scannedPkg) {
3933        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3934            return PackageManager.SIGNATURE_NO_MATCH;
3935        }
3936
3937        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3938        for (Signature sig : existingSigs.mSignatures) {
3939            existingSet.add(sig);
3940        }
3941        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3942        for (Signature sig : scannedPkg.mSignatures) {
3943            try {
3944                Signature[] chainSignatures = sig.getChainSignatures();
3945                for (Signature chainSig : chainSignatures) {
3946                    scannedCompatSet.add(chainSig);
3947                }
3948            } catch (CertificateEncodingException e) {
3949                scannedCompatSet.add(sig);
3950            }
3951        }
3952        /*
3953         * Make sure the expanded scanned set contains all signatures in the
3954         * existing one.
3955         */
3956        if (scannedCompatSet.equals(existingSet)) {
3957            // Migrate the old signatures to the new scheme.
3958            existingSigs.assignSignatures(scannedPkg.mSignatures);
3959            // The new KeySets will be re-added later in the scanning process.
3960            synchronized (mPackages) {
3961                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3962            }
3963            return PackageManager.SIGNATURE_MATCH;
3964        }
3965        return PackageManager.SIGNATURE_NO_MATCH;
3966    }
3967
3968    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3969        if (isExternal(scannedPkg)) {
3970            return mSettings.isExternalDatabaseVersionOlderThan(
3971                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3972        } else {
3973            return mSettings.isInternalDatabaseVersionOlderThan(
3974                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3975        }
3976    }
3977
3978    private int compareSignaturesRecover(PackageSignatures existingSigs,
3979            PackageParser.Package scannedPkg) {
3980        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3981            return PackageManager.SIGNATURE_NO_MATCH;
3982        }
3983
3984        String msg = null;
3985        try {
3986            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3987                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3988                        + scannedPkg.packageName);
3989                return PackageManager.SIGNATURE_MATCH;
3990            }
3991        } catch (CertificateException e) {
3992            msg = e.getMessage();
3993        }
3994
3995        logCriticalInfo(Log.INFO,
3996                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3997        return PackageManager.SIGNATURE_NO_MATCH;
3998    }
3999
4000    @Override
4001    public String[] getPackagesForUid(int uid) {
4002        uid = UserHandle.getAppId(uid);
4003        // reader
4004        synchronized (mPackages) {
4005            Object obj = mSettings.getUserIdLPr(uid);
4006            if (obj instanceof SharedUserSetting) {
4007                final SharedUserSetting sus = (SharedUserSetting) obj;
4008                final int N = sus.packages.size();
4009                final String[] res = new String[N];
4010                final Iterator<PackageSetting> it = sus.packages.iterator();
4011                int i = 0;
4012                while (it.hasNext()) {
4013                    res[i++] = it.next().name;
4014                }
4015                return res;
4016            } else if (obj instanceof PackageSetting) {
4017                final PackageSetting ps = (PackageSetting) obj;
4018                return new String[] { ps.name };
4019            }
4020        }
4021        return null;
4022    }
4023
4024    @Override
4025    public String getNameForUid(int uid) {
4026        // reader
4027        synchronized (mPackages) {
4028            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4029            if (obj instanceof SharedUserSetting) {
4030                final SharedUserSetting sus = (SharedUserSetting) obj;
4031                return sus.name + ":" + sus.userId;
4032            } else if (obj instanceof PackageSetting) {
4033                final PackageSetting ps = (PackageSetting) obj;
4034                return ps.name;
4035            }
4036        }
4037        return null;
4038    }
4039
4040    @Override
4041    public int getUidForSharedUser(String sharedUserName) {
4042        if(sharedUserName == null) {
4043            return -1;
4044        }
4045        // reader
4046        synchronized (mPackages) {
4047            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4048            if (suid == null) {
4049                return -1;
4050            }
4051            return suid.userId;
4052        }
4053    }
4054
4055    @Override
4056    public int getFlagsForUid(int uid) {
4057        synchronized (mPackages) {
4058            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4059            if (obj instanceof SharedUserSetting) {
4060                final SharedUserSetting sus = (SharedUserSetting) obj;
4061                return sus.pkgFlags;
4062            } else if (obj instanceof PackageSetting) {
4063                final PackageSetting ps = (PackageSetting) obj;
4064                return ps.pkgFlags;
4065            }
4066        }
4067        return 0;
4068    }
4069
4070    @Override
4071    public int getPrivateFlagsForUid(int uid) {
4072        synchronized (mPackages) {
4073            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4074            if (obj instanceof SharedUserSetting) {
4075                final SharedUserSetting sus = (SharedUserSetting) obj;
4076                return sus.pkgPrivateFlags;
4077            } else if (obj instanceof PackageSetting) {
4078                final PackageSetting ps = (PackageSetting) obj;
4079                return ps.pkgPrivateFlags;
4080            }
4081        }
4082        return 0;
4083    }
4084
4085    @Override
4086    public boolean isUidPrivileged(int uid) {
4087        uid = UserHandle.getAppId(uid);
4088        // reader
4089        synchronized (mPackages) {
4090            Object obj = mSettings.getUserIdLPr(uid);
4091            if (obj instanceof SharedUserSetting) {
4092                final SharedUserSetting sus = (SharedUserSetting) obj;
4093                final Iterator<PackageSetting> it = sus.packages.iterator();
4094                while (it.hasNext()) {
4095                    if (it.next().isPrivileged()) {
4096                        return true;
4097                    }
4098                }
4099            } else if (obj instanceof PackageSetting) {
4100                final PackageSetting ps = (PackageSetting) obj;
4101                return ps.isPrivileged();
4102            }
4103        }
4104        return false;
4105    }
4106
4107    @Override
4108    public String[] getAppOpPermissionPackages(String permissionName) {
4109        synchronized (mPackages) {
4110            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4111            if (pkgs == null) {
4112                return null;
4113            }
4114            return pkgs.toArray(new String[pkgs.size()]);
4115        }
4116    }
4117
4118    @Override
4119    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4120            int flags, int userId) {
4121        if (!sUserManager.exists(userId)) return null;
4122        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4123        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4124        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4125    }
4126
4127    @Override
4128    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4129            IntentFilter filter, int match, ComponentName activity) {
4130        final int userId = UserHandle.getCallingUserId();
4131        if (DEBUG_PREFERRED) {
4132            Log.v(TAG, "setLastChosenActivity intent=" + intent
4133                + " resolvedType=" + resolvedType
4134                + " flags=" + flags
4135                + " filter=" + filter
4136                + " match=" + match
4137                + " activity=" + activity);
4138            filter.dump(new PrintStreamPrinter(System.out), "    ");
4139        }
4140        intent.setComponent(null);
4141        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4142        // Find any earlier preferred or last chosen entries and nuke them
4143        findPreferredActivity(intent, resolvedType,
4144                flags, query, 0, false, true, false, userId);
4145        // Add the new activity as the last chosen for this filter
4146        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4147                "Setting last chosen");
4148    }
4149
4150    @Override
4151    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4152        final int userId = UserHandle.getCallingUserId();
4153        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4154        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4155        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4156                false, false, false, userId);
4157    }
4158
4159    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4160            int flags, List<ResolveInfo> query, int userId) {
4161        if (query != null) {
4162            final int N = query.size();
4163            if (N == 1) {
4164                return query.get(0);
4165            } else if (N > 1) {
4166                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4167                // If there is more than one activity with the same priority,
4168                // then let the user decide between them.
4169                ResolveInfo r0 = query.get(0);
4170                ResolveInfo r1 = query.get(1);
4171                if (DEBUG_INTENT_MATCHING || debug) {
4172                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4173                            + r1.activityInfo.name + "=" + r1.priority);
4174                }
4175                // If the first activity has a higher priority, or a different
4176                // default, then it is always desireable to pick it.
4177                if (r0.priority != r1.priority
4178                        || r0.preferredOrder != r1.preferredOrder
4179                        || r0.isDefault != r1.isDefault) {
4180                    return query.get(0);
4181                }
4182                // If we have saved a preference for a preferred activity for
4183                // this Intent, use that.
4184                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4185                        flags, query, r0.priority, true, false, debug, userId);
4186                if (ri != null) {
4187                    return ri;
4188                }
4189                if (userId != 0) {
4190                    ri = new ResolveInfo(mResolveInfo);
4191                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4192                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4193                            ri.activityInfo.applicationInfo);
4194                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4195                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4196                    return ri;
4197                }
4198                return mResolveInfo;
4199            }
4200        }
4201        return null;
4202    }
4203
4204    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4205            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4206        final int N = query.size();
4207        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4208                .get(userId);
4209        // Get the list of persistent preferred activities that handle the intent
4210        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4211        List<PersistentPreferredActivity> pprefs = ppir != null
4212                ? ppir.queryIntent(intent, resolvedType,
4213                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4214                : null;
4215        if (pprefs != null && pprefs.size() > 0) {
4216            final int M = pprefs.size();
4217            for (int i=0; i<M; i++) {
4218                final PersistentPreferredActivity ppa = pprefs.get(i);
4219                if (DEBUG_PREFERRED || debug) {
4220                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4221                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4222                            + "\n  component=" + ppa.mComponent);
4223                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4224                }
4225                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4226                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4227                if (DEBUG_PREFERRED || debug) {
4228                    Slog.v(TAG, "Found persistent preferred activity:");
4229                    if (ai != null) {
4230                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4231                    } else {
4232                        Slog.v(TAG, "  null");
4233                    }
4234                }
4235                if (ai == null) {
4236                    // This previously registered persistent preferred activity
4237                    // component is no longer known. Ignore it and do NOT remove it.
4238                    continue;
4239                }
4240                for (int j=0; j<N; j++) {
4241                    final ResolveInfo ri = query.get(j);
4242                    if (!ri.activityInfo.applicationInfo.packageName
4243                            .equals(ai.applicationInfo.packageName)) {
4244                        continue;
4245                    }
4246                    if (!ri.activityInfo.name.equals(ai.name)) {
4247                        continue;
4248                    }
4249                    //  Found a persistent preference that can handle the intent.
4250                    if (DEBUG_PREFERRED || debug) {
4251                        Slog.v(TAG, "Returning persistent preferred activity: " +
4252                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4253                    }
4254                    return ri;
4255                }
4256            }
4257        }
4258        return null;
4259    }
4260
4261    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4262            List<ResolveInfo> query, int priority, boolean always,
4263            boolean removeMatches, boolean debug, int userId) {
4264        if (!sUserManager.exists(userId)) return null;
4265        // writer
4266        synchronized (mPackages) {
4267            if (intent.getSelector() != null) {
4268                intent = intent.getSelector();
4269            }
4270            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4271
4272            // Try to find a matching persistent preferred activity.
4273            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4274                    debug, userId);
4275
4276            // If a persistent preferred activity matched, use it.
4277            if (pri != null) {
4278                return pri;
4279            }
4280
4281            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4282            // Get the list of preferred activities that handle the intent
4283            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4284            List<PreferredActivity> prefs = pir != null
4285                    ? pir.queryIntent(intent, resolvedType,
4286                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4287                    : null;
4288            if (prefs != null && prefs.size() > 0) {
4289                boolean changed = false;
4290                try {
4291                    // First figure out how good the original match set is.
4292                    // We will only allow preferred activities that came
4293                    // from the same match quality.
4294                    int match = 0;
4295
4296                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4297
4298                    final int N = query.size();
4299                    for (int j=0; j<N; j++) {
4300                        final ResolveInfo ri = query.get(j);
4301                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4302                                + ": 0x" + Integer.toHexString(match));
4303                        if (ri.match > match) {
4304                            match = ri.match;
4305                        }
4306                    }
4307
4308                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4309                            + Integer.toHexString(match));
4310
4311                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4312                    final int M = prefs.size();
4313                    for (int i=0; i<M; i++) {
4314                        final PreferredActivity pa = prefs.get(i);
4315                        if (DEBUG_PREFERRED || debug) {
4316                            Slog.v(TAG, "Checking PreferredActivity ds="
4317                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4318                                    + "\n  component=" + pa.mPref.mComponent);
4319                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4320                        }
4321                        if (pa.mPref.mMatch != match) {
4322                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4323                                    + Integer.toHexString(pa.mPref.mMatch));
4324                            continue;
4325                        }
4326                        // If it's not an "always" type preferred activity and that's what we're
4327                        // looking for, skip it.
4328                        if (always && !pa.mPref.mAlways) {
4329                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4330                            continue;
4331                        }
4332                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4333                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4334                        if (DEBUG_PREFERRED || debug) {
4335                            Slog.v(TAG, "Found preferred activity:");
4336                            if (ai != null) {
4337                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4338                            } else {
4339                                Slog.v(TAG, "  null");
4340                            }
4341                        }
4342                        if (ai == null) {
4343                            // This previously registered preferred activity
4344                            // component is no longer known.  Most likely an update
4345                            // to the app was installed and in the new version this
4346                            // component no longer exists.  Clean it up by removing
4347                            // it from the preferred activities list, and skip it.
4348                            Slog.w(TAG, "Removing dangling preferred activity: "
4349                                    + pa.mPref.mComponent);
4350                            pir.removeFilter(pa);
4351                            changed = true;
4352                            continue;
4353                        }
4354                        for (int j=0; j<N; j++) {
4355                            final ResolveInfo ri = query.get(j);
4356                            if (!ri.activityInfo.applicationInfo.packageName
4357                                    .equals(ai.applicationInfo.packageName)) {
4358                                continue;
4359                            }
4360                            if (!ri.activityInfo.name.equals(ai.name)) {
4361                                continue;
4362                            }
4363
4364                            if (removeMatches) {
4365                                pir.removeFilter(pa);
4366                                changed = true;
4367                                if (DEBUG_PREFERRED) {
4368                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4369                                }
4370                                break;
4371                            }
4372
4373                            // Okay we found a previously set preferred or last chosen app.
4374                            // If the result set is different from when this
4375                            // was created, we need to clear it and re-ask the
4376                            // user their preference, if we're looking for an "always" type entry.
4377                            if (always && !pa.mPref.sameSet(query)) {
4378                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4379                                        + intent + " type " + resolvedType);
4380                                if (DEBUG_PREFERRED) {
4381                                    Slog.v(TAG, "Removing preferred activity since set changed "
4382                                            + pa.mPref.mComponent);
4383                                }
4384                                pir.removeFilter(pa);
4385                                // Re-add the filter as a "last chosen" entry (!always)
4386                                PreferredActivity lastChosen = new PreferredActivity(
4387                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4388                                pir.addFilter(lastChosen);
4389                                changed = true;
4390                                return null;
4391                            }
4392
4393                            // Yay! Either the set matched or we're looking for the last chosen
4394                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4395                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4396                            return ri;
4397                        }
4398                    }
4399                } finally {
4400                    if (changed) {
4401                        if (DEBUG_PREFERRED) {
4402                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4403                        }
4404                        scheduleWritePackageRestrictionsLocked(userId);
4405                    }
4406                }
4407            }
4408        }
4409        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4410        return null;
4411    }
4412
4413    /*
4414     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4415     */
4416    @Override
4417    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4418            int targetUserId) {
4419        mContext.enforceCallingOrSelfPermission(
4420                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4421        List<CrossProfileIntentFilter> matches =
4422                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4423        if (matches != null) {
4424            int size = matches.size();
4425            for (int i = 0; i < size; i++) {
4426                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4427            }
4428        }
4429        if (hasWebURI(intent)) {
4430            // cross-profile app linking works only towards the parent.
4431            final UserInfo parent = getProfileParent(sourceUserId);
4432            synchronized(mPackages) {
4433                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4434                        intent, resolvedType, 0, sourceUserId, parent.id);
4435                return xpDomainInfo != null
4436                        && xpDomainInfo.bestDomainVerificationStatus !=
4437                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4438            }
4439        }
4440        return false;
4441    }
4442
4443    private UserInfo getProfileParent(int userId) {
4444        final long identity = Binder.clearCallingIdentity();
4445        try {
4446            return sUserManager.getProfileParent(userId);
4447        } finally {
4448            Binder.restoreCallingIdentity(identity);
4449        }
4450    }
4451
4452    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4453            String resolvedType, int userId) {
4454        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4455        if (resolver != null) {
4456            return resolver.queryIntent(intent, resolvedType, false, userId);
4457        }
4458        return null;
4459    }
4460
4461    @Override
4462    public List<ResolveInfo> queryIntentActivities(Intent intent,
4463            String resolvedType, int flags, int userId) {
4464        if (!sUserManager.exists(userId)) return Collections.emptyList();
4465        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4466        ComponentName comp = intent.getComponent();
4467        if (comp == null) {
4468            if (intent.getSelector() != null) {
4469                intent = intent.getSelector();
4470                comp = intent.getComponent();
4471            }
4472        }
4473
4474        if (comp != null) {
4475            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4476            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4477            if (ai != null) {
4478                final ResolveInfo ri = new ResolveInfo();
4479                ri.activityInfo = ai;
4480                list.add(ri);
4481            }
4482            return list;
4483        }
4484
4485        // reader
4486        synchronized (mPackages) {
4487            final String pkgName = intent.getPackage();
4488            if (pkgName == null) {
4489                List<CrossProfileIntentFilter> matchingFilters =
4490                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4491                // Check for results that need to skip the current profile.
4492                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4493                        resolvedType, flags, userId);
4494                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4495                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4496                    result.add(xpResolveInfo);
4497                    return filterIfNotPrimaryUser(result, userId);
4498                }
4499
4500                // Check for results in the current profile.
4501                List<ResolveInfo> result = mActivities.queryIntent(
4502                        intent, resolvedType, flags, userId);
4503
4504                // Check for cross profile results.
4505                xpResolveInfo = queryCrossProfileIntents(
4506                        matchingFilters, intent, resolvedType, flags, userId);
4507                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4508                    result.add(xpResolveInfo);
4509                    Collections.sort(result, mResolvePrioritySorter);
4510                }
4511                result = filterIfNotPrimaryUser(result, userId);
4512                if (hasWebURI(intent)) {
4513                    CrossProfileDomainInfo xpDomainInfo = null;
4514                    final UserInfo parent = getProfileParent(userId);
4515                    if (parent != null) {
4516                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4517                                flags, userId, parent.id);
4518                    }
4519                    if (xpDomainInfo != null) {
4520                        if (xpResolveInfo != null) {
4521                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4522                            // in the result.
4523                            result.remove(xpResolveInfo);
4524                        }
4525                        if (result.size() == 0) {
4526                            result.add(xpDomainInfo.resolveInfo);
4527                            return result;
4528                        }
4529                    } else if (result.size() <= 1) {
4530                        return result;
4531                    }
4532                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4533                            xpDomainInfo, userId);
4534                    Collections.sort(result, mResolvePrioritySorter);
4535                }
4536                return result;
4537            }
4538            final PackageParser.Package pkg = mPackages.get(pkgName);
4539            if (pkg != null) {
4540                return filterIfNotPrimaryUser(
4541                        mActivities.queryIntentForPackage(
4542                                intent, resolvedType, flags, pkg.activities, userId),
4543                        userId);
4544            }
4545            return new ArrayList<ResolveInfo>();
4546        }
4547    }
4548
4549    private static class CrossProfileDomainInfo {
4550        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4551        ResolveInfo resolveInfo;
4552        /* Best domain verification status of the activities found in the other profile */
4553        int bestDomainVerificationStatus;
4554    }
4555
4556    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4557            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4558        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4559                sourceUserId)) {
4560            return null;
4561        }
4562        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4563                resolvedType, flags, parentUserId);
4564
4565        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4566            return null;
4567        }
4568        CrossProfileDomainInfo result = null;
4569        int size = resultTargetUser.size();
4570        for (int i = 0; i < size; i++) {
4571            ResolveInfo riTargetUser = resultTargetUser.get(i);
4572            // Intent filter verification is only for filters that specify a host. So don't return
4573            // those that handle all web uris.
4574            if (riTargetUser.handleAllWebDataURI) {
4575                continue;
4576            }
4577            String packageName = riTargetUser.activityInfo.packageName;
4578            PackageSetting ps = mSettings.mPackages.get(packageName);
4579            if (ps == null) {
4580                continue;
4581            }
4582            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4583            if (result == null) {
4584                result = new CrossProfileDomainInfo();
4585                result.resolveInfo =
4586                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4587                result.bestDomainVerificationStatus = status;
4588            } else {
4589                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4590                        result.bestDomainVerificationStatus);
4591            }
4592        }
4593        return result;
4594    }
4595
4596    /**
4597     * Verification statuses are ordered from the worse to the best, except for
4598     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4599     */
4600    private int bestDomainVerificationStatus(int status1, int status2) {
4601        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4602            return status2;
4603        }
4604        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4605            return status1;
4606        }
4607        return (int) MathUtils.max(status1, status2);
4608    }
4609
4610    private boolean isUserEnabled(int userId) {
4611        long callingId = Binder.clearCallingIdentity();
4612        try {
4613            UserInfo userInfo = sUserManager.getUserInfo(userId);
4614            return userInfo != null && userInfo.isEnabled();
4615        } finally {
4616            Binder.restoreCallingIdentity(callingId);
4617        }
4618    }
4619
4620    /**
4621     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4622     *
4623     * @return filtered list
4624     */
4625    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4626        if (userId == UserHandle.USER_OWNER) {
4627            return resolveInfos;
4628        }
4629        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4630            ResolveInfo info = resolveInfos.get(i);
4631            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4632                resolveInfos.remove(i);
4633            }
4634        }
4635        return resolveInfos;
4636    }
4637
4638    private static boolean hasWebURI(Intent intent) {
4639        if (intent.getData() == null) {
4640            return false;
4641        }
4642        final String scheme = intent.getScheme();
4643        if (TextUtils.isEmpty(scheme)) {
4644            return false;
4645        }
4646        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4647    }
4648
4649    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4650            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4651            int userId) {
4652        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4653            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4654                    candidates.size());
4655        }
4656
4657        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4658        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4659        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4660        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4661        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4662
4663        synchronized (mPackages) {
4664            final int count = candidates.size();
4665            // First, try to use linked apps. Partition the candidates into four lists:
4666            // one for the final results, one for the "do not use ever", one for "undefined status"
4667            // and finally one for "browser app type".
4668            for (int n=0; n<count; n++) {
4669                ResolveInfo info = candidates.get(n);
4670                String packageName = info.activityInfo.packageName;
4671                PackageSetting ps = mSettings.mPackages.get(packageName);
4672                if (ps != null) {
4673                    // Add to the special match all list (Browser use case)
4674                    if (info.handleAllWebDataURI) {
4675                        matchAllList.add(info);
4676                        continue;
4677                    }
4678                    // Try to get the status from User settings first
4679                    int status = getDomainVerificationStatusLPr(ps, userId);
4680                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4681                        if (DEBUG_DOMAIN_VERIFICATION) {
4682                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4683                        }
4684                        alwaysList.add(info);
4685                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4686                        if (DEBUG_DOMAIN_VERIFICATION) {
4687                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4688                        }
4689                        neverList.add(info);
4690                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4691                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4692                        if (DEBUG_DOMAIN_VERIFICATION) {
4693                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4694                        }
4695                        undefinedList.add(info);
4696                    }
4697                }
4698            }
4699            // First try to add the "always" resolution for the current user if there is any
4700            if (alwaysList.size() > 0) {
4701                result.addAll(alwaysList);
4702            // if there is an "always" for the parent user, add it.
4703            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4704                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4705                result.add(xpDomainInfo.resolveInfo);
4706            } else {
4707                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4708                result.addAll(undefinedList);
4709                if (xpDomainInfo != null && (
4710                        xpDomainInfo.bestDomainVerificationStatus
4711                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4712                        || xpDomainInfo.bestDomainVerificationStatus
4713                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4714                    result.add(xpDomainInfo.resolveInfo);
4715                }
4716                // Also add Browsers (all of them or only the default one)
4717                if ((flags & MATCH_ALL) != 0) {
4718                    result.addAll(matchAllList);
4719                } else {
4720                    // Try to add the Default Browser if we can
4721                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4722                            UserHandle.myUserId());
4723                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4724                        boolean defaultBrowserFound = false;
4725                        final int browserCount = matchAllList.size();
4726                        for (int n=0; n<browserCount; n++) {
4727                            ResolveInfo browser = matchAllList.get(n);
4728                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4729                                result.add(browser);
4730                                defaultBrowserFound = true;
4731                                break;
4732                            }
4733                        }
4734                        if (!defaultBrowserFound) {
4735                            result.addAll(matchAllList);
4736                        }
4737                    } else {
4738                        result.addAll(matchAllList);
4739                    }
4740                }
4741
4742                // If there is nothing selected, add all candidates and remove the ones that the user
4743                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4744                if (result.size() == 0) {
4745                    result.addAll(candidates);
4746                    result.removeAll(neverList);
4747                }
4748            }
4749        }
4750        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4751            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4752                    result.size());
4753            for (ResolveInfo info : result) {
4754                Slog.v(TAG, "  + " + info.activityInfo);
4755            }
4756        }
4757        return result;
4758    }
4759
4760    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4761        int status = ps.getDomainVerificationStatusForUser(userId);
4762        // if none available, get the master status
4763        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4764            if (ps.getIntentFilterVerificationInfo() != null) {
4765                status = ps.getIntentFilterVerificationInfo().getStatus();
4766            }
4767        }
4768        return status;
4769    }
4770
4771    private ResolveInfo querySkipCurrentProfileIntents(
4772            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4773            int flags, int sourceUserId) {
4774        if (matchingFilters != null) {
4775            int size = matchingFilters.size();
4776            for (int i = 0; i < size; i ++) {
4777                CrossProfileIntentFilter filter = matchingFilters.get(i);
4778                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4779                    // Checking if there are activities in the target user that can handle the
4780                    // intent.
4781                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4782                            flags, sourceUserId);
4783                    if (resolveInfo != null) {
4784                        return resolveInfo;
4785                    }
4786                }
4787            }
4788        }
4789        return null;
4790    }
4791
4792    // Return matching ResolveInfo if any for skip current profile intent filters.
4793    private ResolveInfo queryCrossProfileIntents(
4794            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4795            int flags, int sourceUserId) {
4796        if (matchingFilters != null) {
4797            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4798            // match the same intent. For performance reasons, it is better not to
4799            // run queryIntent twice for the same userId
4800            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4801            int size = matchingFilters.size();
4802            for (int i = 0; i < size; i++) {
4803                CrossProfileIntentFilter filter = matchingFilters.get(i);
4804                int targetUserId = filter.getTargetUserId();
4805                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4806                        && !alreadyTriedUserIds.get(targetUserId)) {
4807                    // Checking if there are activities in the target user that can handle the
4808                    // intent.
4809                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4810                            flags, sourceUserId);
4811                    if (resolveInfo != null) return resolveInfo;
4812                    alreadyTriedUserIds.put(targetUserId, true);
4813                }
4814            }
4815        }
4816        return null;
4817    }
4818
4819    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4820            String resolvedType, int flags, int sourceUserId) {
4821        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4822                resolvedType, flags, filter.getTargetUserId());
4823        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4824            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4825        }
4826        return null;
4827    }
4828
4829    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4830            int sourceUserId, int targetUserId) {
4831        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4832        String className;
4833        if (targetUserId == UserHandle.USER_OWNER) {
4834            className = FORWARD_INTENT_TO_USER_OWNER;
4835        } else {
4836            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4837        }
4838        ComponentName forwardingActivityComponentName = new ComponentName(
4839                mAndroidApplication.packageName, className);
4840        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4841                sourceUserId);
4842        if (targetUserId == UserHandle.USER_OWNER) {
4843            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4844            forwardingResolveInfo.noResourceId = true;
4845        }
4846        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4847        forwardingResolveInfo.priority = 0;
4848        forwardingResolveInfo.preferredOrder = 0;
4849        forwardingResolveInfo.match = 0;
4850        forwardingResolveInfo.isDefault = true;
4851        forwardingResolveInfo.filter = filter;
4852        forwardingResolveInfo.targetUserId = targetUserId;
4853        return forwardingResolveInfo;
4854    }
4855
4856    @Override
4857    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4858            Intent[] specifics, String[] specificTypes, Intent intent,
4859            String resolvedType, int flags, int userId) {
4860        if (!sUserManager.exists(userId)) return Collections.emptyList();
4861        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4862                false, "query intent activity options");
4863        final String resultsAction = intent.getAction();
4864
4865        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4866                | PackageManager.GET_RESOLVED_FILTER, userId);
4867
4868        if (DEBUG_INTENT_MATCHING) {
4869            Log.v(TAG, "Query " + intent + ": " + results);
4870        }
4871
4872        int specificsPos = 0;
4873        int N;
4874
4875        // todo: note that the algorithm used here is O(N^2).  This
4876        // isn't a problem in our current environment, but if we start running
4877        // into situations where we have more than 5 or 10 matches then this
4878        // should probably be changed to something smarter...
4879
4880        // First we go through and resolve each of the specific items
4881        // that were supplied, taking care of removing any corresponding
4882        // duplicate items in the generic resolve list.
4883        if (specifics != null) {
4884            for (int i=0; i<specifics.length; i++) {
4885                final Intent sintent = specifics[i];
4886                if (sintent == null) {
4887                    continue;
4888                }
4889
4890                if (DEBUG_INTENT_MATCHING) {
4891                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4892                }
4893
4894                String action = sintent.getAction();
4895                if (resultsAction != null && resultsAction.equals(action)) {
4896                    // If this action was explicitly requested, then don't
4897                    // remove things that have it.
4898                    action = null;
4899                }
4900
4901                ResolveInfo ri = null;
4902                ActivityInfo ai = null;
4903
4904                ComponentName comp = sintent.getComponent();
4905                if (comp == null) {
4906                    ri = resolveIntent(
4907                        sintent,
4908                        specificTypes != null ? specificTypes[i] : null,
4909                            flags, userId);
4910                    if (ri == null) {
4911                        continue;
4912                    }
4913                    if (ri == mResolveInfo) {
4914                        // ACK!  Must do something better with this.
4915                    }
4916                    ai = ri.activityInfo;
4917                    comp = new ComponentName(ai.applicationInfo.packageName,
4918                            ai.name);
4919                } else {
4920                    ai = getActivityInfo(comp, flags, userId);
4921                    if (ai == null) {
4922                        continue;
4923                    }
4924                }
4925
4926                // Look for any generic query activities that are duplicates
4927                // of this specific one, and remove them from the results.
4928                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4929                N = results.size();
4930                int j;
4931                for (j=specificsPos; j<N; j++) {
4932                    ResolveInfo sri = results.get(j);
4933                    if ((sri.activityInfo.name.equals(comp.getClassName())
4934                            && sri.activityInfo.applicationInfo.packageName.equals(
4935                                    comp.getPackageName()))
4936                        || (action != null && sri.filter.matchAction(action))) {
4937                        results.remove(j);
4938                        if (DEBUG_INTENT_MATCHING) Log.v(
4939                            TAG, "Removing duplicate item from " + j
4940                            + " due to specific " + specificsPos);
4941                        if (ri == null) {
4942                            ri = sri;
4943                        }
4944                        j--;
4945                        N--;
4946                    }
4947                }
4948
4949                // Add this specific item to its proper place.
4950                if (ri == null) {
4951                    ri = new ResolveInfo();
4952                    ri.activityInfo = ai;
4953                }
4954                results.add(specificsPos, ri);
4955                ri.specificIndex = i;
4956                specificsPos++;
4957            }
4958        }
4959
4960        // Now we go through the remaining generic results and remove any
4961        // duplicate actions that are found here.
4962        N = results.size();
4963        for (int i=specificsPos; i<N-1; i++) {
4964            final ResolveInfo rii = results.get(i);
4965            if (rii.filter == null) {
4966                continue;
4967            }
4968
4969            // Iterate over all of the actions of this result's intent
4970            // filter...  typically this should be just one.
4971            final Iterator<String> it = rii.filter.actionsIterator();
4972            if (it == null) {
4973                continue;
4974            }
4975            while (it.hasNext()) {
4976                final String action = it.next();
4977                if (resultsAction != null && resultsAction.equals(action)) {
4978                    // If this action was explicitly requested, then don't
4979                    // remove things that have it.
4980                    continue;
4981                }
4982                for (int j=i+1; j<N; j++) {
4983                    final ResolveInfo rij = results.get(j);
4984                    if (rij.filter != null && rij.filter.hasAction(action)) {
4985                        results.remove(j);
4986                        if (DEBUG_INTENT_MATCHING) Log.v(
4987                            TAG, "Removing duplicate item from " + j
4988                            + " due to action " + action + " at " + i);
4989                        j--;
4990                        N--;
4991                    }
4992                }
4993            }
4994
4995            // If the caller didn't request filter information, drop it now
4996            // so we don't have to marshall/unmarshall it.
4997            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4998                rii.filter = null;
4999            }
5000        }
5001
5002        // Filter out the caller activity if so requested.
5003        if (caller != null) {
5004            N = results.size();
5005            for (int i=0; i<N; i++) {
5006                ActivityInfo ainfo = results.get(i).activityInfo;
5007                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5008                        && caller.getClassName().equals(ainfo.name)) {
5009                    results.remove(i);
5010                    break;
5011                }
5012            }
5013        }
5014
5015        // If the caller didn't request filter information,
5016        // drop them now so we don't have to
5017        // marshall/unmarshall it.
5018        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5019            N = results.size();
5020            for (int i=0; i<N; i++) {
5021                results.get(i).filter = null;
5022            }
5023        }
5024
5025        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5026        return results;
5027    }
5028
5029    @Override
5030    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5031            int userId) {
5032        if (!sUserManager.exists(userId)) return Collections.emptyList();
5033        ComponentName comp = intent.getComponent();
5034        if (comp == null) {
5035            if (intent.getSelector() != null) {
5036                intent = intent.getSelector();
5037                comp = intent.getComponent();
5038            }
5039        }
5040        if (comp != null) {
5041            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5042            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5043            if (ai != null) {
5044                ResolveInfo ri = new ResolveInfo();
5045                ri.activityInfo = ai;
5046                list.add(ri);
5047            }
5048            return list;
5049        }
5050
5051        // reader
5052        synchronized (mPackages) {
5053            String pkgName = intent.getPackage();
5054            if (pkgName == null) {
5055                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5056            }
5057            final PackageParser.Package pkg = mPackages.get(pkgName);
5058            if (pkg != null) {
5059                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5060                        userId);
5061            }
5062            return null;
5063        }
5064    }
5065
5066    @Override
5067    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5068        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5069        if (!sUserManager.exists(userId)) return null;
5070        if (query != null) {
5071            if (query.size() >= 1) {
5072                // If there is more than one service with the same priority,
5073                // just arbitrarily pick the first one.
5074                return query.get(0);
5075            }
5076        }
5077        return null;
5078    }
5079
5080    @Override
5081    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5082            int userId) {
5083        if (!sUserManager.exists(userId)) return Collections.emptyList();
5084        ComponentName comp = intent.getComponent();
5085        if (comp == null) {
5086            if (intent.getSelector() != null) {
5087                intent = intent.getSelector();
5088                comp = intent.getComponent();
5089            }
5090        }
5091        if (comp != null) {
5092            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5093            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5094            if (si != null) {
5095                final ResolveInfo ri = new ResolveInfo();
5096                ri.serviceInfo = si;
5097                list.add(ri);
5098            }
5099            return list;
5100        }
5101
5102        // reader
5103        synchronized (mPackages) {
5104            String pkgName = intent.getPackage();
5105            if (pkgName == null) {
5106                return mServices.queryIntent(intent, resolvedType, flags, userId);
5107            }
5108            final PackageParser.Package pkg = mPackages.get(pkgName);
5109            if (pkg != null) {
5110                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5111                        userId);
5112            }
5113            return null;
5114        }
5115    }
5116
5117    @Override
5118    public List<ResolveInfo> queryIntentContentProviders(
5119            Intent intent, String resolvedType, int flags, int userId) {
5120        if (!sUserManager.exists(userId)) return Collections.emptyList();
5121        ComponentName comp = intent.getComponent();
5122        if (comp == null) {
5123            if (intent.getSelector() != null) {
5124                intent = intent.getSelector();
5125                comp = intent.getComponent();
5126            }
5127        }
5128        if (comp != null) {
5129            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5130            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5131            if (pi != null) {
5132                final ResolveInfo ri = new ResolveInfo();
5133                ri.providerInfo = pi;
5134                list.add(ri);
5135            }
5136            return list;
5137        }
5138
5139        // reader
5140        synchronized (mPackages) {
5141            String pkgName = intent.getPackage();
5142            if (pkgName == null) {
5143                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5144            }
5145            final PackageParser.Package pkg = mPackages.get(pkgName);
5146            if (pkg != null) {
5147                return mProviders.queryIntentForPackage(
5148                        intent, resolvedType, flags, pkg.providers, userId);
5149            }
5150            return null;
5151        }
5152    }
5153
5154    @Override
5155    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5156        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5157
5158        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5159
5160        // writer
5161        synchronized (mPackages) {
5162            ArrayList<PackageInfo> list;
5163            if (listUninstalled) {
5164                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5165                for (PackageSetting ps : mSettings.mPackages.values()) {
5166                    PackageInfo pi;
5167                    if (ps.pkg != null) {
5168                        pi = generatePackageInfo(ps.pkg, flags, userId);
5169                    } else {
5170                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5171                    }
5172                    if (pi != null) {
5173                        list.add(pi);
5174                    }
5175                }
5176            } else {
5177                list = new ArrayList<PackageInfo>(mPackages.size());
5178                for (PackageParser.Package p : mPackages.values()) {
5179                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5180                    if (pi != null) {
5181                        list.add(pi);
5182                    }
5183                }
5184            }
5185
5186            return new ParceledListSlice<PackageInfo>(list);
5187        }
5188    }
5189
5190    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5191            String[] permissions, boolean[] tmp, int flags, int userId) {
5192        int numMatch = 0;
5193        final PermissionsState permissionsState = ps.getPermissionsState();
5194        for (int i=0; i<permissions.length; i++) {
5195            final String permission = permissions[i];
5196            if (permissionsState.hasPermission(permission, userId)) {
5197                tmp[i] = true;
5198                numMatch++;
5199            } else {
5200                tmp[i] = false;
5201            }
5202        }
5203        if (numMatch == 0) {
5204            return;
5205        }
5206        PackageInfo pi;
5207        if (ps.pkg != null) {
5208            pi = generatePackageInfo(ps.pkg, flags, userId);
5209        } else {
5210            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5211        }
5212        // The above might return null in cases of uninstalled apps or install-state
5213        // skew across users/profiles.
5214        if (pi != null) {
5215            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5216                if (numMatch == permissions.length) {
5217                    pi.requestedPermissions = permissions;
5218                } else {
5219                    pi.requestedPermissions = new String[numMatch];
5220                    numMatch = 0;
5221                    for (int i=0; i<permissions.length; i++) {
5222                        if (tmp[i]) {
5223                            pi.requestedPermissions[numMatch] = permissions[i];
5224                            numMatch++;
5225                        }
5226                    }
5227                }
5228            }
5229            list.add(pi);
5230        }
5231    }
5232
5233    @Override
5234    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5235            String[] permissions, int flags, int userId) {
5236        if (!sUserManager.exists(userId)) return null;
5237        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5238
5239        // writer
5240        synchronized (mPackages) {
5241            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5242            boolean[] tmpBools = new boolean[permissions.length];
5243            if (listUninstalled) {
5244                for (PackageSetting ps : mSettings.mPackages.values()) {
5245                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5246                }
5247            } else {
5248                for (PackageParser.Package pkg : mPackages.values()) {
5249                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5250                    if (ps != null) {
5251                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5252                                userId);
5253                    }
5254                }
5255            }
5256
5257            return new ParceledListSlice<PackageInfo>(list);
5258        }
5259    }
5260
5261    @Override
5262    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5263        if (!sUserManager.exists(userId)) return null;
5264        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5265
5266        // writer
5267        synchronized (mPackages) {
5268            ArrayList<ApplicationInfo> list;
5269            if (listUninstalled) {
5270                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5271                for (PackageSetting ps : mSettings.mPackages.values()) {
5272                    ApplicationInfo ai;
5273                    if (ps.pkg != null) {
5274                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5275                                ps.readUserState(userId), userId);
5276                    } else {
5277                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5278                    }
5279                    if (ai != null) {
5280                        list.add(ai);
5281                    }
5282                }
5283            } else {
5284                list = new ArrayList<ApplicationInfo>(mPackages.size());
5285                for (PackageParser.Package p : mPackages.values()) {
5286                    if (p.mExtras != null) {
5287                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5288                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5289                        if (ai != null) {
5290                            list.add(ai);
5291                        }
5292                    }
5293                }
5294            }
5295
5296            return new ParceledListSlice<ApplicationInfo>(list);
5297        }
5298    }
5299
5300    public List<ApplicationInfo> getPersistentApplications(int flags) {
5301        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5302
5303        // reader
5304        synchronized (mPackages) {
5305            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5306            final int userId = UserHandle.getCallingUserId();
5307            while (i.hasNext()) {
5308                final PackageParser.Package p = i.next();
5309                if (p.applicationInfo != null
5310                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5311                        && (!mSafeMode || isSystemApp(p))) {
5312                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5313                    if (ps != null) {
5314                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5315                                ps.readUserState(userId), userId);
5316                        if (ai != null) {
5317                            finalList.add(ai);
5318                        }
5319                    }
5320                }
5321            }
5322        }
5323
5324        return finalList;
5325    }
5326
5327    @Override
5328    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5329        if (!sUserManager.exists(userId)) return null;
5330        // reader
5331        synchronized (mPackages) {
5332            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5333            PackageSetting ps = provider != null
5334                    ? mSettings.mPackages.get(provider.owner.packageName)
5335                    : null;
5336            return ps != null
5337                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5338                    && (!mSafeMode || (provider.info.applicationInfo.flags
5339                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5340                    ? PackageParser.generateProviderInfo(provider, flags,
5341                            ps.readUserState(userId), userId)
5342                    : null;
5343        }
5344    }
5345
5346    /**
5347     * @deprecated
5348     */
5349    @Deprecated
5350    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5351        // reader
5352        synchronized (mPackages) {
5353            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5354                    .entrySet().iterator();
5355            final int userId = UserHandle.getCallingUserId();
5356            while (i.hasNext()) {
5357                Map.Entry<String, PackageParser.Provider> entry = i.next();
5358                PackageParser.Provider p = entry.getValue();
5359                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5360
5361                if (ps != null && p.syncable
5362                        && (!mSafeMode || (p.info.applicationInfo.flags
5363                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5364                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5365                            ps.readUserState(userId), userId);
5366                    if (info != null) {
5367                        outNames.add(entry.getKey());
5368                        outInfo.add(info);
5369                    }
5370                }
5371            }
5372        }
5373    }
5374
5375    @Override
5376    public List<ProviderInfo> queryContentProviders(String processName,
5377            int uid, int flags) {
5378        ArrayList<ProviderInfo> finalList = null;
5379        // reader
5380        synchronized (mPackages) {
5381            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5382            final int userId = processName != null ?
5383                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5384            while (i.hasNext()) {
5385                final PackageParser.Provider p = i.next();
5386                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5387                if (ps != null && p.info.authority != null
5388                        && (processName == null
5389                                || (p.info.processName.equals(processName)
5390                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5391                        && mSettings.isEnabledLPr(p.info, flags, userId)
5392                        && (!mSafeMode
5393                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5394                    if (finalList == null) {
5395                        finalList = new ArrayList<ProviderInfo>(3);
5396                    }
5397                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5398                            ps.readUserState(userId), userId);
5399                    if (info != null) {
5400                        finalList.add(info);
5401                    }
5402                }
5403            }
5404        }
5405
5406        if (finalList != null) {
5407            Collections.sort(finalList, mProviderInitOrderSorter);
5408        }
5409
5410        return finalList;
5411    }
5412
5413    @Override
5414    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5415            int flags) {
5416        // reader
5417        synchronized (mPackages) {
5418            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5419            return PackageParser.generateInstrumentationInfo(i, flags);
5420        }
5421    }
5422
5423    @Override
5424    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5425            int flags) {
5426        ArrayList<InstrumentationInfo> finalList =
5427            new ArrayList<InstrumentationInfo>();
5428
5429        // reader
5430        synchronized (mPackages) {
5431            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5432            while (i.hasNext()) {
5433                final PackageParser.Instrumentation p = i.next();
5434                if (targetPackage == null
5435                        || targetPackage.equals(p.info.targetPackage)) {
5436                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5437                            flags);
5438                    if (ii != null) {
5439                        finalList.add(ii);
5440                    }
5441                }
5442            }
5443        }
5444
5445        return finalList;
5446    }
5447
5448    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5449        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5450        if (overlays == null) {
5451            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5452            return;
5453        }
5454        for (PackageParser.Package opkg : overlays.values()) {
5455            // Not much to do if idmap fails: we already logged the error
5456            // and we certainly don't want to abort installation of pkg simply
5457            // because an overlay didn't fit properly. For these reasons,
5458            // ignore the return value of createIdmapForPackagePairLI.
5459            createIdmapForPackagePairLI(pkg, opkg);
5460        }
5461    }
5462
5463    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5464            PackageParser.Package opkg) {
5465        if (!opkg.mTrustedOverlay) {
5466            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5467                    opkg.baseCodePath + ": overlay not trusted");
5468            return false;
5469        }
5470        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5471        if (overlaySet == null) {
5472            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5473                    opkg.baseCodePath + " but target package has no known overlays");
5474            return false;
5475        }
5476        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5477        // TODO: generate idmap for split APKs
5478        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5479            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5480                    + opkg.baseCodePath);
5481            return false;
5482        }
5483        PackageParser.Package[] overlayArray =
5484            overlaySet.values().toArray(new PackageParser.Package[0]);
5485        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5486            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5487                return p1.mOverlayPriority - p2.mOverlayPriority;
5488            }
5489        };
5490        Arrays.sort(overlayArray, cmp);
5491
5492        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5493        int i = 0;
5494        for (PackageParser.Package p : overlayArray) {
5495            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5496        }
5497        return true;
5498    }
5499
5500    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5501        final File[] files = dir.listFiles();
5502        if (ArrayUtils.isEmpty(files)) {
5503            Log.d(TAG, "No files in app dir " + dir);
5504            return;
5505        }
5506
5507        if (DEBUG_PACKAGE_SCANNING) {
5508            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5509                    + " flags=0x" + Integer.toHexString(parseFlags));
5510        }
5511
5512        for (File file : files) {
5513            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5514                    && !PackageInstallerService.isStageName(file.getName());
5515            if (!isPackage) {
5516                // Ignore entries which are not packages
5517                continue;
5518            }
5519            try {
5520                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5521                        scanFlags, currentTime, null);
5522            } catch (PackageManagerException e) {
5523                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5524
5525                // Delete invalid userdata apps
5526                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5527                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5528                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5529                    if (file.isDirectory()) {
5530                        mInstaller.rmPackageDir(file.getAbsolutePath());
5531                    } else {
5532                        file.delete();
5533                    }
5534                }
5535            }
5536        }
5537    }
5538
5539    private static File getSettingsProblemFile() {
5540        File dataDir = Environment.getDataDirectory();
5541        File systemDir = new File(dataDir, "system");
5542        File fname = new File(systemDir, "uiderrors.txt");
5543        return fname;
5544    }
5545
5546    static void reportSettingsProblem(int priority, String msg) {
5547        logCriticalInfo(priority, msg);
5548    }
5549
5550    static void logCriticalInfo(int priority, String msg) {
5551        Slog.println(priority, TAG, msg);
5552        EventLogTags.writePmCriticalInfo(msg);
5553        try {
5554            File fname = getSettingsProblemFile();
5555            FileOutputStream out = new FileOutputStream(fname, true);
5556            PrintWriter pw = new FastPrintWriter(out);
5557            SimpleDateFormat formatter = new SimpleDateFormat();
5558            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5559            pw.println(dateString + ": " + msg);
5560            pw.close();
5561            FileUtils.setPermissions(
5562                    fname.toString(),
5563                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5564                    -1, -1);
5565        } catch (java.io.IOException e) {
5566        }
5567    }
5568
5569    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5570            PackageParser.Package pkg, File srcFile, int parseFlags)
5571            throws PackageManagerException {
5572        if (ps != null
5573                && ps.codePath.equals(srcFile)
5574                && ps.timeStamp == srcFile.lastModified()
5575                && !isCompatSignatureUpdateNeeded(pkg)
5576                && !isRecoverSignatureUpdateNeeded(pkg)) {
5577            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5578            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5579            ArraySet<PublicKey> signingKs;
5580            synchronized (mPackages) {
5581                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5582            }
5583            if (ps.signatures.mSignatures != null
5584                    && ps.signatures.mSignatures.length != 0
5585                    && signingKs != null) {
5586                // Optimization: reuse the existing cached certificates
5587                // if the package appears to be unchanged.
5588                pkg.mSignatures = ps.signatures.mSignatures;
5589                pkg.mSigningKeys = signingKs;
5590                return;
5591            }
5592
5593            Slog.w(TAG, "PackageSetting for " + ps.name
5594                    + " is missing signatures.  Collecting certs again to recover them.");
5595        } else {
5596            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5597        }
5598
5599        try {
5600            pp.collectCertificates(pkg, parseFlags);
5601            pp.collectManifestDigest(pkg);
5602        } catch (PackageParserException e) {
5603            throw PackageManagerException.from(e);
5604        }
5605    }
5606
5607    /*
5608     *  Scan a package and return the newly parsed package.
5609     *  Returns null in case of errors and the error code is stored in mLastScanError
5610     */
5611    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5612            long currentTime, UserHandle user) throws PackageManagerException {
5613        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5614        parseFlags |= mDefParseFlags;
5615        PackageParser pp = new PackageParser();
5616        pp.setSeparateProcesses(mSeparateProcesses);
5617        pp.setOnlyCoreApps(mOnlyCore);
5618        pp.setDisplayMetrics(mMetrics);
5619
5620        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5621            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5622        }
5623
5624        final PackageParser.Package pkg;
5625        try {
5626            pkg = pp.parsePackage(scanFile, parseFlags);
5627        } catch (PackageParserException e) {
5628            throw PackageManagerException.from(e);
5629        }
5630
5631        PackageSetting ps = null;
5632        PackageSetting updatedPkg;
5633        // reader
5634        synchronized (mPackages) {
5635            // Look to see if we already know about this package.
5636            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5637            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5638                // This package has been renamed to its original name.  Let's
5639                // use that.
5640                ps = mSettings.peekPackageLPr(oldName);
5641            }
5642            // If there was no original package, see one for the real package name.
5643            if (ps == null) {
5644                ps = mSettings.peekPackageLPr(pkg.packageName);
5645            }
5646            // Check to see if this package could be hiding/updating a system
5647            // package.  Must look for it either under the original or real
5648            // package name depending on our state.
5649            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5650            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5651        }
5652        boolean updatedPkgBetter = false;
5653        // First check if this is a system package that may involve an update
5654        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5655            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5656            // it needs to drop FLAG_PRIVILEGED.
5657            if (locationIsPrivileged(scanFile)) {
5658                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5659            } else {
5660                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5661            }
5662
5663            if (ps != null && !ps.codePath.equals(scanFile)) {
5664                // The path has changed from what was last scanned...  check the
5665                // version of the new path against what we have stored to determine
5666                // what to do.
5667                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5668                if (pkg.mVersionCode <= ps.versionCode) {
5669                    // The system package has been updated and the code path does not match
5670                    // Ignore entry. Skip it.
5671                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5672                            + " ignored: updated version " + ps.versionCode
5673                            + " better than this " + pkg.mVersionCode);
5674                    if (!updatedPkg.codePath.equals(scanFile)) {
5675                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5676                                + ps.name + " changing from " + updatedPkg.codePathString
5677                                + " to " + scanFile);
5678                        updatedPkg.codePath = scanFile;
5679                        updatedPkg.codePathString = scanFile.toString();
5680                        updatedPkg.resourcePath = scanFile;
5681                        updatedPkg.resourcePathString = scanFile.toString();
5682                    }
5683                    updatedPkg.pkg = pkg;
5684                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5685                            "Package " + ps.name + " at " + scanFile
5686                                    + " ignored: updated version " + ps.versionCode
5687                                    + " better than this " + pkg.mVersionCode);
5688                } else {
5689                    // The current app on the system partition is better than
5690                    // what we have updated to on the data partition; switch
5691                    // back to the system partition version.
5692                    // At this point, its safely assumed that package installation for
5693                    // apps in system partition will go through. If not there won't be a working
5694                    // version of the app
5695                    // writer
5696                    synchronized (mPackages) {
5697                        // Just remove the loaded entries from package lists.
5698                        mPackages.remove(ps.name);
5699                    }
5700
5701                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5702                            + " reverting from " + ps.codePathString
5703                            + ": new version " + pkg.mVersionCode
5704                            + " better than installed " + ps.versionCode);
5705
5706                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5707                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5708                    synchronized (mInstallLock) {
5709                        args.cleanUpResourcesLI();
5710                    }
5711                    synchronized (mPackages) {
5712                        mSettings.enableSystemPackageLPw(ps.name);
5713                    }
5714                    updatedPkgBetter = true;
5715                }
5716            }
5717        }
5718
5719        if (updatedPkg != null) {
5720            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5721            // initially
5722            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5723
5724            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5725            // flag set initially
5726            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5727                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5728            }
5729        }
5730
5731        // Verify certificates against what was last scanned
5732        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5733
5734        /*
5735         * A new system app appeared, but we already had a non-system one of the
5736         * same name installed earlier.
5737         */
5738        boolean shouldHideSystemApp = false;
5739        if (updatedPkg == null && ps != null
5740                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5741            /*
5742             * Check to make sure the signatures match first. If they don't,
5743             * wipe the installed application and its data.
5744             */
5745            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5746                    != PackageManager.SIGNATURE_MATCH) {
5747                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5748                        + " signatures don't match existing userdata copy; removing");
5749                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5750                ps = null;
5751            } else {
5752                /*
5753                 * If the newly-added system app is an older version than the
5754                 * already installed version, hide it. It will be scanned later
5755                 * and re-added like an update.
5756                 */
5757                if (pkg.mVersionCode <= ps.versionCode) {
5758                    shouldHideSystemApp = true;
5759                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5760                            + " but new version " + pkg.mVersionCode + " better than installed "
5761                            + ps.versionCode + "; hiding system");
5762                } else {
5763                    /*
5764                     * The newly found system app is a newer version that the
5765                     * one previously installed. Simply remove the
5766                     * already-installed application and replace it with our own
5767                     * while keeping the application data.
5768                     */
5769                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5770                            + " reverting from " + ps.codePathString + ": new version "
5771                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5772                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5773                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5774                    synchronized (mInstallLock) {
5775                        args.cleanUpResourcesLI();
5776                    }
5777                }
5778            }
5779        }
5780
5781        // The apk is forward locked (not public) if its code and resources
5782        // are kept in different files. (except for app in either system or
5783        // vendor path).
5784        // TODO grab this value from PackageSettings
5785        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5786            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5787                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5788            }
5789        }
5790
5791        // TODO: extend to support forward-locked splits
5792        String resourcePath = null;
5793        String baseResourcePath = null;
5794        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5795            if (ps != null && ps.resourcePathString != null) {
5796                resourcePath = ps.resourcePathString;
5797                baseResourcePath = ps.resourcePathString;
5798            } else {
5799                // Should not happen at all. Just log an error.
5800                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5801            }
5802        } else {
5803            resourcePath = pkg.codePath;
5804            baseResourcePath = pkg.baseCodePath;
5805        }
5806
5807        // Set application objects path explicitly.
5808        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5809        pkg.applicationInfo.setCodePath(pkg.codePath);
5810        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5811        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5812        pkg.applicationInfo.setResourcePath(resourcePath);
5813        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5814        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5815
5816        // Note that we invoke the following method only if we are about to unpack an application
5817        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5818                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5819
5820        /*
5821         * If the system app should be overridden by a previously installed
5822         * data, hide the system app now and let the /data/app scan pick it up
5823         * again.
5824         */
5825        if (shouldHideSystemApp) {
5826            synchronized (mPackages) {
5827                /*
5828                 * We have to grant systems permissions before we hide, because
5829                 * grantPermissions will assume the package update is trying to
5830                 * expand its permissions.
5831                 */
5832                grantPermissionsLPw(pkg, true, pkg.packageName);
5833                mSettings.disableSystemPackageLPw(pkg.packageName);
5834            }
5835        }
5836
5837        return scannedPkg;
5838    }
5839
5840    private static String fixProcessName(String defProcessName,
5841            String processName, int uid) {
5842        if (processName == null) {
5843            return defProcessName;
5844        }
5845        return processName;
5846    }
5847
5848    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5849            throws PackageManagerException {
5850        if (pkgSetting.signatures.mSignatures != null) {
5851            // Already existing package. Make sure signatures match
5852            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5853                    == PackageManager.SIGNATURE_MATCH;
5854            if (!match) {
5855                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5856                        == PackageManager.SIGNATURE_MATCH;
5857            }
5858            if (!match) {
5859                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5860                        == PackageManager.SIGNATURE_MATCH;
5861            }
5862            if (!match) {
5863                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5864                        + pkg.packageName + " signatures do not match the "
5865                        + "previously installed version; ignoring!");
5866            }
5867        }
5868
5869        // Check for shared user signatures
5870        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5871            // Already existing package. Make sure signatures match
5872            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5873                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5874            if (!match) {
5875                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5876                        == PackageManager.SIGNATURE_MATCH;
5877            }
5878            if (!match) {
5879                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5880                        == PackageManager.SIGNATURE_MATCH;
5881            }
5882            if (!match) {
5883                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5884                        "Package " + pkg.packageName
5885                        + " has no signatures that match those in shared user "
5886                        + pkgSetting.sharedUser.name + "; ignoring!");
5887            }
5888        }
5889    }
5890
5891    /**
5892     * Enforces that only the system UID or root's UID can call a method exposed
5893     * via Binder.
5894     *
5895     * @param message used as message if SecurityException is thrown
5896     * @throws SecurityException if the caller is not system or root
5897     */
5898    private static final void enforceSystemOrRoot(String message) {
5899        final int uid = Binder.getCallingUid();
5900        if (uid != Process.SYSTEM_UID && uid != 0) {
5901            throw new SecurityException(message);
5902        }
5903    }
5904
5905    @Override
5906    public void performBootDexOpt() {
5907        enforceSystemOrRoot("Only the system can request dexopt be performed");
5908
5909        // Before everything else, see whether we need to fstrim.
5910        try {
5911            IMountService ms = PackageHelper.getMountService();
5912            if (ms != null) {
5913                final boolean isUpgrade = isUpgrade();
5914                boolean doTrim = isUpgrade;
5915                if (doTrim) {
5916                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5917                } else {
5918                    final long interval = android.provider.Settings.Global.getLong(
5919                            mContext.getContentResolver(),
5920                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5921                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5922                    if (interval > 0) {
5923                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5924                        if (timeSinceLast > interval) {
5925                            doTrim = true;
5926                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5927                                    + "; running immediately");
5928                        }
5929                    }
5930                }
5931                if (doTrim) {
5932                    if (!isFirstBoot()) {
5933                        try {
5934                            ActivityManagerNative.getDefault().showBootMessage(
5935                                    mContext.getResources().getString(
5936                                            R.string.android_upgrading_fstrim), true);
5937                        } catch (RemoteException e) {
5938                        }
5939                    }
5940                    ms.runMaintenance();
5941                }
5942            } else {
5943                Slog.e(TAG, "Mount service unavailable!");
5944            }
5945        } catch (RemoteException e) {
5946            // Can't happen; MountService is local
5947        }
5948
5949        final ArraySet<PackageParser.Package> pkgs;
5950        synchronized (mPackages) {
5951            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5952        }
5953
5954        if (pkgs != null) {
5955            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5956            // in case the device runs out of space.
5957            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5958            // Give priority to core apps.
5959            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5960                PackageParser.Package pkg = it.next();
5961                if (pkg.coreApp) {
5962                    if (DEBUG_DEXOPT) {
5963                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5964                    }
5965                    sortedPkgs.add(pkg);
5966                    it.remove();
5967                }
5968            }
5969            // Give priority to system apps that listen for pre boot complete.
5970            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5971            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5972            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5973                PackageParser.Package pkg = it.next();
5974                if (pkgNames.contains(pkg.packageName)) {
5975                    if (DEBUG_DEXOPT) {
5976                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5977                    }
5978                    sortedPkgs.add(pkg);
5979                    it.remove();
5980                }
5981            }
5982            // Give priority to system apps.
5983            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5984                PackageParser.Package pkg = it.next();
5985                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5986                    if (DEBUG_DEXOPT) {
5987                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5988                    }
5989                    sortedPkgs.add(pkg);
5990                    it.remove();
5991                }
5992            }
5993            // Give priority to updated system apps.
5994            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5995                PackageParser.Package pkg = it.next();
5996                if (pkg.isUpdatedSystemApp()) {
5997                    if (DEBUG_DEXOPT) {
5998                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5999                    }
6000                    sortedPkgs.add(pkg);
6001                    it.remove();
6002                }
6003            }
6004            // Give priority to apps that listen for boot complete.
6005            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6006            pkgNames = getPackageNamesForIntent(intent);
6007            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6008                PackageParser.Package pkg = it.next();
6009                if (pkgNames.contains(pkg.packageName)) {
6010                    if (DEBUG_DEXOPT) {
6011                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6012                    }
6013                    sortedPkgs.add(pkg);
6014                    it.remove();
6015                }
6016            }
6017            // Filter out packages that aren't recently used.
6018            filterRecentlyUsedApps(pkgs);
6019            // Add all remaining apps.
6020            for (PackageParser.Package pkg : pkgs) {
6021                if (DEBUG_DEXOPT) {
6022                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6023                }
6024                sortedPkgs.add(pkg);
6025            }
6026
6027            // If we want to be lazy, filter everything that wasn't recently used.
6028            if (mLazyDexOpt) {
6029                filterRecentlyUsedApps(sortedPkgs);
6030            }
6031
6032            int i = 0;
6033            int total = sortedPkgs.size();
6034            File dataDir = Environment.getDataDirectory();
6035            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6036            if (lowThreshold == 0) {
6037                throw new IllegalStateException("Invalid low memory threshold");
6038            }
6039            for (PackageParser.Package pkg : sortedPkgs) {
6040                long usableSpace = dataDir.getUsableSpace();
6041                if (usableSpace < lowThreshold) {
6042                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6043                    break;
6044                }
6045                performBootDexOpt(pkg, ++i, total);
6046            }
6047        }
6048    }
6049
6050    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6051        // Filter out packages that aren't recently used.
6052        //
6053        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6054        // should do a full dexopt.
6055        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6056            int total = pkgs.size();
6057            int skipped = 0;
6058            long now = System.currentTimeMillis();
6059            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6060                PackageParser.Package pkg = i.next();
6061                long then = pkg.mLastPackageUsageTimeInMills;
6062                if (then + mDexOptLRUThresholdInMills < now) {
6063                    if (DEBUG_DEXOPT) {
6064                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6065                              ((then == 0) ? "never" : new Date(then)));
6066                    }
6067                    i.remove();
6068                    skipped++;
6069                }
6070            }
6071            if (DEBUG_DEXOPT) {
6072                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6073            }
6074        }
6075    }
6076
6077    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6078        List<ResolveInfo> ris = null;
6079        try {
6080            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6081                    intent, null, 0, UserHandle.USER_OWNER);
6082        } catch (RemoteException e) {
6083        }
6084        ArraySet<String> pkgNames = new ArraySet<String>();
6085        if (ris != null) {
6086            for (ResolveInfo ri : ris) {
6087                pkgNames.add(ri.activityInfo.packageName);
6088            }
6089        }
6090        return pkgNames;
6091    }
6092
6093    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6094        if (DEBUG_DEXOPT) {
6095            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6096        }
6097        if (!isFirstBoot()) {
6098            try {
6099                ActivityManagerNative.getDefault().showBootMessage(
6100                        mContext.getResources().getString(R.string.android_upgrading_apk,
6101                                curr, total), true);
6102            } catch (RemoteException e) {
6103            }
6104        }
6105        PackageParser.Package p = pkg;
6106        synchronized (mInstallLock) {
6107            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6108                    false /* force dex */, false /* defer */, true /* include dependencies */);
6109        }
6110    }
6111
6112    @Override
6113    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6114        return performDexOpt(packageName, instructionSet, false);
6115    }
6116
6117    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6118        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6119        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6120        if (!dexopt && !updateUsage) {
6121            // We aren't going to dexopt or update usage, so bail early.
6122            return false;
6123        }
6124        PackageParser.Package p;
6125        final String targetInstructionSet;
6126        synchronized (mPackages) {
6127            p = mPackages.get(packageName);
6128            if (p == null) {
6129                return false;
6130            }
6131            if (updateUsage) {
6132                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6133            }
6134            mPackageUsage.write(false);
6135            if (!dexopt) {
6136                // We aren't going to dexopt, so bail early.
6137                return false;
6138            }
6139
6140            targetInstructionSet = instructionSet != null ? instructionSet :
6141                    getPrimaryInstructionSet(p.applicationInfo);
6142            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6143                return false;
6144            }
6145        }
6146
6147        synchronized (mInstallLock) {
6148            final String[] instructionSets = new String[] { targetInstructionSet };
6149            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6150                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6151            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6152        }
6153    }
6154
6155    public ArraySet<String> getPackagesThatNeedDexOpt() {
6156        ArraySet<String> pkgs = null;
6157        synchronized (mPackages) {
6158            for (PackageParser.Package p : mPackages.values()) {
6159                if (DEBUG_DEXOPT) {
6160                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6161                }
6162                if (!p.mDexOptPerformed.isEmpty()) {
6163                    continue;
6164                }
6165                if (pkgs == null) {
6166                    pkgs = new ArraySet<String>();
6167                }
6168                pkgs.add(p.packageName);
6169            }
6170        }
6171        return pkgs;
6172    }
6173
6174    public void shutdown() {
6175        mPackageUsage.write(true);
6176    }
6177
6178    @Override
6179    public void forceDexOpt(String packageName) {
6180        enforceSystemOrRoot("forceDexOpt");
6181
6182        PackageParser.Package pkg;
6183        synchronized (mPackages) {
6184            pkg = mPackages.get(packageName);
6185            if (pkg == null) {
6186                throw new IllegalArgumentException("Missing package: " + packageName);
6187            }
6188        }
6189
6190        synchronized (mInstallLock) {
6191            final String[] instructionSets = new String[] {
6192                    getPrimaryInstructionSet(pkg.applicationInfo) };
6193            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6194                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6195            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6196                throw new IllegalStateException("Failed to dexopt: " + res);
6197            }
6198        }
6199    }
6200
6201    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6202        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6203            Slog.w(TAG, "Unable to update from " + oldPkg.name
6204                    + " to " + newPkg.packageName
6205                    + ": old package not in system partition");
6206            return false;
6207        } else if (mPackages.get(oldPkg.name) != null) {
6208            Slog.w(TAG, "Unable to update from " + oldPkg.name
6209                    + " to " + newPkg.packageName
6210                    + ": old package still exists");
6211            return false;
6212        }
6213        return true;
6214    }
6215
6216    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6217        int[] users = sUserManager.getUserIds();
6218        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6219        if (res < 0) {
6220            return res;
6221        }
6222        for (int user : users) {
6223            if (user != 0) {
6224                res = mInstaller.createUserData(volumeUuid, packageName,
6225                        UserHandle.getUid(user, uid), user, seinfo);
6226                if (res < 0) {
6227                    return res;
6228                }
6229            }
6230        }
6231        return res;
6232    }
6233
6234    private int removeDataDirsLI(String volumeUuid, String packageName) {
6235        int[] users = sUserManager.getUserIds();
6236        int res = 0;
6237        for (int user : users) {
6238            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6239            if (resInner < 0) {
6240                res = resInner;
6241            }
6242        }
6243
6244        return res;
6245    }
6246
6247    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6248        int[] users = sUserManager.getUserIds();
6249        int res = 0;
6250        for (int user : users) {
6251            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6252            if (resInner < 0) {
6253                res = resInner;
6254            }
6255        }
6256        return res;
6257    }
6258
6259    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6260            PackageParser.Package changingLib) {
6261        if (file.path != null) {
6262            usesLibraryFiles.add(file.path);
6263            return;
6264        }
6265        PackageParser.Package p = mPackages.get(file.apk);
6266        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6267            // If we are doing this while in the middle of updating a library apk,
6268            // then we need to make sure to use that new apk for determining the
6269            // dependencies here.  (We haven't yet finished committing the new apk
6270            // to the package manager state.)
6271            if (p == null || p.packageName.equals(changingLib.packageName)) {
6272                p = changingLib;
6273            }
6274        }
6275        if (p != null) {
6276            usesLibraryFiles.addAll(p.getAllCodePaths());
6277        }
6278    }
6279
6280    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6281            PackageParser.Package changingLib) throws PackageManagerException {
6282        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6283            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6284            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6285            for (int i=0; i<N; i++) {
6286                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6287                if (file == null) {
6288                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6289                            "Package " + pkg.packageName + " requires unavailable shared library "
6290                            + pkg.usesLibraries.get(i) + "; failing!");
6291                }
6292                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6293            }
6294            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6295            for (int i=0; i<N; i++) {
6296                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6297                if (file == null) {
6298                    Slog.w(TAG, "Package " + pkg.packageName
6299                            + " desires unavailable shared library "
6300                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6301                } else {
6302                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6303                }
6304            }
6305            N = usesLibraryFiles.size();
6306            if (N > 0) {
6307                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6308            } else {
6309                pkg.usesLibraryFiles = null;
6310            }
6311        }
6312    }
6313
6314    private static boolean hasString(List<String> list, List<String> which) {
6315        if (list == null) {
6316            return false;
6317        }
6318        for (int i=list.size()-1; i>=0; i--) {
6319            for (int j=which.size()-1; j>=0; j--) {
6320                if (which.get(j).equals(list.get(i))) {
6321                    return true;
6322                }
6323            }
6324        }
6325        return false;
6326    }
6327
6328    private void updateAllSharedLibrariesLPw() {
6329        for (PackageParser.Package pkg : mPackages.values()) {
6330            try {
6331                updateSharedLibrariesLPw(pkg, null);
6332            } catch (PackageManagerException e) {
6333                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6334            }
6335        }
6336    }
6337
6338    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6339            PackageParser.Package changingPkg) {
6340        ArrayList<PackageParser.Package> res = null;
6341        for (PackageParser.Package pkg : mPackages.values()) {
6342            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6343                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6344                if (res == null) {
6345                    res = new ArrayList<PackageParser.Package>();
6346                }
6347                res.add(pkg);
6348                try {
6349                    updateSharedLibrariesLPw(pkg, changingPkg);
6350                } catch (PackageManagerException e) {
6351                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6352                }
6353            }
6354        }
6355        return res;
6356    }
6357
6358    /**
6359     * Derive the value of the {@code cpuAbiOverride} based on the provided
6360     * value and an optional stored value from the package settings.
6361     */
6362    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6363        String cpuAbiOverride = null;
6364
6365        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6366            cpuAbiOverride = null;
6367        } else if (abiOverride != null) {
6368            cpuAbiOverride = abiOverride;
6369        } else if (settings != null) {
6370            cpuAbiOverride = settings.cpuAbiOverrideString;
6371        }
6372
6373        return cpuAbiOverride;
6374    }
6375
6376    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6377            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6378        boolean success = false;
6379        try {
6380            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6381                    currentTime, user);
6382            success = true;
6383            return res;
6384        } finally {
6385            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6386                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6387            }
6388        }
6389    }
6390
6391    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6392            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6393        final File scanFile = new File(pkg.codePath);
6394        if (pkg.applicationInfo.getCodePath() == null ||
6395                pkg.applicationInfo.getResourcePath() == null) {
6396            // Bail out. The resource and code paths haven't been set.
6397            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6398                    "Code and resource paths haven't been set correctly");
6399        }
6400
6401        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6402            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6403        } else {
6404            // Only allow system apps to be flagged as core apps.
6405            pkg.coreApp = false;
6406        }
6407
6408        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6409            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6410        }
6411
6412        if (mCustomResolverComponentName != null &&
6413                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6414            setUpCustomResolverActivity(pkg);
6415        }
6416
6417        if (pkg.packageName.equals("android")) {
6418            synchronized (mPackages) {
6419                if (mAndroidApplication != null) {
6420                    Slog.w(TAG, "*************************************************");
6421                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6422                    Slog.w(TAG, " file=" + scanFile);
6423                    Slog.w(TAG, "*************************************************");
6424                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6425                            "Core android package being redefined.  Skipping.");
6426                }
6427
6428                // Set up information for our fall-back user intent resolution activity.
6429                mPlatformPackage = pkg;
6430                pkg.mVersionCode = mSdkVersion;
6431                mAndroidApplication = pkg.applicationInfo;
6432
6433                if (!mResolverReplaced) {
6434                    mResolveActivity.applicationInfo = mAndroidApplication;
6435                    mResolveActivity.name = ResolverActivity.class.getName();
6436                    mResolveActivity.packageName = mAndroidApplication.packageName;
6437                    mResolveActivity.processName = "system:ui";
6438                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6439                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6440                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6441                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6442                    mResolveActivity.exported = true;
6443                    mResolveActivity.enabled = true;
6444                    mResolveInfo.activityInfo = mResolveActivity;
6445                    mResolveInfo.priority = 0;
6446                    mResolveInfo.preferredOrder = 0;
6447                    mResolveInfo.match = 0;
6448                    mResolveComponentName = new ComponentName(
6449                            mAndroidApplication.packageName, mResolveActivity.name);
6450                }
6451            }
6452        }
6453
6454        if (DEBUG_PACKAGE_SCANNING) {
6455            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6456                Log.d(TAG, "Scanning package " + pkg.packageName);
6457        }
6458
6459        if (mPackages.containsKey(pkg.packageName)
6460                || mSharedLibraries.containsKey(pkg.packageName)) {
6461            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6462                    "Application package " + pkg.packageName
6463                    + " already installed.  Skipping duplicate.");
6464        }
6465
6466        // If we're only installing presumed-existing packages, require that the
6467        // scanned APK is both already known and at the path previously established
6468        // for it.  Previously unknown packages we pick up normally, but if we have an
6469        // a priori expectation about this package's install presence, enforce it.
6470        // With a singular exception for new system packages. When an OTA contains
6471        // a new system package, we allow the codepath to change from a system location
6472        // to the user-installed location. If we don't allow this change, any newer,
6473        // user-installed version of the application will be ignored.
6474        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6475            if (mExpectingBetter.containsKey(pkg.packageName)) {
6476                logCriticalInfo(Log.WARN,
6477                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6478            } else {
6479                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6480                if (known != null) {
6481                    if (DEBUG_PACKAGE_SCANNING) {
6482                        Log.d(TAG, "Examining " + pkg.codePath
6483                                + " and requiring known paths " + known.codePathString
6484                                + " & " + known.resourcePathString);
6485                    }
6486                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6487                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6488                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6489                                "Application package " + pkg.packageName
6490                                + " found at " + pkg.applicationInfo.getCodePath()
6491                                + " but expected at " + known.codePathString + "; ignoring.");
6492                    }
6493                }
6494            }
6495        }
6496
6497        // Initialize package source and resource directories
6498        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6499        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6500
6501        SharedUserSetting suid = null;
6502        PackageSetting pkgSetting = null;
6503
6504        if (!isSystemApp(pkg)) {
6505            // Only system apps can use these features.
6506            pkg.mOriginalPackages = null;
6507            pkg.mRealPackage = null;
6508            pkg.mAdoptPermissions = null;
6509        }
6510
6511        // writer
6512        synchronized (mPackages) {
6513            if (pkg.mSharedUserId != null) {
6514                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6515                if (suid == null) {
6516                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6517                            "Creating application package " + pkg.packageName
6518                            + " for shared user failed");
6519                }
6520                if (DEBUG_PACKAGE_SCANNING) {
6521                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6522                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6523                                + "): packages=" + suid.packages);
6524                }
6525            }
6526
6527            // Check if we are renaming from an original package name.
6528            PackageSetting origPackage = null;
6529            String realName = null;
6530            if (pkg.mOriginalPackages != null) {
6531                // This package may need to be renamed to a previously
6532                // installed name.  Let's check on that...
6533                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6534                if (pkg.mOriginalPackages.contains(renamed)) {
6535                    // This package had originally been installed as the
6536                    // original name, and we have already taken care of
6537                    // transitioning to the new one.  Just update the new
6538                    // one to continue using the old name.
6539                    realName = pkg.mRealPackage;
6540                    if (!pkg.packageName.equals(renamed)) {
6541                        // Callers into this function may have already taken
6542                        // care of renaming the package; only do it here if
6543                        // it is not already done.
6544                        pkg.setPackageName(renamed);
6545                    }
6546
6547                } else {
6548                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6549                        if ((origPackage = mSettings.peekPackageLPr(
6550                                pkg.mOriginalPackages.get(i))) != null) {
6551                            // We do have the package already installed under its
6552                            // original name...  should we use it?
6553                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6554                                // New package is not compatible with original.
6555                                origPackage = null;
6556                                continue;
6557                            } else if (origPackage.sharedUser != null) {
6558                                // Make sure uid is compatible between packages.
6559                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6560                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6561                                            + " to " + pkg.packageName + ": old uid "
6562                                            + origPackage.sharedUser.name
6563                                            + " differs from " + pkg.mSharedUserId);
6564                                    origPackage = null;
6565                                    continue;
6566                                }
6567                            } else {
6568                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6569                                        + pkg.packageName + " to old name " + origPackage.name);
6570                            }
6571                            break;
6572                        }
6573                    }
6574                }
6575            }
6576
6577            if (mTransferedPackages.contains(pkg.packageName)) {
6578                Slog.w(TAG, "Package " + pkg.packageName
6579                        + " was transferred to another, but its .apk remains");
6580            }
6581
6582            // Just create the setting, don't add it yet. For already existing packages
6583            // the PkgSetting exists already and doesn't have to be created.
6584            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6585                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6586                    pkg.applicationInfo.primaryCpuAbi,
6587                    pkg.applicationInfo.secondaryCpuAbi,
6588                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6589                    user, false);
6590            if (pkgSetting == null) {
6591                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6592                        "Creating application package " + pkg.packageName + " failed");
6593            }
6594
6595            if (pkgSetting.origPackage != null) {
6596                // If we are first transitioning from an original package,
6597                // fix up the new package's name now.  We need to do this after
6598                // looking up the package under its new name, so getPackageLP
6599                // can take care of fiddling things correctly.
6600                pkg.setPackageName(origPackage.name);
6601
6602                // File a report about this.
6603                String msg = "New package " + pkgSetting.realName
6604                        + " renamed to replace old package " + pkgSetting.name;
6605                reportSettingsProblem(Log.WARN, msg);
6606
6607                // Make a note of it.
6608                mTransferedPackages.add(origPackage.name);
6609
6610                // No longer need to retain this.
6611                pkgSetting.origPackage = null;
6612            }
6613
6614            if (realName != null) {
6615                // Make a note of it.
6616                mTransferedPackages.add(pkg.packageName);
6617            }
6618
6619            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6620                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6621            }
6622
6623            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6624                // Check all shared libraries and map to their actual file path.
6625                // We only do this here for apps not on a system dir, because those
6626                // are the only ones that can fail an install due to this.  We
6627                // will take care of the system apps by updating all of their
6628                // library paths after the scan is done.
6629                updateSharedLibrariesLPw(pkg, null);
6630            }
6631
6632            if (mFoundPolicyFile) {
6633                SELinuxMMAC.assignSeinfoValue(pkg);
6634            }
6635
6636            pkg.applicationInfo.uid = pkgSetting.appId;
6637            pkg.mExtras = pkgSetting;
6638            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6639                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6640                    // We just determined the app is signed correctly, so bring
6641                    // over the latest parsed certs.
6642                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6643                } else {
6644                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6645                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6646                                "Package " + pkg.packageName + " upgrade keys do not match the "
6647                                + "previously installed version");
6648                    } else {
6649                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6650                        String msg = "System package " + pkg.packageName
6651                            + " signature changed; retaining data.";
6652                        reportSettingsProblem(Log.WARN, msg);
6653                    }
6654                }
6655            } else {
6656                try {
6657                    verifySignaturesLP(pkgSetting, pkg);
6658                    // We just determined the app is signed correctly, so bring
6659                    // over the latest parsed certs.
6660                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6661                } catch (PackageManagerException e) {
6662                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6663                        throw e;
6664                    }
6665                    // The signature has changed, but this package is in the system
6666                    // image...  let's recover!
6667                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6668                    // However...  if this package is part of a shared user, but it
6669                    // doesn't match the signature of the shared user, let's fail.
6670                    // What this means is that you can't change the signatures
6671                    // associated with an overall shared user, which doesn't seem all
6672                    // that unreasonable.
6673                    if (pkgSetting.sharedUser != null) {
6674                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6675                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6676                            throw new PackageManagerException(
6677                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6678                                            "Signature mismatch for shared user : "
6679                                            + pkgSetting.sharedUser);
6680                        }
6681                    }
6682                    // File a report about this.
6683                    String msg = "System package " + pkg.packageName
6684                        + " signature changed; retaining data.";
6685                    reportSettingsProblem(Log.WARN, msg);
6686                }
6687            }
6688            // Verify that this new package doesn't have any content providers
6689            // that conflict with existing packages.  Only do this if the
6690            // package isn't already installed, since we don't want to break
6691            // things that are installed.
6692            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6693                final int N = pkg.providers.size();
6694                int i;
6695                for (i=0; i<N; i++) {
6696                    PackageParser.Provider p = pkg.providers.get(i);
6697                    if (p.info.authority != null) {
6698                        String names[] = p.info.authority.split(";");
6699                        for (int j = 0; j < names.length; j++) {
6700                            if (mProvidersByAuthority.containsKey(names[j])) {
6701                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6702                                final String otherPackageName =
6703                                        ((other != null && other.getComponentName() != null) ?
6704                                                other.getComponentName().getPackageName() : "?");
6705                                throw new PackageManagerException(
6706                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6707                                                "Can't install because provider name " + names[j]
6708                                                + " (in package " + pkg.applicationInfo.packageName
6709                                                + ") is already used by " + otherPackageName);
6710                            }
6711                        }
6712                    }
6713                }
6714            }
6715
6716            if (pkg.mAdoptPermissions != null) {
6717                // This package wants to adopt ownership of permissions from
6718                // another package.
6719                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6720                    final String origName = pkg.mAdoptPermissions.get(i);
6721                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6722                    if (orig != null) {
6723                        if (verifyPackageUpdateLPr(orig, pkg)) {
6724                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6725                                    + pkg.packageName);
6726                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6727                        }
6728                    }
6729                }
6730            }
6731        }
6732
6733        final String pkgName = pkg.packageName;
6734
6735        final long scanFileTime = scanFile.lastModified();
6736        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6737        pkg.applicationInfo.processName = fixProcessName(
6738                pkg.applicationInfo.packageName,
6739                pkg.applicationInfo.processName,
6740                pkg.applicationInfo.uid);
6741
6742        File dataPath;
6743        if (mPlatformPackage == pkg) {
6744            // The system package is special.
6745            dataPath = new File(Environment.getDataDirectory(), "system");
6746
6747            pkg.applicationInfo.dataDir = dataPath.getPath();
6748
6749        } else {
6750            // This is a normal package, need to make its data directory.
6751            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6752                    UserHandle.USER_OWNER, pkg.packageName);
6753
6754            boolean uidError = false;
6755            if (dataPath.exists()) {
6756                int currentUid = 0;
6757                try {
6758                    StructStat stat = Os.stat(dataPath.getPath());
6759                    currentUid = stat.st_uid;
6760                } catch (ErrnoException e) {
6761                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6762                }
6763
6764                // If we have mismatched owners for the data path, we have a problem.
6765                if (currentUid != pkg.applicationInfo.uid) {
6766                    boolean recovered = false;
6767                    if (currentUid == 0) {
6768                        // The directory somehow became owned by root.  Wow.
6769                        // This is probably because the system was stopped while
6770                        // installd was in the middle of messing with its libs
6771                        // directory.  Ask installd to fix that.
6772                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6773                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6774                        if (ret >= 0) {
6775                            recovered = true;
6776                            String msg = "Package " + pkg.packageName
6777                                    + " unexpectedly changed to uid 0; recovered to " +
6778                                    + pkg.applicationInfo.uid;
6779                            reportSettingsProblem(Log.WARN, msg);
6780                        }
6781                    }
6782                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6783                            || (scanFlags&SCAN_BOOTING) != 0)) {
6784                        // If this is a system app, we can at least delete its
6785                        // current data so the application will still work.
6786                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6787                        if (ret >= 0) {
6788                            // TODO: Kill the processes first
6789                            // Old data gone!
6790                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6791                                    ? "System package " : "Third party package ";
6792                            String msg = prefix + pkg.packageName
6793                                    + " has changed from uid: "
6794                                    + currentUid + " to "
6795                                    + pkg.applicationInfo.uid + "; old data erased";
6796                            reportSettingsProblem(Log.WARN, msg);
6797                            recovered = true;
6798
6799                            // And now re-install the app.
6800                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6801                                    pkg.applicationInfo.seinfo);
6802                            if (ret == -1) {
6803                                // Ack should not happen!
6804                                msg = prefix + pkg.packageName
6805                                        + " could not have data directory re-created after delete.";
6806                                reportSettingsProblem(Log.WARN, msg);
6807                                throw new PackageManagerException(
6808                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6809                            }
6810                        }
6811                        if (!recovered) {
6812                            mHasSystemUidErrors = true;
6813                        }
6814                    } else if (!recovered) {
6815                        // If we allow this install to proceed, we will be broken.
6816                        // Abort, abort!
6817                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6818                                "scanPackageLI");
6819                    }
6820                    if (!recovered) {
6821                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6822                            + pkg.applicationInfo.uid + "/fs_"
6823                            + currentUid;
6824                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6825                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6826                        String msg = "Package " + pkg.packageName
6827                                + " has mismatched uid: "
6828                                + currentUid + " on disk, "
6829                                + pkg.applicationInfo.uid + " in settings";
6830                        // writer
6831                        synchronized (mPackages) {
6832                            mSettings.mReadMessages.append(msg);
6833                            mSettings.mReadMessages.append('\n');
6834                            uidError = true;
6835                            if (!pkgSetting.uidError) {
6836                                reportSettingsProblem(Log.ERROR, msg);
6837                            }
6838                        }
6839                    }
6840                }
6841                pkg.applicationInfo.dataDir = dataPath.getPath();
6842                if (mShouldRestoreconData) {
6843                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6844                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6845                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6846                }
6847            } else {
6848                if (DEBUG_PACKAGE_SCANNING) {
6849                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6850                        Log.v(TAG, "Want this data dir: " + dataPath);
6851                }
6852                //invoke installer to do the actual installation
6853                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6854                        pkg.applicationInfo.seinfo);
6855                if (ret < 0) {
6856                    // Error from installer
6857                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6858                            "Unable to create data dirs [errorCode=" + ret + "]");
6859                }
6860
6861                if (dataPath.exists()) {
6862                    pkg.applicationInfo.dataDir = dataPath.getPath();
6863                } else {
6864                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6865                    pkg.applicationInfo.dataDir = null;
6866                }
6867            }
6868
6869            pkgSetting.uidError = uidError;
6870        }
6871
6872        final String path = scanFile.getPath();
6873        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6874
6875        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6876            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6877
6878            // Some system apps still use directory structure for native libraries
6879            // in which case we might end up not detecting abi solely based on apk
6880            // structure. Try to detect abi based on directory structure.
6881            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6882                    pkg.applicationInfo.primaryCpuAbi == null) {
6883                setBundledAppAbisAndRoots(pkg, pkgSetting);
6884                setNativeLibraryPaths(pkg);
6885            }
6886
6887        } else {
6888            if ((scanFlags & SCAN_MOVE) != 0) {
6889                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6890                // but we already have this packages package info in the PackageSetting. We just
6891                // use that and derive the native library path based on the new codepath.
6892                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6893                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6894            }
6895
6896            // Set native library paths again. For moves, the path will be updated based on the
6897            // ABIs we've determined above. For non-moves, the path will be updated based on the
6898            // ABIs we determined during compilation, but the path will depend on the final
6899            // package path (after the rename away from the stage path).
6900            setNativeLibraryPaths(pkg);
6901        }
6902
6903        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6904        final int[] userIds = sUserManager.getUserIds();
6905        synchronized (mInstallLock) {
6906            // Make sure all user data directories are ready to roll; we're okay
6907            // if they already exist
6908            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6909                for (int userId : userIds) {
6910                    if (userId != 0) {
6911                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6912                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6913                                pkg.applicationInfo.seinfo);
6914                    }
6915                }
6916            }
6917
6918            // Create a native library symlink only if we have native libraries
6919            // and if the native libraries are 32 bit libraries. We do not provide
6920            // this symlink for 64 bit libraries.
6921            if (pkg.applicationInfo.primaryCpuAbi != null &&
6922                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6923                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6924                for (int userId : userIds) {
6925                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6926                            nativeLibPath, userId) < 0) {
6927                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6928                                "Failed linking native library dir (user=" + userId + ")");
6929                    }
6930                }
6931            }
6932        }
6933
6934        // This is a special case for the "system" package, where the ABI is
6935        // dictated by the zygote configuration (and init.rc). We should keep track
6936        // of this ABI so that we can deal with "normal" applications that run under
6937        // the same UID correctly.
6938        if (mPlatformPackage == pkg) {
6939            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6940                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6941        }
6942
6943        // If there's a mismatch between the abi-override in the package setting
6944        // and the abiOverride specified for the install. Warn about this because we
6945        // would've already compiled the app without taking the package setting into
6946        // account.
6947        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6948            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6949                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6950                        " for package: " + pkg.packageName);
6951            }
6952        }
6953
6954        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6955        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6956        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6957
6958        // Copy the derived override back to the parsed package, so that we can
6959        // update the package settings accordingly.
6960        pkg.cpuAbiOverride = cpuAbiOverride;
6961
6962        if (DEBUG_ABI_SELECTION) {
6963            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6964                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6965                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6966        }
6967
6968        // Push the derived path down into PackageSettings so we know what to
6969        // clean up at uninstall time.
6970        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6971
6972        if (DEBUG_ABI_SELECTION) {
6973            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6974                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6975                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6976        }
6977
6978        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6979            // We don't do this here during boot because we can do it all
6980            // at once after scanning all existing packages.
6981            //
6982            // We also do this *before* we perform dexopt on this package, so that
6983            // we can avoid redundant dexopts, and also to make sure we've got the
6984            // code and package path correct.
6985            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6986                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6987        }
6988
6989        if ((scanFlags & SCAN_NO_DEX) == 0) {
6990            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6991                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6992            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6993                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6994            }
6995        }
6996        if (mFactoryTest && pkg.requestedPermissions.contains(
6997                android.Manifest.permission.FACTORY_TEST)) {
6998            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6999        }
7000
7001        ArrayList<PackageParser.Package> clientLibPkgs = null;
7002
7003        // writer
7004        synchronized (mPackages) {
7005            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7006                // Only system apps can add new shared libraries.
7007                if (pkg.libraryNames != null) {
7008                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7009                        String name = pkg.libraryNames.get(i);
7010                        boolean allowed = false;
7011                        if (pkg.isUpdatedSystemApp()) {
7012                            // New library entries can only be added through the
7013                            // system image.  This is important to get rid of a lot
7014                            // of nasty edge cases: for example if we allowed a non-
7015                            // system update of the app to add a library, then uninstalling
7016                            // the update would make the library go away, and assumptions
7017                            // we made such as through app install filtering would now
7018                            // have allowed apps on the device which aren't compatible
7019                            // with it.  Better to just have the restriction here, be
7020                            // conservative, and create many fewer cases that can negatively
7021                            // impact the user experience.
7022                            final PackageSetting sysPs = mSettings
7023                                    .getDisabledSystemPkgLPr(pkg.packageName);
7024                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7025                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7026                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7027                                        allowed = true;
7028                                        allowed = true;
7029                                        break;
7030                                    }
7031                                }
7032                            }
7033                        } else {
7034                            allowed = true;
7035                        }
7036                        if (allowed) {
7037                            if (!mSharedLibraries.containsKey(name)) {
7038                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7039                            } else if (!name.equals(pkg.packageName)) {
7040                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7041                                        + name + " already exists; skipping");
7042                            }
7043                        } else {
7044                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7045                                    + name + " that is not declared on system image; skipping");
7046                        }
7047                    }
7048                    if ((scanFlags&SCAN_BOOTING) == 0) {
7049                        // If we are not booting, we need to update any applications
7050                        // that are clients of our shared library.  If we are booting,
7051                        // this will all be done once the scan is complete.
7052                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7053                    }
7054                }
7055            }
7056        }
7057
7058        // We also need to dexopt any apps that are dependent on this library.  Note that
7059        // if these fail, we should abort the install since installing the library will
7060        // result in some apps being broken.
7061        if (clientLibPkgs != null) {
7062            if ((scanFlags & SCAN_NO_DEX) == 0) {
7063                for (int i = 0; i < clientLibPkgs.size(); i++) {
7064                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7065                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7066                            null /* instruction sets */, forceDex,
7067                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7068                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7069                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7070                                "scanPackageLI failed to dexopt clientLibPkgs");
7071                    }
7072                }
7073            }
7074        }
7075
7076        // Also need to kill any apps that are dependent on the library.
7077        if (clientLibPkgs != null) {
7078            for (int i=0; i<clientLibPkgs.size(); i++) {
7079                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7080                killApplication(clientPkg.applicationInfo.packageName,
7081                        clientPkg.applicationInfo.uid, "update lib");
7082            }
7083        }
7084
7085        // Make sure we're not adding any bogus keyset info
7086        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7087        ksms.assertScannedPackageValid(pkg);
7088
7089        // writer
7090        synchronized (mPackages) {
7091            // We don't expect installation to fail beyond this point
7092
7093            // Add the new setting to mSettings
7094            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7095            // Add the new setting to mPackages
7096            mPackages.put(pkg.applicationInfo.packageName, pkg);
7097            // Make sure we don't accidentally delete its data.
7098            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7099            while (iter.hasNext()) {
7100                PackageCleanItem item = iter.next();
7101                if (pkgName.equals(item.packageName)) {
7102                    iter.remove();
7103                }
7104            }
7105
7106            // Take care of first install / last update times.
7107            if (currentTime != 0) {
7108                if (pkgSetting.firstInstallTime == 0) {
7109                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7110                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7111                    pkgSetting.lastUpdateTime = currentTime;
7112                }
7113            } else if (pkgSetting.firstInstallTime == 0) {
7114                // We need *something*.  Take time time stamp of the file.
7115                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7116            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7117                if (scanFileTime != pkgSetting.timeStamp) {
7118                    // A package on the system image has changed; consider this
7119                    // to be an update.
7120                    pkgSetting.lastUpdateTime = scanFileTime;
7121                }
7122            }
7123
7124            // Add the package's KeySets to the global KeySetManagerService
7125            ksms.addScannedPackageLPw(pkg);
7126
7127            int N = pkg.providers.size();
7128            StringBuilder r = null;
7129            int i;
7130            for (i=0; i<N; i++) {
7131                PackageParser.Provider p = pkg.providers.get(i);
7132                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7133                        p.info.processName, pkg.applicationInfo.uid);
7134                mProviders.addProvider(p);
7135                p.syncable = p.info.isSyncable;
7136                if (p.info.authority != null) {
7137                    String names[] = p.info.authority.split(";");
7138                    p.info.authority = null;
7139                    for (int j = 0; j < names.length; j++) {
7140                        if (j == 1 && p.syncable) {
7141                            // We only want the first authority for a provider to possibly be
7142                            // syncable, so if we already added this provider using a different
7143                            // authority clear the syncable flag. We copy the provider before
7144                            // changing it because the mProviders object contains a reference
7145                            // to a provider that we don't want to change.
7146                            // Only do this for the second authority since the resulting provider
7147                            // object can be the same for all future authorities for this provider.
7148                            p = new PackageParser.Provider(p);
7149                            p.syncable = false;
7150                        }
7151                        if (!mProvidersByAuthority.containsKey(names[j])) {
7152                            mProvidersByAuthority.put(names[j], p);
7153                            if (p.info.authority == null) {
7154                                p.info.authority = names[j];
7155                            } else {
7156                                p.info.authority = p.info.authority + ";" + names[j];
7157                            }
7158                            if (DEBUG_PACKAGE_SCANNING) {
7159                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7160                                    Log.d(TAG, "Registered content provider: " + names[j]
7161                                            + ", className = " + p.info.name + ", isSyncable = "
7162                                            + p.info.isSyncable);
7163                            }
7164                        } else {
7165                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7166                            Slog.w(TAG, "Skipping provider name " + names[j] +
7167                                    " (in package " + pkg.applicationInfo.packageName +
7168                                    "): name already used by "
7169                                    + ((other != null && other.getComponentName() != null)
7170                                            ? other.getComponentName().getPackageName() : "?"));
7171                        }
7172                    }
7173                }
7174                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7175                    if (r == null) {
7176                        r = new StringBuilder(256);
7177                    } else {
7178                        r.append(' ');
7179                    }
7180                    r.append(p.info.name);
7181                }
7182            }
7183            if (r != null) {
7184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7185            }
7186
7187            N = pkg.services.size();
7188            r = null;
7189            for (i=0; i<N; i++) {
7190                PackageParser.Service s = pkg.services.get(i);
7191                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7192                        s.info.processName, pkg.applicationInfo.uid);
7193                mServices.addService(s);
7194                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7195                    if (r == null) {
7196                        r = new StringBuilder(256);
7197                    } else {
7198                        r.append(' ');
7199                    }
7200                    r.append(s.info.name);
7201                }
7202            }
7203            if (r != null) {
7204                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7205            }
7206
7207            N = pkg.receivers.size();
7208            r = null;
7209            for (i=0; i<N; i++) {
7210                PackageParser.Activity a = pkg.receivers.get(i);
7211                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7212                        a.info.processName, pkg.applicationInfo.uid);
7213                mReceivers.addActivity(a, "receiver");
7214                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7215                    if (r == null) {
7216                        r = new StringBuilder(256);
7217                    } else {
7218                        r.append(' ');
7219                    }
7220                    r.append(a.info.name);
7221                }
7222            }
7223            if (r != null) {
7224                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7225            }
7226
7227            N = pkg.activities.size();
7228            r = null;
7229            for (i=0; i<N; i++) {
7230                PackageParser.Activity a = pkg.activities.get(i);
7231                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7232                        a.info.processName, pkg.applicationInfo.uid);
7233                mActivities.addActivity(a, "activity");
7234                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7235                    if (r == null) {
7236                        r = new StringBuilder(256);
7237                    } else {
7238                        r.append(' ');
7239                    }
7240                    r.append(a.info.name);
7241                }
7242            }
7243            if (r != null) {
7244                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7245            }
7246
7247            N = pkg.permissionGroups.size();
7248            r = null;
7249            for (i=0; i<N; i++) {
7250                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7251                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7252                if (cur == null) {
7253                    mPermissionGroups.put(pg.info.name, pg);
7254                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7255                        if (r == null) {
7256                            r = new StringBuilder(256);
7257                        } else {
7258                            r.append(' ');
7259                        }
7260                        r.append(pg.info.name);
7261                    }
7262                } else {
7263                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7264                            + pg.info.packageName + " ignored: original from "
7265                            + cur.info.packageName);
7266                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7267                        if (r == null) {
7268                            r = new StringBuilder(256);
7269                        } else {
7270                            r.append(' ');
7271                        }
7272                        r.append("DUP:");
7273                        r.append(pg.info.name);
7274                    }
7275                }
7276            }
7277            if (r != null) {
7278                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7279            }
7280
7281            N = pkg.permissions.size();
7282            r = null;
7283            for (i=0; i<N; i++) {
7284                PackageParser.Permission p = pkg.permissions.get(i);
7285
7286                // Now that permission groups have a special meaning, we ignore permission
7287                // groups for legacy apps to prevent unexpected behavior. In particular,
7288                // permissions for one app being granted to someone just becuase they happen
7289                // to be in a group defined by another app (before this had no implications).
7290                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7291                    p.group = mPermissionGroups.get(p.info.group);
7292                    // Warn for a permission in an unknown group.
7293                    if (p.info.group != null && p.group == null) {
7294                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7295                                + p.info.packageName + " in an unknown group " + p.info.group);
7296                    }
7297                }
7298
7299                ArrayMap<String, BasePermission> permissionMap =
7300                        p.tree ? mSettings.mPermissionTrees
7301                                : mSettings.mPermissions;
7302                BasePermission bp = permissionMap.get(p.info.name);
7303
7304                // Allow system apps to redefine non-system permissions
7305                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7306                    final boolean currentOwnerIsSystem = (bp.perm != null
7307                            && isSystemApp(bp.perm.owner));
7308                    if (isSystemApp(p.owner)) {
7309                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7310                            // It's a built-in permission and no owner, take ownership now
7311                            bp.packageSetting = pkgSetting;
7312                            bp.perm = p;
7313                            bp.uid = pkg.applicationInfo.uid;
7314                            bp.sourcePackage = p.info.packageName;
7315                        } else if (!currentOwnerIsSystem) {
7316                            String msg = "New decl " + p.owner + " of permission  "
7317                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7318                            reportSettingsProblem(Log.WARN, msg);
7319                            bp = null;
7320                        }
7321                    }
7322                }
7323
7324                if (bp == null) {
7325                    bp = new BasePermission(p.info.name, p.info.packageName,
7326                            BasePermission.TYPE_NORMAL);
7327                    permissionMap.put(p.info.name, bp);
7328                }
7329
7330                if (bp.perm == null) {
7331                    if (bp.sourcePackage == null
7332                            || bp.sourcePackage.equals(p.info.packageName)) {
7333                        BasePermission tree = findPermissionTreeLP(p.info.name);
7334                        if (tree == null
7335                                || tree.sourcePackage.equals(p.info.packageName)) {
7336                            bp.packageSetting = pkgSetting;
7337                            bp.perm = p;
7338                            bp.uid = pkg.applicationInfo.uid;
7339                            bp.sourcePackage = p.info.packageName;
7340                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7341                                if (r == null) {
7342                                    r = new StringBuilder(256);
7343                                } else {
7344                                    r.append(' ');
7345                                }
7346                                r.append(p.info.name);
7347                            }
7348                        } else {
7349                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7350                                    + p.info.packageName + " ignored: base tree "
7351                                    + tree.name + " is from package "
7352                                    + tree.sourcePackage);
7353                        }
7354                    } else {
7355                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7356                                + p.info.packageName + " ignored: original from "
7357                                + bp.sourcePackage);
7358                    }
7359                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7360                    if (r == null) {
7361                        r = new StringBuilder(256);
7362                    } else {
7363                        r.append(' ');
7364                    }
7365                    r.append("DUP:");
7366                    r.append(p.info.name);
7367                }
7368                if (bp.perm == p) {
7369                    bp.protectionLevel = p.info.protectionLevel;
7370                }
7371            }
7372
7373            if (r != null) {
7374                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7375            }
7376
7377            N = pkg.instrumentation.size();
7378            r = null;
7379            for (i=0; i<N; i++) {
7380                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7381                a.info.packageName = pkg.applicationInfo.packageName;
7382                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7383                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7384                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7385                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7386                a.info.dataDir = pkg.applicationInfo.dataDir;
7387
7388                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7389                // need other information about the application, like the ABI and what not ?
7390                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7391                mInstrumentation.put(a.getComponentName(), a);
7392                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7393                    if (r == null) {
7394                        r = new StringBuilder(256);
7395                    } else {
7396                        r.append(' ');
7397                    }
7398                    r.append(a.info.name);
7399                }
7400            }
7401            if (r != null) {
7402                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7403            }
7404
7405            if (pkg.protectedBroadcasts != null) {
7406                N = pkg.protectedBroadcasts.size();
7407                for (i=0; i<N; i++) {
7408                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7409                }
7410            }
7411
7412            pkgSetting.setTimeStamp(scanFileTime);
7413
7414            // Create idmap files for pairs of (packages, overlay packages).
7415            // Note: "android", ie framework-res.apk, is handled by native layers.
7416            if (pkg.mOverlayTarget != null) {
7417                // This is an overlay package.
7418                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7419                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7420                        mOverlays.put(pkg.mOverlayTarget,
7421                                new ArrayMap<String, PackageParser.Package>());
7422                    }
7423                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7424                    map.put(pkg.packageName, pkg);
7425                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7426                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7427                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7428                                "scanPackageLI failed to createIdmap");
7429                    }
7430                }
7431            } else if (mOverlays.containsKey(pkg.packageName) &&
7432                    !pkg.packageName.equals("android")) {
7433                // This is a regular package, with one or more known overlay packages.
7434                createIdmapsForPackageLI(pkg);
7435            }
7436        }
7437
7438        return pkg;
7439    }
7440
7441    /**
7442     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7443     * is derived purely on the basis of the contents of {@code scanFile} and
7444     * {@code cpuAbiOverride}.
7445     *
7446     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7447     */
7448    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7449                                 String cpuAbiOverride, boolean extractLibs)
7450            throws PackageManagerException {
7451        // TODO: We can probably be smarter about this stuff. For installed apps,
7452        // we can calculate this information at install time once and for all. For
7453        // system apps, we can probably assume that this information doesn't change
7454        // after the first boot scan. As things stand, we do lots of unnecessary work.
7455
7456        // Give ourselves some initial paths; we'll come back for another
7457        // pass once we've determined ABI below.
7458        setNativeLibraryPaths(pkg);
7459
7460        // We would never need to extract libs for forward-locked and external packages,
7461        // since the container service will do it for us. We shouldn't attempt to
7462        // extract libs from system app when it was not updated.
7463        if (pkg.isForwardLocked() || isExternal(pkg) ||
7464            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7465            extractLibs = false;
7466        }
7467
7468        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7469        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7470
7471        NativeLibraryHelper.Handle handle = null;
7472        try {
7473            handle = NativeLibraryHelper.Handle.create(pkg);
7474            // TODO(multiArch): This can be null for apps that didn't go through the
7475            // usual installation process. We can calculate it again, like we
7476            // do during install time.
7477            //
7478            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7479            // unnecessary.
7480            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7481
7482            // Null out the abis so that they can be recalculated.
7483            pkg.applicationInfo.primaryCpuAbi = null;
7484            pkg.applicationInfo.secondaryCpuAbi = null;
7485            if (isMultiArch(pkg.applicationInfo)) {
7486                // Warn if we've set an abiOverride for multi-lib packages..
7487                // By definition, we need to copy both 32 and 64 bit libraries for
7488                // such packages.
7489                if (pkg.cpuAbiOverride != null
7490                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7491                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7492                }
7493
7494                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7495                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7496                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7497                    if (extractLibs) {
7498                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7499                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7500                                useIsaSpecificSubdirs);
7501                    } else {
7502                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7503                    }
7504                }
7505
7506                maybeThrowExceptionForMultiArchCopy(
7507                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7508
7509                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7510                    if (extractLibs) {
7511                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7512                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7513                                useIsaSpecificSubdirs);
7514                    } else {
7515                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7516                    }
7517                }
7518
7519                maybeThrowExceptionForMultiArchCopy(
7520                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7521
7522                if (abi64 >= 0) {
7523                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7524                }
7525
7526                if (abi32 >= 0) {
7527                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7528                    if (abi64 >= 0) {
7529                        pkg.applicationInfo.secondaryCpuAbi = abi;
7530                    } else {
7531                        pkg.applicationInfo.primaryCpuAbi = abi;
7532                    }
7533                }
7534            } else {
7535                String[] abiList = (cpuAbiOverride != null) ?
7536                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7537
7538                // Enable gross and lame hacks for apps that are built with old
7539                // SDK tools. We must scan their APKs for renderscript bitcode and
7540                // not launch them if it's present. Don't bother checking on devices
7541                // that don't have 64 bit support.
7542                boolean needsRenderScriptOverride = false;
7543                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7544                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7545                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7546                    needsRenderScriptOverride = true;
7547                }
7548
7549                final int copyRet;
7550                if (extractLibs) {
7551                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7552                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7553                } else {
7554                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7555                }
7556
7557                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7558                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7559                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7560                }
7561
7562                if (copyRet >= 0) {
7563                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7564                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7565                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7566                } else if (needsRenderScriptOverride) {
7567                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7568                }
7569            }
7570        } catch (IOException ioe) {
7571            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7572        } finally {
7573            IoUtils.closeQuietly(handle);
7574        }
7575
7576        // Now that we've calculated the ABIs and determined if it's an internal app,
7577        // we will go ahead and populate the nativeLibraryPath.
7578        setNativeLibraryPaths(pkg);
7579    }
7580
7581    /**
7582     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7583     * i.e, so that all packages can be run inside a single process if required.
7584     *
7585     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7586     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7587     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7588     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7589     * updating a package that belongs to a shared user.
7590     *
7591     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7592     * adds unnecessary complexity.
7593     */
7594    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7595            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7596        String requiredInstructionSet = null;
7597        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7598            requiredInstructionSet = VMRuntime.getInstructionSet(
7599                     scannedPackage.applicationInfo.primaryCpuAbi);
7600        }
7601
7602        PackageSetting requirer = null;
7603        for (PackageSetting ps : packagesForUser) {
7604            // If packagesForUser contains scannedPackage, we skip it. This will happen
7605            // when scannedPackage is an update of an existing package. Without this check,
7606            // we will never be able to change the ABI of any package belonging to a shared
7607            // user, even if it's compatible with other packages.
7608            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7609                if (ps.primaryCpuAbiString == null) {
7610                    continue;
7611                }
7612
7613                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7614                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7615                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7616                    // this but there's not much we can do.
7617                    String errorMessage = "Instruction set mismatch, "
7618                            + ((requirer == null) ? "[caller]" : requirer)
7619                            + " requires " + requiredInstructionSet + " whereas " + ps
7620                            + " requires " + instructionSet;
7621                    Slog.w(TAG, errorMessage);
7622                }
7623
7624                if (requiredInstructionSet == null) {
7625                    requiredInstructionSet = instructionSet;
7626                    requirer = ps;
7627                }
7628            }
7629        }
7630
7631        if (requiredInstructionSet != null) {
7632            String adjustedAbi;
7633            if (requirer != null) {
7634                // requirer != null implies that either scannedPackage was null or that scannedPackage
7635                // did not require an ABI, in which case we have to adjust scannedPackage to match
7636                // the ABI of the set (which is the same as requirer's ABI)
7637                adjustedAbi = requirer.primaryCpuAbiString;
7638                if (scannedPackage != null) {
7639                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7640                }
7641            } else {
7642                // requirer == null implies that we're updating all ABIs in the set to
7643                // match scannedPackage.
7644                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7645            }
7646
7647            for (PackageSetting ps : packagesForUser) {
7648                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7649                    if (ps.primaryCpuAbiString != null) {
7650                        continue;
7651                    }
7652
7653                    ps.primaryCpuAbiString = adjustedAbi;
7654                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7655                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7656                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7657
7658                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7659                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7660                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7661                            ps.primaryCpuAbiString = null;
7662                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7663                            return;
7664                        } else {
7665                            mInstaller.rmdex(ps.codePathString,
7666                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7667                        }
7668                    }
7669                }
7670            }
7671        }
7672    }
7673
7674    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7675        synchronized (mPackages) {
7676            mResolverReplaced = true;
7677            // Set up information for custom user intent resolution activity.
7678            mResolveActivity.applicationInfo = pkg.applicationInfo;
7679            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7680            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7681            mResolveActivity.processName = pkg.applicationInfo.packageName;
7682            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7683            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7684                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7685            mResolveActivity.theme = 0;
7686            mResolveActivity.exported = true;
7687            mResolveActivity.enabled = true;
7688            mResolveInfo.activityInfo = mResolveActivity;
7689            mResolveInfo.priority = 0;
7690            mResolveInfo.preferredOrder = 0;
7691            mResolveInfo.match = 0;
7692            mResolveComponentName = mCustomResolverComponentName;
7693            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7694                    mResolveComponentName);
7695        }
7696    }
7697
7698    private static String calculateBundledApkRoot(final String codePathString) {
7699        final File codePath = new File(codePathString);
7700        final File codeRoot;
7701        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7702            codeRoot = Environment.getRootDirectory();
7703        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7704            codeRoot = Environment.getOemDirectory();
7705        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7706            codeRoot = Environment.getVendorDirectory();
7707        } else {
7708            // Unrecognized code path; take its top real segment as the apk root:
7709            // e.g. /something/app/blah.apk => /something
7710            try {
7711                File f = codePath.getCanonicalFile();
7712                File parent = f.getParentFile();    // non-null because codePath is a file
7713                File tmp;
7714                while ((tmp = parent.getParentFile()) != null) {
7715                    f = parent;
7716                    parent = tmp;
7717                }
7718                codeRoot = f;
7719                Slog.w(TAG, "Unrecognized code path "
7720                        + codePath + " - using " + codeRoot);
7721            } catch (IOException e) {
7722                // Can't canonicalize the code path -- shenanigans?
7723                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7724                return Environment.getRootDirectory().getPath();
7725            }
7726        }
7727        return codeRoot.getPath();
7728    }
7729
7730    /**
7731     * Derive and set the location of native libraries for the given package,
7732     * which varies depending on where and how the package was installed.
7733     */
7734    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7735        final ApplicationInfo info = pkg.applicationInfo;
7736        final String codePath = pkg.codePath;
7737        final File codeFile = new File(codePath);
7738        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7739        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7740
7741        info.nativeLibraryRootDir = null;
7742        info.nativeLibraryRootRequiresIsa = false;
7743        info.nativeLibraryDir = null;
7744        info.secondaryNativeLibraryDir = null;
7745
7746        if (isApkFile(codeFile)) {
7747            // Monolithic install
7748            if (bundledApp) {
7749                // If "/system/lib64/apkname" exists, assume that is the per-package
7750                // native library directory to use; otherwise use "/system/lib/apkname".
7751                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7752                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7753                        getPrimaryInstructionSet(info));
7754
7755                // This is a bundled system app so choose the path based on the ABI.
7756                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7757                // is just the default path.
7758                final String apkName = deriveCodePathName(codePath);
7759                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7760                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7761                        apkName).getAbsolutePath();
7762
7763                if (info.secondaryCpuAbi != null) {
7764                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7765                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7766                            secondaryLibDir, apkName).getAbsolutePath();
7767                }
7768            } else if (asecApp) {
7769                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7770                        .getAbsolutePath();
7771            } else {
7772                final String apkName = deriveCodePathName(codePath);
7773                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7774                        .getAbsolutePath();
7775            }
7776
7777            info.nativeLibraryRootRequiresIsa = false;
7778            info.nativeLibraryDir = info.nativeLibraryRootDir;
7779        } else {
7780            // Cluster install
7781            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7782            info.nativeLibraryRootRequiresIsa = true;
7783
7784            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7785                    getPrimaryInstructionSet(info)).getAbsolutePath();
7786
7787            if (info.secondaryCpuAbi != null) {
7788                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7789                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7790            }
7791        }
7792    }
7793
7794    /**
7795     * Calculate the abis and roots for a bundled app. These can uniquely
7796     * be determined from the contents of the system partition, i.e whether
7797     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7798     * of this information, and instead assume that the system was built
7799     * sensibly.
7800     */
7801    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7802                                           PackageSetting pkgSetting) {
7803        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7804
7805        // If "/system/lib64/apkname" exists, assume that is the per-package
7806        // native library directory to use; otherwise use "/system/lib/apkname".
7807        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7808        setBundledAppAbi(pkg, apkRoot, apkName);
7809        // pkgSetting might be null during rescan following uninstall of updates
7810        // to a bundled app, so accommodate that possibility.  The settings in
7811        // that case will be established later from the parsed package.
7812        //
7813        // If the settings aren't null, sync them up with what we've just derived.
7814        // note that apkRoot isn't stored in the package settings.
7815        if (pkgSetting != null) {
7816            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7817            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7818        }
7819    }
7820
7821    /**
7822     * Deduces the ABI of a bundled app and sets the relevant fields on the
7823     * parsed pkg object.
7824     *
7825     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7826     *        under which system libraries are installed.
7827     * @param apkName the name of the installed package.
7828     */
7829    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7830        final File codeFile = new File(pkg.codePath);
7831
7832        final boolean has64BitLibs;
7833        final boolean has32BitLibs;
7834        if (isApkFile(codeFile)) {
7835            // Monolithic install
7836            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7837            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7838        } else {
7839            // Cluster install
7840            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7841            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7842                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7843                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7844                has64BitLibs = (new File(rootDir, isa)).exists();
7845            } else {
7846                has64BitLibs = false;
7847            }
7848            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7849                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7850                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7851                has32BitLibs = (new File(rootDir, isa)).exists();
7852            } else {
7853                has32BitLibs = false;
7854            }
7855        }
7856
7857        if (has64BitLibs && !has32BitLibs) {
7858            // The package has 64 bit libs, but not 32 bit libs. Its primary
7859            // ABI should be 64 bit. We can safely assume here that the bundled
7860            // native libraries correspond to the most preferred ABI in the list.
7861
7862            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7863            pkg.applicationInfo.secondaryCpuAbi = null;
7864        } else if (has32BitLibs && !has64BitLibs) {
7865            // The package has 32 bit libs but not 64 bit libs. Its primary
7866            // ABI should be 32 bit.
7867
7868            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7869            pkg.applicationInfo.secondaryCpuAbi = null;
7870        } else if (has32BitLibs && has64BitLibs) {
7871            // The application has both 64 and 32 bit bundled libraries. We check
7872            // here that the app declares multiArch support, and warn if it doesn't.
7873            //
7874            // We will be lenient here and record both ABIs. The primary will be the
7875            // ABI that's higher on the list, i.e, a device that's configured to prefer
7876            // 64 bit apps will see a 64 bit primary ABI,
7877
7878            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7879                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7880            }
7881
7882            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7883                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7884                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7885            } else {
7886                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7887                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7888            }
7889        } else {
7890            pkg.applicationInfo.primaryCpuAbi = null;
7891            pkg.applicationInfo.secondaryCpuAbi = null;
7892        }
7893    }
7894
7895    private void killApplication(String pkgName, int appId, String reason) {
7896        // Request the ActivityManager to kill the process(only for existing packages)
7897        // so that we do not end up in a confused state while the user is still using the older
7898        // version of the application while the new one gets installed.
7899        IActivityManager am = ActivityManagerNative.getDefault();
7900        if (am != null) {
7901            try {
7902                am.killApplicationWithAppId(pkgName, appId, reason);
7903            } catch (RemoteException e) {
7904            }
7905        }
7906    }
7907
7908    void removePackageLI(PackageSetting ps, boolean chatty) {
7909        if (DEBUG_INSTALL) {
7910            if (chatty)
7911                Log.d(TAG, "Removing package " + ps.name);
7912        }
7913
7914        // writer
7915        synchronized (mPackages) {
7916            mPackages.remove(ps.name);
7917            final PackageParser.Package pkg = ps.pkg;
7918            if (pkg != null) {
7919                cleanPackageDataStructuresLILPw(pkg, chatty);
7920            }
7921        }
7922    }
7923
7924    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7925        if (DEBUG_INSTALL) {
7926            if (chatty)
7927                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7928        }
7929
7930        // writer
7931        synchronized (mPackages) {
7932            mPackages.remove(pkg.applicationInfo.packageName);
7933            cleanPackageDataStructuresLILPw(pkg, chatty);
7934        }
7935    }
7936
7937    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7938        int N = pkg.providers.size();
7939        StringBuilder r = null;
7940        int i;
7941        for (i=0; i<N; i++) {
7942            PackageParser.Provider p = pkg.providers.get(i);
7943            mProviders.removeProvider(p);
7944            if (p.info.authority == null) {
7945
7946                /* There was another ContentProvider with this authority when
7947                 * this app was installed so this authority is null,
7948                 * Ignore it as we don't have to unregister the provider.
7949                 */
7950                continue;
7951            }
7952            String names[] = p.info.authority.split(";");
7953            for (int j = 0; j < names.length; j++) {
7954                if (mProvidersByAuthority.get(names[j]) == p) {
7955                    mProvidersByAuthority.remove(names[j]);
7956                    if (DEBUG_REMOVE) {
7957                        if (chatty)
7958                            Log.d(TAG, "Unregistered content provider: " + names[j]
7959                                    + ", className = " + p.info.name + ", isSyncable = "
7960                                    + p.info.isSyncable);
7961                    }
7962                }
7963            }
7964            if (DEBUG_REMOVE && chatty) {
7965                if (r == null) {
7966                    r = new StringBuilder(256);
7967                } else {
7968                    r.append(' ');
7969                }
7970                r.append(p.info.name);
7971            }
7972        }
7973        if (r != null) {
7974            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7975        }
7976
7977        N = pkg.services.size();
7978        r = null;
7979        for (i=0; i<N; i++) {
7980            PackageParser.Service s = pkg.services.get(i);
7981            mServices.removeService(s);
7982            if (chatty) {
7983                if (r == null) {
7984                    r = new StringBuilder(256);
7985                } else {
7986                    r.append(' ');
7987                }
7988                r.append(s.info.name);
7989            }
7990        }
7991        if (r != null) {
7992            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7993        }
7994
7995        N = pkg.receivers.size();
7996        r = null;
7997        for (i=0; i<N; i++) {
7998            PackageParser.Activity a = pkg.receivers.get(i);
7999            mReceivers.removeActivity(a, "receiver");
8000            if (DEBUG_REMOVE && chatty) {
8001                if (r == null) {
8002                    r = new StringBuilder(256);
8003                } else {
8004                    r.append(' ');
8005                }
8006                r.append(a.info.name);
8007            }
8008        }
8009        if (r != null) {
8010            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8011        }
8012
8013        N = pkg.activities.size();
8014        r = null;
8015        for (i=0; i<N; i++) {
8016            PackageParser.Activity a = pkg.activities.get(i);
8017            mActivities.removeActivity(a, "activity");
8018            if (DEBUG_REMOVE && chatty) {
8019                if (r == null) {
8020                    r = new StringBuilder(256);
8021                } else {
8022                    r.append(' ');
8023                }
8024                r.append(a.info.name);
8025            }
8026        }
8027        if (r != null) {
8028            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8029        }
8030
8031        N = pkg.permissions.size();
8032        r = null;
8033        for (i=0; i<N; i++) {
8034            PackageParser.Permission p = pkg.permissions.get(i);
8035            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8036            if (bp == null) {
8037                bp = mSettings.mPermissionTrees.get(p.info.name);
8038            }
8039            if (bp != null && bp.perm == p) {
8040                bp.perm = null;
8041                if (DEBUG_REMOVE && chatty) {
8042                    if (r == null) {
8043                        r = new StringBuilder(256);
8044                    } else {
8045                        r.append(' ');
8046                    }
8047                    r.append(p.info.name);
8048                }
8049            }
8050            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8051                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8052                if (appOpPerms != null) {
8053                    appOpPerms.remove(pkg.packageName);
8054                }
8055            }
8056        }
8057        if (r != null) {
8058            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8059        }
8060
8061        N = pkg.requestedPermissions.size();
8062        r = null;
8063        for (i=0; i<N; i++) {
8064            String perm = pkg.requestedPermissions.get(i);
8065            BasePermission bp = mSettings.mPermissions.get(perm);
8066            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8067                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8068                if (appOpPerms != null) {
8069                    appOpPerms.remove(pkg.packageName);
8070                    if (appOpPerms.isEmpty()) {
8071                        mAppOpPermissionPackages.remove(perm);
8072                    }
8073                }
8074            }
8075        }
8076        if (r != null) {
8077            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8078        }
8079
8080        N = pkg.instrumentation.size();
8081        r = null;
8082        for (i=0; i<N; i++) {
8083            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8084            mInstrumentation.remove(a.getComponentName());
8085            if (DEBUG_REMOVE && chatty) {
8086                if (r == null) {
8087                    r = new StringBuilder(256);
8088                } else {
8089                    r.append(' ');
8090                }
8091                r.append(a.info.name);
8092            }
8093        }
8094        if (r != null) {
8095            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8096        }
8097
8098        r = null;
8099        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8100            // Only system apps can hold shared libraries.
8101            if (pkg.libraryNames != null) {
8102                for (i=0; i<pkg.libraryNames.size(); i++) {
8103                    String name = pkg.libraryNames.get(i);
8104                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8105                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8106                        mSharedLibraries.remove(name);
8107                        if (DEBUG_REMOVE && chatty) {
8108                            if (r == null) {
8109                                r = new StringBuilder(256);
8110                            } else {
8111                                r.append(' ');
8112                            }
8113                            r.append(name);
8114                        }
8115                    }
8116                }
8117            }
8118        }
8119        if (r != null) {
8120            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8121        }
8122    }
8123
8124    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8125        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8126            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8127                return true;
8128            }
8129        }
8130        return false;
8131    }
8132
8133    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8134    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8135    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8136
8137    private void updatePermissionsLPw(String changingPkg,
8138            PackageParser.Package pkgInfo, int flags) {
8139        // Make sure there are no dangling permission trees.
8140        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8141        while (it.hasNext()) {
8142            final BasePermission bp = it.next();
8143            if (bp.packageSetting == null) {
8144                // We may not yet have parsed the package, so just see if
8145                // we still know about its settings.
8146                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8147            }
8148            if (bp.packageSetting == null) {
8149                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8150                        + " from package " + bp.sourcePackage);
8151                it.remove();
8152            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8153                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8154                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8155                            + " from package " + bp.sourcePackage);
8156                    flags |= UPDATE_PERMISSIONS_ALL;
8157                    it.remove();
8158                }
8159            }
8160        }
8161
8162        // Make sure all dynamic permissions have been assigned to a package,
8163        // and make sure there are no dangling permissions.
8164        it = mSettings.mPermissions.values().iterator();
8165        while (it.hasNext()) {
8166            final BasePermission bp = it.next();
8167            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8168                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8169                        + bp.name + " pkg=" + bp.sourcePackage
8170                        + " info=" + bp.pendingInfo);
8171                if (bp.packageSetting == null && bp.pendingInfo != null) {
8172                    final BasePermission tree = findPermissionTreeLP(bp.name);
8173                    if (tree != null && tree.perm != null) {
8174                        bp.packageSetting = tree.packageSetting;
8175                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8176                                new PermissionInfo(bp.pendingInfo));
8177                        bp.perm.info.packageName = tree.perm.info.packageName;
8178                        bp.perm.info.name = bp.name;
8179                        bp.uid = tree.uid;
8180                    }
8181                }
8182            }
8183            if (bp.packageSetting == null) {
8184                // We may not yet have parsed the package, so just see if
8185                // we still know about its settings.
8186                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8187            }
8188            if (bp.packageSetting == null) {
8189                Slog.w(TAG, "Removing dangling permission: " + bp.name
8190                        + " from package " + bp.sourcePackage);
8191                it.remove();
8192            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8193                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8194                    Slog.i(TAG, "Removing old permission: " + bp.name
8195                            + " from package " + bp.sourcePackage);
8196                    flags |= UPDATE_PERMISSIONS_ALL;
8197                    it.remove();
8198                }
8199            }
8200        }
8201
8202        // Now update the permissions for all packages, in particular
8203        // replace the granted permissions of the system packages.
8204        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8205            for (PackageParser.Package pkg : mPackages.values()) {
8206                if (pkg != pkgInfo) {
8207                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8208                            changingPkg);
8209                }
8210            }
8211        }
8212
8213        if (pkgInfo != null) {
8214            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8215        }
8216    }
8217
8218    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8219            String packageOfInterest) {
8220        // IMPORTANT: There are two types of permissions: install and runtime.
8221        // Install time permissions are granted when the app is installed to
8222        // all device users and users added in the future. Runtime permissions
8223        // are granted at runtime explicitly to specific users. Normal and signature
8224        // protected permissions are install time permissions. Dangerous permissions
8225        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8226        // otherwise they are runtime permissions. This function does not manage
8227        // runtime permissions except for the case an app targeting Lollipop MR1
8228        // being upgraded to target a newer SDK, in which case dangerous permissions
8229        // are transformed from install time to runtime ones.
8230
8231        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8232        if (ps == null) {
8233            return;
8234        }
8235
8236        PermissionsState permissionsState = ps.getPermissionsState();
8237        PermissionsState origPermissions = permissionsState;
8238
8239        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8240
8241        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8242
8243        boolean changedInstallPermission = false;
8244
8245        if (replace) {
8246            ps.installPermissionsFixed = false;
8247            if (!ps.isSharedUser()) {
8248                origPermissions = new PermissionsState(permissionsState);
8249                permissionsState.reset();
8250            }
8251        }
8252
8253        permissionsState.setGlobalGids(mGlobalGids);
8254
8255        final int N = pkg.requestedPermissions.size();
8256        for (int i=0; i<N; i++) {
8257            final String name = pkg.requestedPermissions.get(i);
8258            final BasePermission bp = mSettings.mPermissions.get(name);
8259
8260            if (DEBUG_INSTALL) {
8261                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8262            }
8263
8264            if (bp == null || bp.packageSetting == null) {
8265                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8266                    Slog.w(TAG, "Unknown permission " + name
8267                            + " in package " + pkg.packageName);
8268                }
8269                continue;
8270            }
8271
8272            final String perm = bp.name;
8273            boolean allowedSig = false;
8274            int grant = GRANT_DENIED;
8275
8276            // Keep track of app op permissions.
8277            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8278                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8279                if (pkgs == null) {
8280                    pkgs = new ArraySet<>();
8281                    mAppOpPermissionPackages.put(bp.name, pkgs);
8282                }
8283                pkgs.add(pkg.packageName);
8284            }
8285
8286            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8287            switch (level) {
8288                case PermissionInfo.PROTECTION_NORMAL: {
8289                    // For all apps normal permissions are install time ones.
8290                    grant = GRANT_INSTALL;
8291                } break;
8292
8293                case PermissionInfo.PROTECTION_DANGEROUS: {
8294                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8295                        // For legacy apps dangerous permissions are install time ones.
8296                        grant = GRANT_INSTALL_LEGACY;
8297                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8298                        // For legacy apps that became modern, install becomes runtime.
8299                        grant = GRANT_UPGRADE;
8300                    } else {
8301                        // For modern apps keep runtime permissions unchanged.
8302                        grant = GRANT_RUNTIME;
8303                    }
8304                } break;
8305
8306                case PermissionInfo.PROTECTION_SIGNATURE: {
8307                    // For all apps signature permissions are install time ones.
8308                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8309                    if (allowedSig) {
8310                        grant = GRANT_INSTALL;
8311                    }
8312                } break;
8313            }
8314
8315            if (DEBUG_INSTALL) {
8316                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8317            }
8318
8319            if (grant != GRANT_DENIED) {
8320                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8321                    // If this is an existing, non-system package, then
8322                    // we can't add any new permissions to it.
8323                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8324                        // Except...  if this is a permission that was added
8325                        // to the platform (note: need to only do this when
8326                        // updating the platform).
8327                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8328                            grant = GRANT_DENIED;
8329                        }
8330                    }
8331                }
8332
8333                switch (grant) {
8334                    case GRANT_INSTALL: {
8335                        // Revoke this as runtime permission to handle the case of
8336                        // a runtime permission being downgraded to an install one.
8337                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8338                            if (origPermissions.getRuntimePermissionState(
8339                                    bp.name, userId) != null) {
8340                                // Revoke the runtime permission and clear the flags.
8341                                origPermissions.revokeRuntimePermission(bp, userId);
8342                                origPermissions.updatePermissionFlags(bp, userId,
8343                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8344                                // If we revoked a permission permission, we have to write.
8345                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8346                                        changedRuntimePermissionUserIds, userId);
8347                            }
8348                        }
8349                        // Grant an install permission.
8350                        if (permissionsState.grantInstallPermission(bp) !=
8351                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8352                            changedInstallPermission = true;
8353                        }
8354                    } break;
8355
8356                    case GRANT_INSTALL_LEGACY: {
8357                        // Grant an install permission.
8358                        if (permissionsState.grantInstallPermission(bp) !=
8359                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8360                            changedInstallPermission = true;
8361                        }
8362                    } break;
8363
8364                    case GRANT_RUNTIME: {
8365                        // Grant previously granted runtime permissions.
8366                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8367                            PermissionState permissionState = origPermissions
8368                                    .getRuntimePermissionState(bp.name, userId);
8369                            final int flags = permissionState != null
8370                                    ? permissionState.getFlags() : 0;
8371                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8372                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8373                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8374                                    // If we cannot put the permission as it was, we have to write.
8375                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8376                                            changedRuntimePermissionUserIds, userId);
8377                                }
8378                            }
8379                            // Propagate the permission flags.
8380                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8381                        }
8382                    } break;
8383
8384                    case GRANT_UPGRADE: {
8385                        // Grant runtime permissions for a previously held install permission.
8386                        PermissionState permissionState = origPermissions
8387                                .getInstallPermissionState(bp.name);
8388                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8389
8390                        if (origPermissions.revokeInstallPermission(bp)
8391                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8392                            // We will be transferring the permission flags, so clear them.
8393                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8394                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8395                            changedInstallPermission = true;
8396                        }
8397
8398                        // If the permission is not to be promoted to runtime we ignore it and
8399                        // also its other flags as they are not applicable to install permissions.
8400                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8401                            for (int userId : currentUserIds) {
8402                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8403                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8404                                    // Transfer the permission flags.
8405                                    permissionsState.updatePermissionFlags(bp, userId,
8406                                            flags, flags);
8407                                    // If we granted the permission, we have to write.
8408                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8409                                            changedRuntimePermissionUserIds, userId);
8410                                }
8411                            }
8412                        }
8413                    } break;
8414
8415                    default: {
8416                        if (packageOfInterest == null
8417                                || packageOfInterest.equals(pkg.packageName)) {
8418                            Slog.w(TAG, "Not granting permission " + perm
8419                                    + " to package " + pkg.packageName
8420                                    + " because it was previously installed without");
8421                        }
8422                    } break;
8423                }
8424            } else {
8425                if (permissionsState.revokeInstallPermission(bp) !=
8426                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8427                    // Also drop the permission flags.
8428                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8429                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8430                    changedInstallPermission = true;
8431                    Slog.i(TAG, "Un-granting permission " + perm
8432                            + " from package " + pkg.packageName
8433                            + " (protectionLevel=" + bp.protectionLevel
8434                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8435                            + ")");
8436                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8437                    // Don't print warning for app op permissions, since it is fine for them
8438                    // not to be granted, there is a UI for the user to decide.
8439                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8440                        Slog.w(TAG, "Not granting permission " + perm
8441                                + " to package " + pkg.packageName
8442                                + " (protectionLevel=" + bp.protectionLevel
8443                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8444                                + ")");
8445                    }
8446                }
8447            }
8448        }
8449
8450        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8451                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8452            // This is the first that we have heard about this package, so the
8453            // permissions we have now selected are fixed until explicitly
8454            // changed.
8455            ps.installPermissionsFixed = true;
8456        }
8457
8458        // Persist the runtime permissions state for users with changes.
8459        for (int userId : changedRuntimePermissionUserIds) {
8460            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8461        }
8462    }
8463
8464    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8465        boolean allowed = false;
8466        final int NP = PackageParser.NEW_PERMISSIONS.length;
8467        for (int ip=0; ip<NP; ip++) {
8468            final PackageParser.NewPermissionInfo npi
8469                    = PackageParser.NEW_PERMISSIONS[ip];
8470            if (npi.name.equals(perm)
8471                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8472                allowed = true;
8473                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8474                        + pkg.packageName);
8475                break;
8476            }
8477        }
8478        return allowed;
8479    }
8480
8481    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8482            BasePermission bp, PermissionsState origPermissions) {
8483        boolean allowed;
8484        allowed = (compareSignatures(
8485                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8486                        == PackageManager.SIGNATURE_MATCH)
8487                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8488                        == PackageManager.SIGNATURE_MATCH);
8489        if (!allowed && (bp.protectionLevel
8490                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8491            if (isSystemApp(pkg)) {
8492                // For updated system applications, a system permission
8493                // is granted only if it had been defined by the original application.
8494                if (pkg.isUpdatedSystemApp()) {
8495                    final PackageSetting sysPs = mSettings
8496                            .getDisabledSystemPkgLPr(pkg.packageName);
8497                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8498                        // If the original was granted this permission, we take
8499                        // that grant decision as read and propagate it to the
8500                        // update.
8501                        if (sysPs.isPrivileged()) {
8502                            allowed = true;
8503                        }
8504                    } else {
8505                        // The system apk may have been updated with an older
8506                        // version of the one on the data partition, but which
8507                        // granted a new system permission that it didn't have
8508                        // before.  In this case we do want to allow the app to
8509                        // now get the new permission if the ancestral apk is
8510                        // privileged to get it.
8511                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8512                            for (int j=0;
8513                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8514                                if (perm.equals(
8515                                        sysPs.pkg.requestedPermissions.get(j))) {
8516                                    allowed = true;
8517                                    break;
8518                                }
8519                            }
8520                        }
8521                    }
8522                } else {
8523                    allowed = isPrivilegedApp(pkg);
8524                }
8525            }
8526        }
8527        if (!allowed) {
8528            if (!allowed && (bp.protectionLevel
8529                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8530                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8531                // If this was a previously normal/dangerous permission that got moved
8532                // to a system permission as part of the runtime permission redesign, then
8533                // we still want to blindly grant it to old apps.
8534                allowed = true;
8535            }
8536            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8537                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8538                // If this permission is to be granted to the system installer and
8539                // this app is an installer, then it gets the permission.
8540                allowed = true;
8541            }
8542            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8543                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8544                // If this permission is to be granted to the system verifier and
8545                // this app is a verifier, then it gets the permission.
8546                allowed = true;
8547            }
8548            if (!allowed && (bp.protectionLevel
8549                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8550                    && isSystemApp(pkg)) {
8551                // Any pre-installed system app is allowed to get this permission.
8552                allowed = true;
8553            }
8554            if (!allowed && (bp.protectionLevel
8555                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8556                // For development permissions, a development permission
8557                // is granted only if it was already granted.
8558                allowed = origPermissions.hasInstallPermission(perm);
8559            }
8560        }
8561        return allowed;
8562    }
8563
8564    final class ActivityIntentResolver
8565            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8566        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8567                boolean defaultOnly, int userId) {
8568            if (!sUserManager.exists(userId)) return null;
8569            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8570            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8571        }
8572
8573        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8574                int userId) {
8575            if (!sUserManager.exists(userId)) return null;
8576            mFlags = flags;
8577            return super.queryIntent(intent, resolvedType,
8578                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8579        }
8580
8581        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8582                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8583            if (!sUserManager.exists(userId)) return null;
8584            if (packageActivities == null) {
8585                return null;
8586            }
8587            mFlags = flags;
8588            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8589            final int N = packageActivities.size();
8590            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8591                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8592
8593            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8594            for (int i = 0; i < N; ++i) {
8595                intentFilters = packageActivities.get(i).intents;
8596                if (intentFilters != null && intentFilters.size() > 0) {
8597                    PackageParser.ActivityIntentInfo[] array =
8598                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8599                    intentFilters.toArray(array);
8600                    listCut.add(array);
8601                }
8602            }
8603            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8604        }
8605
8606        public final void addActivity(PackageParser.Activity a, String type) {
8607            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8608            mActivities.put(a.getComponentName(), a);
8609            if (DEBUG_SHOW_INFO)
8610                Log.v(
8611                TAG, "  " + type + " " +
8612                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8613            if (DEBUG_SHOW_INFO)
8614                Log.v(TAG, "    Class=" + a.info.name);
8615            final int NI = a.intents.size();
8616            for (int j=0; j<NI; j++) {
8617                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8618                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8619                    intent.setPriority(0);
8620                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8621                            + a.className + " with priority > 0, forcing to 0");
8622                }
8623                if (DEBUG_SHOW_INFO) {
8624                    Log.v(TAG, "    IntentFilter:");
8625                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8626                }
8627                if (!intent.debugCheck()) {
8628                    Log.w(TAG, "==> For Activity " + a.info.name);
8629                }
8630                addFilter(intent);
8631            }
8632        }
8633
8634        public final void removeActivity(PackageParser.Activity a, String type) {
8635            mActivities.remove(a.getComponentName());
8636            if (DEBUG_SHOW_INFO) {
8637                Log.v(TAG, "  " + type + " "
8638                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8639                                : a.info.name) + ":");
8640                Log.v(TAG, "    Class=" + a.info.name);
8641            }
8642            final int NI = a.intents.size();
8643            for (int j=0; j<NI; j++) {
8644                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8645                if (DEBUG_SHOW_INFO) {
8646                    Log.v(TAG, "    IntentFilter:");
8647                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8648                }
8649                removeFilter(intent);
8650            }
8651        }
8652
8653        @Override
8654        protected boolean allowFilterResult(
8655                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8656            ActivityInfo filterAi = filter.activity.info;
8657            for (int i=dest.size()-1; i>=0; i--) {
8658                ActivityInfo destAi = dest.get(i).activityInfo;
8659                if (destAi.name == filterAi.name
8660                        && destAi.packageName == filterAi.packageName) {
8661                    return false;
8662                }
8663            }
8664            return true;
8665        }
8666
8667        @Override
8668        protected ActivityIntentInfo[] newArray(int size) {
8669            return new ActivityIntentInfo[size];
8670        }
8671
8672        @Override
8673        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8674            if (!sUserManager.exists(userId)) return true;
8675            PackageParser.Package p = filter.activity.owner;
8676            if (p != null) {
8677                PackageSetting ps = (PackageSetting)p.mExtras;
8678                if (ps != null) {
8679                    // System apps are never considered stopped for purposes of
8680                    // filtering, because there may be no way for the user to
8681                    // actually re-launch them.
8682                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8683                            && ps.getStopped(userId);
8684                }
8685            }
8686            return false;
8687        }
8688
8689        @Override
8690        protected boolean isPackageForFilter(String packageName,
8691                PackageParser.ActivityIntentInfo info) {
8692            return packageName.equals(info.activity.owner.packageName);
8693        }
8694
8695        @Override
8696        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8697                int match, int userId) {
8698            if (!sUserManager.exists(userId)) return null;
8699            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8700                return null;
8701            }
8702            final PackageParser.Activity activity = info.activity;
8703            if (mSafeMode && (activity.info.applicationInfo.flags
8704                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8705                return null;
8706            }
8707            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8708            if (ps == null) {
8709                return null;
8710            }
8711            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8712                    ps.readUserState(userId), userId);
8713            if (ai == null) {
8714                return null;
8715            }
8716            final ResolveInfo res = new ResolveInfo();
8717            res.activityInfo = ai;
8718            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8719                res.filter = info;
8720            }
8721            if (info != null) {
8722                res.handleAllWebDataURI = info.handleAllWebDataURI();
8723            }
8724            res.priority = info.getPriority();
8725            res.preferredOrder = activity.owner.mPreferredOrder;
8726            //System.out.println("Result: " + res.activityInfo.className +
8727            //                   " = " + res.priority);
8728            res.match = match;
8729            res.isDefault = info.hasDefault;
8730            res.labelRes = info.labelRes;
8731            res.nonLocalizedLabel = info.nonLocalizedLabel;
8732            if (userNeedsBadging(userId)) {
8733                res.noResourceId = true;
8734            } else {
8735                res.icon = info.icon;
8736            }
8737            res.iconResourceId = info.icon;
8738            res.system = res.activityInfo.applicationInfo.isSystemApp();
8739            return res;
8740        }
8741
8742        @Override
8743        protected void sortResults(List<ResolveInfo> results) {
8744            Collections.sort(results, mResolvePrioritySorter);
8745        }
8746
8747        @Override
8748        protected void dumpFilter(PrintWriter out, String prefix,
8749                PackageParser.ActivityIntentInfo filter) {
8750            out.print(prefix); out.print(
8751                    Integer.toHexString(System.identityHashCode(filter.activity)));
8752                    out.print(' ');
8753                    filter.activity.printComponentShortName(out);
8754                    out.print(" filter ");
8755                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8756        }
8757
8758        @Override
8759        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8760            return filter.activity;
8761        }
8762
8763        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8764            PackageParser.Activity activity = (PackageParser.Activity)label;
8765            out.print(prefix); out.print(
8766                    Integer.toHexString(System.identityHashCode(activity)));
8767                    out.print(' ');
8768                    activity.printComponentShortName(out);
8769            if (count > 1) {
8770                out.print(" ("); out.print(count); out.print(" filters)");
8771            }
8772            out.println();
8773        }
8774
8775//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8776//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8777//            final List<ResolveInfo> retList = Lists.newArrayList();
8778//            while (i.hasNext()) {
8779//                final ResolveInfo resolveInfo = i.next();
8780//                if (isEnabledLP(resolveInfo.activityInfo)) {
8781//                    retList.add(resolveInfo);
8782//                }
8783//            }
8784//            return retList;
8785//        }
8786
8787        // Keys are String (activity class name), values are Activity.
8788        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8789                = new ArrayMap<ComponentName, PackageParser.Activity>();
8790        private int mFlags;
8791    }
8792
8793    private final class ServiceIntentResolver
8794            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8795        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8796                boolean defaultOnly, int userId) {
8797            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8798            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8799        }
8800
8801        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8802                int userId) {
8803            if (!sUserManager.exists(userId)) return null;
8804            mFlags = flags;
8805            return super.queryIntent(intent, resolvedType,
8806                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8807        }
8808
8809        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8810                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8811            if (!sUserManager.exists(userId)) return null;
8812            if (packageServices == null) {
8813                return null;
8814            }
8815            mFlags = flags;
8816            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8817            final int N = packageServices.size();
8818            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8819                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8820
8821            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8822            for (int i = 0; i < N; ++i) {
8823                intentFilters = packageServices.get(i).intents;
8824                if (intentFilters != null && intentFilters.size() > 0) {
8825                    PackageParser.ServiceIntentInfo[] array =
8826                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8827                    intentFilters.toArray(array);
8828                    listCut.add(array);
8829                }
8830            }
8831            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8832        }
8833
8834        public final void addService(PackageParser.Service s) {
8835            mServices.put(s.getComponentName(), s);
8836            if (DEBUG_SHOW_INFO) {
8837                Log.v(TAG, "  "
8838                        + (s.info.nonLocalizedLabel != null
8839                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8840                Log.v(TAG, "    Class=" + s.info.name);
8841            }
8842            final int NI = s.intents.size();
8843            int j;
8844            for (j=0; j<NI; j++) {
8845                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8846                if (DEBUG_SHOW_INFO) {
8847                    Log.v(TAG, "    IntentFilter:");
8848                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8849                }
8850                if (!intent.debugCheck()) {
8851                    Log.w(TAG, "==> For Service " + s.info.name);
8852                }
8853                addFilter(intent);
8854            }
8855        }
8856
8857        public final void removeService(PackageParser.Service s) {
8858            mServices.remove(s.getComponentName());
8859            if (DEBUG_SHOW_INFO) {
8860                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8861                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8862                Log.v(TAG, "    Class=" + s.info.name);
8863            }
8864            final int NI = s.intents.size();
8865            int j;
8866            for (j=0; j<NI; j++) {
8867                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8868                if (DEBUG_SHOW_INFO) {
8869                    Log.v(TAG, "    IntentFilter:");
8870                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8871                }
8872                removeFilter(intent);
8873            }
8874        }
8875
8876        @Override
8877        protected boolean allowFilterResult(
8878                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8879            ServiceInfo filterSi = filter.service.info;
8880            for (int i=dest.size()-1; i>=0; i--) {
8881                ServiceInfo destAi = dest.get(i).serviceInfo;
8882                if (destAi.name == filterSi.name
8883                        && destAi.packageName == filterSi.packageName) {
8884                    return false;
8885                }
8886            }
8887            return true;
8888        }
8889
8890        @Override
8891        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8892            return new PackageParser.ServiceIntentInfo[size];
8893        }
8894
8895        @Override
8896        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8897            if (!sUserManager.exists(userId)) return true;
8898            PackageParser.Package p = filter.service.owner;
8899            if (p != null) {
8900                PackageSetting ps = (PackageSetting)p.mExtras;
8901                if (ps != null) {
8902                    // System apps are never considered stopped for purposes of
8903                    // filtering, because there may be no way for the user to
8904                    // actually re-launch them.
8905                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8906                            && ps.getStopped(userId);
8907                }
8908            }
8909            return false;
8910        }
8911
8912        @Override
8913        protected boolean isPackageForFilter(String packageName,
8914                PackageParser.ServiceIntentInfo info) {
8915            return packageName.equals(info.service.owner.packageName);
8916        }
8917
8918        @Override
8919        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8920                int match, int userId) {
8921            if (!sUserManager.exists(userId)) return null;
8922            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8923            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8924                return null;
8925            }
8926            final PackageParser.Service service = info.service;
8927            if (mSafeMode && (service.info.applicationInfo.flags
8928                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8929                return null;
8930            }
8931            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8932            if (ps == null) {
8933                return null;
8934            }
8935            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8936                    ps.readUserState(userId), userId);
8937            if (si == null) {
8938                return null;
8939            }
8940            final ResolveInfo res = new ResolveInfo();
8941            res.serviceInfo = si;
8942            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8943                res.filter = filter;
8944            }
8945            res.priority = info.getPriority();
8946            res.preferredOrder = service.owner.mPreferredOrder;
8947            res.match = match;
8948            res.isDefault = info.hasDefault;
8949            res.labelRes = info.labelRes;
8950            res.nonLocalizedLabel = info.nonLocalizedLabel;
8951            res.icon = info.icon;
8952            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8953            return res;
8954        }
8955
8956        @Override
8957        protected void sortResults(List<ResolveInfo> results) {
8958            Collections.sort(results, mResolvePrioritySorter);
8959        }
8960
8961        @Override
8962        protected void dumpFilter(PrintWriter out, String prefix,
8963                PackageParser.ServiceIntentInfo filter) {
8964            out.print(prefix); out.print(
8965                    Integer.toHexString(System.identityHashCode(filter.service)));
8966                    out.print(' ');
8967                    filter.service.printComponentShortName(out);
8968                    out.print(" filter ");
8969                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8970        }
8971
8972        @Override
8973        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8974            return filter.service;
8975        }
8976
8977        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8978            PackageParser.Service service = (PackageParser.Service)label;
8979            out.print(prefix); out.print(
8980                    Integer.toHexString(System.identityHashCode(service)));
8981                    out.print(' ');
8982                    service.printComponentShortName(out);
8983            if (count > 1) {
8984                out.print(" ("); out.print(count); out.print(" filters)");
8985            }
8986            out.println();
8987        }
8988
8989//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8990//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8991//            final List<ResolveInfo> retList = Lists.newArrayList();
8992//            while (i.hasNext()) {
8993//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8994//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8995//                    retList.add(resolveInfo);
8996//                }
8997//            }
8998//            return retList;
8999//        }
9000
9001        // Keys are String (activity class name), values are Activity.
9002        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9003                = new ArrayMap<ComponentName, PackageParser.Service>();
9004        private int mFlags;
9005    };
9006
9007    private final class ProviderIntentResolver
9008            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9009        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9010                boolean defaultOnly, int userId) {
9011            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9012            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9013        }
9014
9015        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9016                int userId) {
9017            if (!sUserManager.exists(userId))
9018                return null;
9019            mFlags = flags;
9020            return super.queryIntent(intent, resolvedType,
9021                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9022        }
9023
9024        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9025                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9026            if (!sUserManager.exists(userId))
9027                return null;
9028            if (packageProviders == null) {
9029                return null;
9030            }
9031            mFlags = flags;
9032            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9033            final int N = packageProviders.size();
9034            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9035                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9036
9037            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9038            for (int i = 0; i < N; ++i) {
9039                intentFilters = packageProviders.get(i).intents;
9040                if (intentFilters != null && intentFilters.size() > 0) {
9041                    PackageParser.ProviderIntentInfo[] array =
9042                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9043                    intentFilters.toArray(array);
9044                    listCut.add(array);
9045                }
9046            }
9047            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9048        }
9049
9050        public final void addProvider(PackageParser.Provider p) {
9051            if (mProviders.containsKey(p.getComponentName())) {
9052                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9053                return;
9054            }
9055
9056            mProviders.put(p.getComponentName(), p);
9057            if (DEBUG_SHOW_INFO) {
9058                Log.v(TAG, "  "
9059                        + (p.info.nonLocalizedLabel != null
9060                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9061                Log.v(TAG, "    Class=" + p.info.name);
9062            }
9063            final int NI = p.intents.size();
9064            int j;
9065            for (j = 0; j < NI; j++) {
9066                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9067                if (DEBUG_SHOW_INFO) {
9068                    Log.v(TAG, "    IntentFilter:");
9069                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9070                }
9071                if (!intent.debugCheck()) {
9072                    Log.w(TAG, "==> For Provider " + p.info.name);
9073                }
9074                addFilter(intent);
9075            }
9076        }
9077
9078        public final void removeProvider(PackageParser.Provider p) {
9079            mProviders.remove(p.getComponentName());
9080            if (DEBUG_SHOW_INFO) {
9081                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9082                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9083                Log.v(TAG, "    Class=" + p.info.name);
9084            }
9085            final int NI = p.intents.size();
9086            int j;
9087            for (j = 0; j < NI; j++) {
9088                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9089                if (DEBUG_SHOW_INFO) {
9090                    Log.v(TAG, "    IntentFilter:");
9091                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9092                }
9093                removeFilter(intent);
9094            }
9095        }
9096
9097        @Override
9098        protected boolean allowFilterResult(
9099                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9100            ProviderInfo filterPi = filter.provider.info;
9101            for (int i = dest.size() - 1; i >= 0; i--) {
9102                ProviderInfo destPi = dest.get(i).providerInfo;
9103                if (destPi.name == filterPi.name
9104                        && destPi.packageName == filterPi.packageName) {
9105                    return false;
9106                }
9107            }
9108            return true;
9109        }
9110
9111        @Override
9112        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9113            return new PackageParser.ProviderIntentInfo[size];
9114        }
9115
9116        @Override
9117        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9118            if (!sUserManager.exists(userId))
9119                return true;
9120            PackageParser.Package p = filter.provider.owner;
9121            if (p != null) {
9122                PackageSetting ps = (PackageSetting) p.mExtras;
9123                if (ps != null) {
9124                    // System apps are never considered stopped for purposes of
9125                    // filtering, because there may be no way for the user to
9126                    // actually re-launch them.
9127                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9128                            && ps.getStopped(userId);
9129                }
9130            }
9131            return false;
9132        }
9133
9134        @Override
9135        protected boolean isPackageForFilter(String packageName,
9136                PackageParser.ProviderIntentInfo info) {
9137            return packageName.equals(info.provider.owner.packageName);
9138        }
9139
9140        @Override
9141        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9142                int match, int userId) {
9143            if (!sUserManager.exists(userId))
9144                return null;
9145            final PackageParser.ProviderIntentInfo info = filter;
9146            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9147                return null;
9148            }
9149            final PackageParser.Provider provider = info.provider;
9150            if (mSafeMode && (provider.info.applicationInfo.flags
9151                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9152                return null;
9153            }
9154            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9155            if (ps == null) {
9156                return null;
9157            }
9158            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9159                    ps.readUserState(userId), userId);
9160            if (pi == null) {
9161                return null;
9162            }
9163            final ResolveInfo res = new ResolveInfo();
9164            res.providerInfo = pi;
9165            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9166                res.filter = filter;
9167            }
9168            res.priority = info.getPriority();
9169            res.preferredOrder = provider.owner.mPreferredOrder;
9170            res.match = match;
9171            res.isDefault = info.hasDefault;
9172            res.labelRes = info.labelRes;
9173            res.nonLocalizedLabel = info.nonLocalizedLabel;
9174            res.icon = info.icon;
9175            res.system = res.providerInfo.applicationInfo.isSystemApp();
9176            return res;
9177        }
9178
9179        @Override
9180        protected void sortResults(List<ResolveInfo> results) {
9181            Collections.sort(results, mResolvePrioritySorter);
9182        }
9183
9184        @Override
9185        protected void dumpFilter(PrintWriter out, String prefix,
9186                PackageParser.ProviderIntentInfo filter) {
9187            out.print(prefix);
9188            out.print(
9189                    Integer.toHexString(System.identityHashCode(filter.provider)));
9190            out.print(' ');
9191            filter.provider.printComponentShortName(out);
9192            out.print(" filter ");
9193            out.println(Integer.toHexString(System.identityHashCode(filter)));
9194        }
9195
9196        @Override
9197        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9198            return filter.provider;
9199        }
9200
9201        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9202            PackageParser.Provider provider = (PackageParser.Provider)label;
9203            out.print(prefix); out.print(
9204                    Integer.toHexString(System.identityHashCode(provider)));
9205                    out.print(' ');
9206                    provider.printComponentShortName(out);
9207            if (count > 1) {
9208                out.print(" ("); out.print(count); out.print(" filters)");
9209            }
9210            out.println();
9211        }
9212
9213        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9214                = new ArrayMap<ComponentName, PackageParser.Provider>();
9215        private int mFlags;
9216    };
9217
9218    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9219            new Comparator<ResolveInfo>() {
9220        public int compare(ResolveInfo r1, ResolveInfo r2) {
9221            int v1 = r1.priority;
9222            int v2 = r2.priority;
9223            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9224            if (v1 != v2) {
9225                return (v1 > v2) ? -1 : 1;
9226            }
9227            v1 = r1.preferredOrder;
9228            v2 = r2.preferredOrder;
9229            if (v1 != v2) {
9230                return (v1 > v2) ? -1 : 1;
9231            }
9232            if (r1.isDefault != r2.isDefault) {
9233                return r1.isDefault ? -1 : 1;
9234            }
9235            v1 = r1.match;
9236            v2 = r2.match;
9237            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9238            if (v1 != v2) {
9239                return (v1 > v2) ? -1 : 1;
9240            }
9241            if (r1.system != r2.system) {
9242                return r1.system ? -1 : 1;
9243            }
9244            return 0;
9245        }
9246    };
9247
9248    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9249            new Comparator<ProviderInfo>() {
9250        public int compare(ProviderInfo p1, ProviderInfo p2) {
9251            final int v1 = p1.initOrder;
9252            final int v2 = p2.initOrder;
9253            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9254        }
9255    };
9256
9257    final void sendPackageBroadcast(final String action, final String pkg,
9258            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9259            final int[] userIds) {
9260        mHandler.post(new Runnable() {
9261            @Override
9262            public void run() {
9263                try {
9264                    final IActivityManager am = ActivityManagerNative.getDefault();
9265                    if (am == null) return;
9266                    final int[] resolvedUserIds;
9267                    if (userIds == null) {
9268                        resolvedUserIds = am.getRunningUserIds();
9269                    } else {
9270                        resolvedUserIds = userIds;
9271                    }
9272                    for (int id : resolvedUserIds) {
9273                        final Intent intent = new Intent(action,
9274                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9275                        if (extras != null) {
9276                            intent.putExtras(extras);
9277                        }
9278                        if (targetPkg != null) {
9279                            intent.setPackage(targetPkg);
9280                        }
9281                        // Modify the UID when posting to other users
9282                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9283                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9284                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9285                            intent.putExtra(Intent.EXTRA_UID, uid);
9286                        }
9287                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9288                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9289                        if (DEBUG_BROADCASTS) {
9290                            RuntimeException here = new RuntimeException("here");
9291                            here.fillInStackTrace();
9292                            Slog.d(TAG, "Sending to user " + id + ": "
9293                                    + intent.toShortString(false, true, false, false)
9294                                    + " " + intent.getExtras(), here);
9295                        }
9296                        am.broadcastIntent(null, intent, null, finishedReceiver,
9297                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9298                                null, finishedReceiver != null, false, id);
9299                    }
9300                } catch (RemoteException ex) {
9301                }
9302            }
9303        });
9304    }
9305
9306    /**
9307     * Check if the external storage media is available. This is true if there
9308     * is a mounted external storage medium or if the external storage is
9309     * emulated.
9310     */
9311    private boolean isExternalMediaAvailable() {
9312        return mMediaMounted || Environment.isExternalStorageEmulated();
9313    }
9314
9315    @Override
9316    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9317        // writer
9318        synchronized (mPackages) {
9319            if (!isExternalMediaAvailable()) {
9320                // If the external storage is no longer mounted at this point,
9321                // the caller may not have been able to delete all of this
9322                // packages files and can not delete any more.  Bail.
9323                return null;
9324            }
9325            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9326            if (lastPackage != null) {
9327                pkgs.remove(lastPackage);
9328            }
9329            if (pkgs.size() > 0) {
9330                return pkgs.get(0);
9331            }
9332        }
9333        return null;
9334    }
9335
9336    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9337        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9338                userId, andCode ? 1 : 0, packageName);
9339        if (mSystemReady) {
9340            msg.sendToTarget();
9341        } else {
9342            if (mPostSystemReadyMessages == null) {
9343                mPostSystemReadyMessages = new ArrayList<>();
9344            }
9345            mPostSystemReadyMessages.add(msg);
9346        }
9347    }
9348
9349    void startCleaningPackages() {
9350        // reader
9351        synchronized (mPackages) {
9352            if (!isExternalMediaAvailable()) {
9353                return;
9354            }
9355            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9356                return;
9357            }
9358        }
9359        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9360        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9361        IActivityManager am = ActivityManagerNative.getDefault();
9362        if (am != null) {
9363            try {
9364                am.startService(null, intent, null, mContext.getOpPackageName(),
9365                        UserHandle.USER_OWNER);
9366            } catch (RemoteException e) {
9367            }
9368        }
9369    }
9370
9371    @Override
9372    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9373            int installFlags, String installerPackageName, VerificationParams verificationParams,
9374            String packageAbiOverride) {
9375        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9376                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9377    }
9378
9379    @Override
9380    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9381            int installFlags, String installerPackageName, VerificationParams verificationParams,
9382            String packageAbiOverride, int userId) {
9383        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9384
9385        final int callingUid = Binder.getCallingUid();
9386        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9387
9388        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9389            try {
9390                if (observer != null) {
9391                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9392                }
9393            } catch (RemoteException re) {
9394            }
9395            return;
9396        }
9397
9398        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9399            installFlags |= PackageManager.INSTALL_FROM_ADB;
9400
9401        } else {
9402            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9403            // about installerPackageName.
9404
9405            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9406            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9407        }
9408
9409        UserHandle user;
9410        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9411            user = UserHandle.ALL;
9412        } else {
9413            user = new UserHandle(userId);
9414        }
9415
9416        // Only system components can circumvent runtime permissions when installing.
9417        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9418                && mContext.checkCallingOrSelfPermission(Manifest.permission
9419                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9420            throw new SecurityException("You need the "
9421                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9422                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9423        }
9424
9425        verificationParams.setInstallerUid(callingUid);
9426
9427        final File originFile = new File(originPath);
9428        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9429
9430        final Message msg = mHandler.obtainMessage(INIT_COPY);
9431        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9432                null, verificationParams, user, packageAbiOverride);
9433        mHandler.sendMessage(msg);
9434    }
9435
9436    void installStage(String packageName, File stagedDir, String stagedCid,
9437            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9438            String installerPackageName, int installerUid, UserHandle user) {
9439        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9440                params.referrerUri, installerUid, null);
9441        verifParams.setInstallerUid(installerUid);
9442
9443        final OriginInfo origin;
9444        if (stagedDir != null) {
9445            origin = OriginInfo.fromStagedFile(stagedDir);
9446        } else {
9447            origin = OriginInfo.fromStagedContainer(stagedCid);
9448        }
9449
9450        final Message msg = mHandler.obtainMessage(INIT_COPY);
9451        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9452                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9453        mHandler.sendMessage(msg);
9454    }
9455
9456    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9457        Bundle extras = new Bundle(1);
9458        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9459
9460        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9461                packageName, extras, null, null, new int[] {userId});
9462        try {
9463            IActivityManager am = ActivityManagerNative.getDefault();
9464            final boolean isSystem =
9465                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9466            if (isSystem && am.isUserRunning(userId, false)) {
9467                // The just-installed/enabled app is bundled on the system, so presumed
9468                // to be able to run automatically without needing an explicit launch.
9469                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9470                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9471                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9472                        .setPackage(packageName);
9473                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9474                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9475            }
9476        } catch (RemoteException e) {
9477            // shouldn't happen
9478            Slog.w(TAG, "Unable to bootstrap installed package", e);
9479        }
9480    }
9481
9482    @Override
9483    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9484            int userId) {
9485        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9486        PackageSetting pkgSetting;
9487        final int uid = Binder.getCallingUid();
9488        enforceCrossUserPermission(uid, userId, true, true,
9489                "setApplicationHiddenSetting for user " + userId);
9490
9491        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9492            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9493            return false;
9494        }
9495
9496        long callingId = Binder.clearCallingIdentity();
9497        try {
9498            boolean sendAdded = false;
9499            boolean sendRemoved = false;
9500            // writer
9501            synchronized (mPackages) {
9502                pkgSetting = mSettings.mPackages.get(packageName);
9503                if (pkgSetting == null) {
9504                    return false;
9505                }
9506                if (pkgSetting.getHidden(userId) != hidden) {
9507                    pkgSetting.setHidden(hidden, userId);
9508                    mSettings.writePackageRestrictionsLPr(userId);
9509                    if (hidden) {
9510                        sendRemoved = true;
9511                    } else {
9512                        sendAdded = true;
9513                    }
9514                }
9515            }
9516            if (sendAdded) {
9517                sendPackageAddedForUser(packageName, pkgSetting, userId);
9518                return true;
9519            }
9520            if (sendRemoved) {
9521                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9522                        "hiding pkg");
9523                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9524            }
9525        } finally {
9526            Binder.restoreCallingIdentity(callingId);
9527        }
9528        return false;
9529    }
9530
9531    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9532            int userId) {
9533        final PackageRemovedInfo info = new PackageRemovedInfo();
9534        info.removedPackage = packageName;
9535        info.removedUsers = new int[] {userId};
9536        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9537        info.sendBroadcast(false, false, false);
9538    }
9539
9540    /**
9541     * Returns true if application is not found or there was an error. Otherwise it returns
9542     * the hidden state of the package for the given user.
9543     */
9544    @Override
9545    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9546        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9547        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9548                false, "getApplicationHidden for user " + userId);
9549        PackageSetting pkgSetting;
9550        long callingId = Binder.clearCallingIdentity();
9551        try {
9552            // writer
9553            synchronized (mPackages) {
9554                pkgSetting = mSettings.mPackages.get(packageName);
9555                if (pkgSetting == null) {
9556                    return true;
9557                }
9558                return pkgSetting.getHidden(userId);
9559            }
9560        } finally {
9561            Binder.restoreCallingIdentity(callingId);
9562        }
9563    }
9564
9565    /**
9566     * @hide
9567     */
9568    @Override
9569    public int installExistingPackageAsUser(String packageName, int userId) {
9570        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9571                null);
9572        PackageSetting pkgSetting;
9573        final int uid = Binder.getCallingUid();
9574        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9575                + userId);
9576        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9577            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9578        }
9579
9580        long callingId = Binder.clearCallingIdentity();
9581        try {
9582            boolean sendAdded = false;
9583
9584            // writer
9585            synchronized (mPackages) {
9586                pkgSetting = mSettings.mPackages.get(packageName);
9587                if (pkgSetting == null) {
9588                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9589                }
9590                if (!pkgSetting.getInstalled(userId)) {
9591                    pkgSetting.setInstalled(true, userId);
9592                    pkgSetting.setHidden(false, userId);
9593                    mSettings.writePackageRestrictionsLPr(userId);
9594                    sendAdded = true;
9595                }
9596            }
9597
9598            if (sendAdded) {
9599                sendPackageAddedForUser(packageName, pkgSetting, userId);
9600            }
9601        } finally {
9602            Binder.restoreCallingIdentity(callingId);
9603        }
9604
9605        return PackageManager.INSTALL_SUCCEEDED;
9606    }
9607
9608    boolean isUserRestricted(int userId, String restrictionKey) {
9609        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9610        if (restrictions.getBoolean(restrictionKey, false)) {
9611            Log.w(TAG, "User is restricted: " + restrictionKey);
9612            return true;
9613        }
9614        return false;
9615    }
9616
9617    @Override
9618    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9619        mContext.enforceCallingOrSelfPermission(
9620                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9621                "Only package verification agents can verify applications");
9622
9623        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9624        final PackageVerificationResponse response = new PackageVerificationResponse(
9625                verificationCode, Binder.getCallingUid());
9626        msg.arg1 = id;
9627        msg.obj = response;
9628        mHandler.sendMessage(msg);
9629    }
9630
9631    @Override
9632    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9633            long millisecondsToDelay) {
9634        mContext.enforceCallingOrSelfPermission(
9635                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9636                "Only package verification agents can extend verification timeouts");
9637
9638        final PackageVerificationState state = mPendingVerification.get(id);
9639        final PackageVerificationResponse response = new PackageVerificationResponse(
9640                verificationCodeAtTimeout, Binder.getCallingUid());
9641
9642        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9643            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9644        }
9645        if (millisecondsToDelay < 0) {
9646            millisecondsToDelay = 0;
9647        }
9648        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9649                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9650            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9651        }
9652
9653        if ((state != null) && !state.timeoutExtended()) {
9654            state.extendTimeout();
9655
9656            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9657            msg.arg1 = id;
9658            msg.obj = response;
9659            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9660        }
9661    }
9662
9663    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9664            int verificationCode, UserHandle user) {
9665        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9666        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9667        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9668        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9669        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9670
9671        mContext.sendBroadcastAsUser(intent, user,
9672                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9673    }
9674
9675    private ComponentName matchComponentForVerifier(String packageName,
9676            List<ResolveInfo> receivers) {
9677        ActivityInfo targetReceiver = null;
9678
9679        final int NR = receivers.size();
9680        for (int i = 0; i < NR; i++) {
9681            final ResolveInfo info = receivers.get(i);
9682            if (info.activityInfo == null) {
9683                continue;
9684            }
9685
9686            if (packageName.equals(info.activityInfo.packageName)) {
9687                targetReceiver = info.activityInfo;
9688                break;
9689            }
9690        }
9691
9692        if (targetReceiver == null) {
9693            return null;
9694        }
9695
9696        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9697    }
9698
9699    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9700            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9701        if (pkgInfo.verifiers.length == 0) {
9702            return null;
9703        }
9704
9705        final int N = pkgInfo.verifiers.length;
9706        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9707        for (int i = 0; i < N; i++) {
9708            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9709
9710            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9711                    receivers);
9712            if (comp == null) {
9713                continue;
9714            }
9715
9716            final int verifierUid = getUidForVerifier(verifierInfo);
9717            if (verifierUid == -1) {
9718                continue;
9719            }
9720
9721            if (DEBUG_VERIFY) {
9722                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9723                        + " with the correct signature");
9724            }
9725            sufficientVerifiers.add(comp);
9726            verificationState.addSufficientVerifier(verifierUid);
9727        }
9728
9729        return sufficientVerifiers;
9730    }
9731
9732    private int getUidForVerifier(VerifierInfo verifierInfo) {
9733        synchronized (mPackages) {
9734            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9735            if (pkg == null) {
9736                return -1;
9737            } else if (pkg.mSignatures.length != 1) {
9738                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9739                        + " has more than one signature; ignoring");
9740                return -1;
9741            }
9742
9743            /*
9744             * If the public key of the package's signature does not match
9745             * our expected public key, then this is a different package and
9746             * we should skip.
9747             */
9748
9749            final byte[] expectedPublicKey;
9750            try {
9751                final Signature verifierSig = pkg.mSignatures[0];
9752                final PublicKey publicKey = verifierSig.getPublicKey();
9753                expectedPublicKey = publicKey.getEncoded();
9754            } catch (CertificateException e) {
9755                return -1;
9756            }
9757
9758            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9759
9760            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9761                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9762                        + " does not have the expected public key; ignoring");
9763                return -1;
9764            }
9765
9766            return pkg.applicationInfo.uid;
9767        }
9768    }
9769
9770    @Override
9771    public void finishPackageInstall(int token) {
9772        enforceSystemOrRoot("Only the system is allowed to finish installs");
9773
9774        if (DEBUG_INSTALL) {
9775            Slog.v(TAG, "BM finishing package install for " + token);
9776        }
9777
9778        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9779        mHandler.sendMessage(msg);
9780    }
9781
9782    /**
9783     * Get the verification agent timeout.
9784     *
9785     * @return verification timeout in milliseconds
9786     */
9787    private long getVerificationTimeout() {
9788        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9789                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9790                DEFAULT_VERIFICATION_TIMEOUT);
9791    }
9792
9793    /**
9794     * Get the default verification agent response code.
9795     *
9796     * @return default verification response code
9797     */
9798    private int getDefaultVerificationResponse() {
9799        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9800                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9801                DEFAULT_VERIFICATION_RESPONSE);
9802    }
9803
9804    /**
9805     * Check whether or not package verification has been enabled.
9806     *
9807     * @return true if verification should be performed
9808     */
9809    private boolean isVerificationEnabled(int userId, int installFlags) {
9810        if (!DEFAULT_VERIFY_ENABLE) {
9811            return false;
9812        }
9813
9814        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9815
9816        // Check if installing from ADB
9817        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9818            // Do not run verification in a test harness environment
9819            if (ActivityManager.isRunningInTestHarness()) {
9820                return false;
9821            }
9822            if (ensureVerifyAppsEnabled) {
9823                return true;
9824            }
9825            // Check if the developer does not want package verification for ADB installs
9826            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9827                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9828                return false;
9829            }
9830        }
9831
9832        if (ensureVerifyAppsEnabled) {
9833            return true;
9834        }
9835
9836        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9837                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9838    }
9839
9840    @Override
9841    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9842            throws RemoteException {
9843        mContext.enforceCallingOrSelfPermission(
9844                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9845                "Only intentfilter verification agents can verify applications");
9846
9847        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9848        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9849                Binder.getCallingUid(), verificationCode, failedDomains);
9850        msg.arg1 = id;
9851        msg.obj = response;
9852        mHandler.sendMessage(msg);
9853    }
9854
9855    @Override
9856    public int getIntentVerificationStatus(String packageName, int userId) {
9857        synchronized (mPackages) {
9858            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9859        }
9860    }
9861
9862    @Override
9863    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9864        mContext.enforceCallingOrSelfPermission(
9865                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9866
9867        boolean result = false;
9868        synchronized (mPackages) {
9869            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9870        }
9871        if (result) {
9872            scheduleWritePackageRestrictionsLocked(userId);
9873        }
9874        return result;
9875    }
9876
9877    @Override
9878    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9879        synchronized (mPackages) {
9880            return mSettings.getIntentFilterVerificationsLPr(packageName);
9881        }
9882    }
9883
9884    @Override
9885    public List<IntentFilter> getAllIntentFilters(String packageName) {
9886        if (TextUtils.isEmpty(packageName)) {
9887            return Collections.<IntentFilter>emptyList();
9888        }
9889        synchronized (mPackages) {
9890            PackageParser.Package pkg = mPackages.get(packageName);
9891            if (pkg == null || pkg.activities == null) {
9892                return Collections.<IntentFilter>emptyList();
9893            }
9894            final int count = pkg.activities.size();
9895            ArrayList<IntentFilter> result = new ArrayList<>();
9896            for (int n=0; n<count; n++) {
9897                PackageParser.Activity activity = pkg.activities.get(n);
9898                if (activity.intents != null || activity.intents.size() > 0) {
9899                    result.addAll(activity.intents);
9900                }
9901            }
9902            return result;
9903        }
9904    }
9905
9906    @Override
9907    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9908        mContext.enforceCallingOrSelfPermission(
9909                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9910
9911        synchronized (mPackages) {
9912            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9913            if (packageName != null) {
9914                result |= updateIntentVerificationStatus(packageName,
9915                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9916                        UserHandle.myUserId());
9917                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9918                        packageName, userId);
9919            }
9920            return result;
9921        }
9922    }
9923
9924    @Override
9925    public String getDefaultBrowserPackageName(int userId) {
9926        synchronized (mPackages) {
9927            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9928        }
9929    }
9930
9931    /**
9932     * Get the "allow unknown sources" setting.
9933     *
9934     * @return the current "allow unknown sources" setting
9935     */
9936    private int getUnknownSourcesSettings() {
9937        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9938                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9939                -1);
9940    }
9941
9942    @Override
9943    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9944        final int uid = Binder.getCallingUid();
9945        // writer
9946        synchronized (mPackages) {
9947            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9948            if (targetPackageSetting == null) {
9949                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9950            }
9951
9952            PackageSetting installerPackageSetting;
9953            if (installerPackageName != null) {
9954                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9955                if (installerPackageSetting == null) {
9956                    throw new IllegalArgumentException("Unknown installer package: "
9957                            + installerPackageName);
9958                }
9959            } else {
9960                installerPackageSetting = null;
9961            }
9962
9963            Signature[] callerSignature;
9964            Object obj = mSettings.getUserIdLPr(uid);
9965            if (obj != null) {
9966                if (obj instanceof SharedUserSetting) {
9967                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9968                } else if (obj instanceof PackageSetting) {
9969                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9970                } else {
9971                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9972                }
9973            } else {
9974                throw new SecurityException("Unknown calling uid " + uid);
9975            }
9976
9977            // Verify: can't set installerPackageName to a package that is
9978            // not signed with the same cert as the caller.
9979            if (installerPackageSetting != null) {
9980                if (compareSignatures(callerSignature,
9981                        installerPackageSetting.signatures.mSignatures)
9982                        != PackageManager.SIGNATURE_MATCH) {
9983                    throw new SecurityException(
9984                            "Caller does not have same cert as new installer package "
9985                            + installerPackageName);
9986                }
9987            }
9988
9989            // Verify: if target already has an installer package, it must
9990            // be signed with the same cert as the caller.
9991            if (targetPackageSetting.installerPackageName != null) {
9992                PackageSetting setting = mSettings.mPackages.get(
9993                        targetPackageSetting.installerPackageName);
9994                // If the currently set package isn't valid, then it's always
9995                // okay to change it.
9996                if (setting != null) {
9997                    if (compareSignatures(callerSignature,
9998                            setting.signatures.mSignatures)
9999                            != PackageManager.SIGNATURE_MATCH) {
10000                        throw new SecurityException(
10001                                "Caller does not have same cert as old installer package "
10002                                + targetPackageSetting.installerPackageName);
10003                    }
10004                }
10005            }
10006
10007            // Okay!
10008            targetPackageSetting.installerPackageName = installerPackageName;
10009            scheduleWriteSettingsLocked();
10010        }
10011    }
10012
10013    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10014        // Queue up an async operation since the package installation may take a little while.
10015        mHandler.post(new Runnable() {
10016            public void run() {
10017                mHandler.removeCallbacks(this);
10018                 // Result object to be returned
10019                PackageInstalledInfo res = new PackageInstalledInfo();
10020                res.returnCode = currentStatus;
10021                res.uid = -1;
10022                res.pkg = null;
10023                res.removedInfo = new PackageRemovedInfo();
10024                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10025                    args.doPreInstall(res.returnCode);
10026                    synchronized (mInstallLock) {
10027                        installPackageLI(args, res);
10028                    }
10029                    args.doPostInstall(res.returnCode, res.uid);
10030                }
10031
10032                // A restore should be performed at this point if (a) the install
10033                // succeeded, (b) the operation is not an update, and (c) the new
10034                // package has not opted out of backup participation.
10035                final boolean update = res.removedInfo.removedPackage != null;
10036                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10037                boolean doRestore = !update
10038                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10039
10040                // Set up the post-install work request bookkeeping.  This will be used
10041                // and cleaned up by the post-install event handling regardless of whether
10042                // there's a restore pass performed.  Token values are >= 1.
10043                int token;
10044                if (mNextInstallToken < 0) mNextInstallToken = 1;
10045                token = mNextInstallToken++;
10046
10047                PostInstallData data = new PostInstallData(args, res);
10048                mRunningInstalls.put(token, data);
10049                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10050
10051                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10052                    // Pass responsibility to the Backup Manager.  It will perform a
10053                    // restore if appropriate, then pass responsibility back to the
10054                    // Package Manager to run the post-install observer callbacks
10055                    // and broadcasts.
10056                    IBackupManager bm = IBackupManager.Stub.asInterface(
10057                            ServiceManager.getService(Context.BACKUP_SERVICE));
10058                    if (bm != null) {
10059                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10060                                + " to BM for possible restore");
10061                        try {
10062                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10063                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10064                            } else {
10065                                doRestore = false;
10066                            }
10067                        } catch (RemoteException e) {
10068                            // can't happen; the backup manager is local
10069                        } catch (Exception e) {
10070                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10071                            doRestore = false;
10072                        }
10073                    } else {
10074                        Slog.e(TAG, "Backup Manager not found!");
10075                        doRestore = false;
10076                    }
10077                }
10078
10079                if (!doRestore) {
10080                    // No restore possible, or the Backup Manager was mysteriously not
10081                    // available -- just fire the post-install work request directly.
10082                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10083                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10084                    mHandler.sendMessage(msg);
10085                }
10086            }
10087        });
10088    }
10089
10090    private abstract class HandlerParams {
10091        private static final int MAX_RETRIES = 4;
10092
10093        /**
10094         * Number of times startCopy() has been attempted and had a non-fatal
10095         * error.
10096         */
10097        private int mRetries = 0;
10098
10099        /** User handle for the user requesting the information or installation. */
10100        private final UserHandle mUser;
10101
10102        HandlerParams(UserHandle user) {
10103            mUser = user;
10104        }
10105
10106        UserHandle getUser() {
10107            return mUser;
10108        }
10109
10110        final boolean startCopy() {
10111            boolean res;
10112            try {
10113                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10114
10115                if (++mRetries > MAX_RETRIES) {
10116                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10117                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10118                    handleServiceError();
10119                    return false;
10120                } else {
10121                    handleStartCopy();
10122                    res = true;
10123                }
10124            } catch (RemoteException e) {
10125                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10126                mHandler.sendEmptyMessage(MCS_RECONNECT);
10127                res = false;
10128            }
10129            handleReturnCode();
10130            return res;
10131        }
10132
10133        final void serviceError() {
10134            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10135            handleServiceError();
10136            handleReturnCode();
10137        }
10138
10139        abstract void handleStartCopy() throws RemoteException;
10140        abstract void handleServiceError();
10141        abstract void handleReturnCode();
10142    }
10143
10144    class MeasureParams extends HandlerParams {
10145        private final PackageStats mStats;
10146        private boolean mSuccess;
10147
10148        private final IPackageStatsObserver mObserver;
10149
10150        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10151            super(new UserHandle(stats.userHandle));
10152            mObserver = observer;
10153            mStats = stats;
10154        }
10155
10156        @Override
10157        public String toString() {
10158            return "MeasureParams{"
10159                + Integer.toHexString(System.identityHashCode(this))
10160                + " " + mStats.packageName + "}";
10161        }
10162
10163        @Override
10164        void handleStartCopy() throws RemoteException {
10165            synchronized (mInstallLock) {
10166                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10167            }
10168
10169            if (mSuccess) {
10170                final boolean mounted;
10171                if (Environment.isExternalStorageEmulated()) {
10172                    mounted = true;
10173                } else {
10174                    final String status = Environment.getExternalStorageState();
10175                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10176                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10177                }
10178
10179                if (mounted) {
10180                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10181
10182                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10183                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10184
10185                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10186                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10187
10188                    // Always subtract cache size, since it's a subdirectory
10189                    mStats.externalDataSize -= mStats.externalCacheSize;
10190
10191                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10192                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10193
10194                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10195                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10196                }
10197            }
10198        }
10199
10200        @Override
10201        void handleReturnCode() {
10202            if (mObserver != null) {
10203                try {
10204                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10205                } catch (RemoteException e) {
10206                    Slog.i(TAG, "Observer no longer exists.");
10207                }
10208            }
10209        }
10210
10211        @Override
10212        void handleServiceError() {
10213            Slog.e(TAG, "Could not measure application " + mStats.packageName
10214                            + " external storage");
10215        }
10216    }
10217
10218    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10219            throws RemoteException {
10220        long result = 0;
10221        for (File path : paths) {
10222            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10223        }
10224        return result;
10225    }
10226
10227    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10228        for (File path : paths) {
10229            try {
10230                mcs.clearDirectory(path.getAbsolutePath());
10231            } catch (RemoteException e) {
10232            }
10233        }
10234    }
10235
10236    static class OriginInfo {
10237        /**
10238         * Location where install is coming from, before it has been
10239         * copied/renamed into place. This could be a single monolithic APK
10240         * file, or a cluster directory. This location may be untrusted.
10241         */
10242        final File file;
10243        final String cid;
10244
10245        /**
10246         * Flag indicating that {@link #file} or {@link #cid} has already been
10247         * staged, meaning downstream users don't need to defensively copy the
10248         * contents.
10249         */
10250        final boolean staged;
10251
10252        /**
10253         * Flag indicating that {@link #file} or {@link #cid} is an already
10254         * installed app that is being moved.
10255         */
10256        final boolean existing;
10257
10258        final String resolvedPath;
10259        final File resolvedFile;
10260
10261        static OriginInfo fromNothing() {
10262            return new OriginInfo(null, null, false, false);
10263        }
10264
10265        static OriginInfo fromUntrustedFile(File file) {
10266            return new OriginInfo(file, null, false, false);
10267        }
10268
10269        static OriginInfo fromExistingFile(File file) {
10270            return new OriginInfo(file, null, false, true);
10271        }
10272
10273        static OriginInfo fromStagedFile(File file) {
10274            return new OriginInfo(file, null, true, false);
10275        }
10276
10277        static OriginInfo fromStagedContainer(String cid) {
10278            return new OriginInfo(null, cid, true, false);
10279        }
10280
10281        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10282            this.file = file;
10283            this.cid = cid;
10284            this.staged = staged;
10285            this.existing = existing;
10286
10287            if (cid != null) {
10288                resolvedPath = PackageHelper.getSdDir(cid);
10289                resolvedFile = new File(resolvedPath);
10290            } else if (file != null) {
10291                resolvedPath = file.getAbsolutePath();
10292                resolvedFile = file;
10293            } else {
10294                resolvedPath = null;
10295                resolvedFile = null;
10296            }
10297        }
10298    }
10299
10300    class MoveInfo {
10301        final int moveId;
10302        final String fromUuid;
10303        final String toUuid;
10304        final String packageName;
10305        final String dataAppName;
10306        final int appId;
10307        final String seinfo;
10308
10309        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10310                String dataAppName, int appId, String seinfo) {
10311            this.moveId = moveId;
10312            this.fromUuid = fromUuid;
10313            this.toUuid = toUuid;
10314            this.packageName = packageName;
10315            this.dataAppName = dataAppName;
10316            this.appId = appId;
10317            this.seinfo = seinfo;
10318        }
10319    }
10320
10321    class InstallParams extends HandlerParams {
10322        final OriginInfo origin;
10323        final MoveInfo move;
10324        final IPackageInstallObserver2 observer;
10325        int installFlags;
10326        final String installerPackageName;
10327        final String volumeUuid;
10328        final VerificationParams verificationParams;
10329        private InstallArgs mArgs;
10330        private int mRet;
10331        final String packageAbiOverride;
10332
10333        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10334                int installFlags, String installerPackageName, String volumeUuid,
10335                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10336            super(user);
10337            this.origin = origin;
10338            this.move = move;
10339            this.observer = observer;
10340            this.installFlags = installFlags;
10341            this.installerPackageName = installerPackageName;
10342            this.volumeUuid = volumeUuid;
10343            this.verificationParams = verificationParams;
10344            this.packageAbiOverride = packageAbiOverride;
10345        }
10346
10347        @Override
10348        public String toString() {
10349            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10350                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10351        }
10352
10353        public ManifestDigest getManifestDigest() {
10354            if (verificationParams == null) {
10355                return null;
10356            }
10357            return verificationParams.getManifestDigest();
10358        }
10359
10360        private int installLocationPolicy(PackageInfoLite pkgLite) {
10361            String packageName = pkgLite.packageName;
10362            int installLocation = pkgLite.installLocation;
10363            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10364            // reader
10365            synchronized (mPackages) {
10366                PackageParser.Package pkg = mPackages.get(packageName);
10367                if (pkg != null) {
10368                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10369                        // Check for downgrading.
10370                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10371                            try {
10372                                checkDowngrade(pkg, pkgLite);
10373                            } catch (PackageManagerException e) {
10374                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10375                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10376                            }
10377                        }
10378                        // Check for updated system application.
10379                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10380                            if (onSd) {
10381                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10382                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10383                            }
10384                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10385                        } else {
10386                            if (onSd) {
10387                                // Install flag overrides everything.
10388                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10389                            }
10390                            // If current upgrade specifies particular preference
10391                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10392                                // Application explicitly specified internal.
10393                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10394                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10395                                // App explictly prefers external. Let policy decide
10396                            } else {
10397                                // Prefer previous location
10398                                if (isExternal(pkg)) {
10399                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10400                                }
10401                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10402                            }
10403                        }
10404                    } else {
10405                        // Invalid install. Return error code
10406                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10407                    }
10408                }
10409            }
10410            // All the special cases have been taken care of.
10411            // Return result based on recommended install location.
10412            if (onSd) {
10413                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10414            }
10415            return pkgLite.recommendedInstallLocation;
10416        }
10417
10418        /*
10419         * Invoke remote method to get package information and install
10420         * location values. Override install location based on default
10421         * policy if needed and then create install arguments based
10422         * on the install location.
10423         */
10424        public void handleStartCopy() throws RemoteException {
10425            int ret = PackageManager.INSTALL_SUCCEEDED;
10426
10427            // If we're already staged, we've firmly committed to an install location
10428            if (origin.staged) {
10429                if (origin.file != null) {
10430                    installFlags |= PackageManager.INSTALL_INTERNAL;
10431                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10432                } else if (origin.cid != null) {
10433                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10434                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10435                } else {
10436                    throw new IllegalStateException("Invalid stage location");
10437                }
10438            }
10439
10440            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10441            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10442
10443            PackageInfoLite pkgLite = null;
10444
10445            if (onInt && onSd) {
10446                // Check if both bits are set.
10447                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10448                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10449            } else {
10450                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10451                        packageAbiOverride);
10452
10453                /*
10454                 * If we have too little free space, try to free cache
10455                 * before giving up.
10456                 */
10457                if (!origin.staged && pkgLite.recommendedInstallLocation
10458                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10459                    // TODO: focus freeing disk space on the target device
10460                    final StorageManager storage = StorageManager.from(mContext);
10461                    final long lowThreshold = storage.getStorageLowBytes(
10462                            Environment.getDataDirectory());
10463
10464                    final long sizeBytes = mContainerService.calculateInstalledSize(
10465                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10466
10467                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10468                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10469                                installFlags, packageAbiOverride);
10470                    }
10471
10472                    /*
10473                     * The cache free must have deleted the file we
10474                     * downloaded to install.
10475                     *
10476                     * TODO: fix the "freeCache" call to not delete
10477                     *       the file we care about.
10478                     */
10479                    if (pkgLite.recommendedInstallLocation
10480                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10481                        pkgLite.recommendedInstallLocation
10482                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10483                    }
10484                }
10485            }
10486
10487            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10488                int loc = pkgLite.recommendedInstallLocation;
10489                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10490                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10491                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10492                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10493                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10494                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10495                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10496                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10497                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10498                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10499                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10500                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10501                } else {
10502                    // Override with defaults if needed.
10503                    loc = installLocationPolicy(pkgLite);
10504                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10505                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10506                    } else if (!onSd && !onInt) {
10507                        // Override install location with flags
10508                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10509                            // Set the flag to install on external media.
10510                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10511                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10512                        } else {
10513                            // Make sure the flag for installing on external
10514                            // media is unset
10515                            installFlags |= PackageManager.INSTALL_INTERNAL;
10516                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10517                        }
10518                    }
10519                }
10520            }
10521
10522            final InstallArgs args = createInstallArgs(this);
10523            mArgs = args;
10524
10525            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10526                 /*
10527                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10528                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10529                 */
10530                int userIdentifier = getUser().getIdentifier();
10531                if (userIdentifier == UserHandle.USER_ALL
10532                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10533                    userIdentifier = UserHandle.USER_OWNER;
10534                }
10535
10536                /*
10537                 * Determine if we have any installed package verifiers. If we
10538                 * do, then we'll defer to them to verify the packages.
10539                 */
10540                final int requiredUid = mRequiredVerifierPackage == null ? -1
10541                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10542                if (!origin.existing && requiredUid != -1
10543                        && isVerificationEnabled(userIdentifier, installFlags)) {
10544                    final Intent verification = new Intent(
10545                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10546                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10547                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10548                            PACKAGE_MIME_TYPE);
10549                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10550
10551                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10552                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10553                            0 /* TODO: Which userId? */);
10554
10555                    if (DEBUG_VERIFY) {
10556                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10557                                + verification.toString() + " with " + pkgLite.verifiers.length
10558                                + " optional verifiers");
10559                    }
10560
10561                    final int verificationId = mPendingVerificationToken++;
10562
10563                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10564
10565                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10566                            installerPackageName);
10567
10568                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10569                            installFlags);
10570
10571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10572                            pkgLite.packageName);
10573
10574                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10575                            pkgLite.versionCode);
10576
10577                    if (verificationParams != null) {
10578                        if (verificationParams.getVerificationURI() != null) {
10579                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10580                                 verificationParams.getVerificationURI());
10581                        }
10582                        if (verificationParams.getOriginatingURI() != null) {
10583                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10584                                  verificationParams.getOriginatingURI());
10585                        }
10586                        if (verificationParams.getReferrer() != null) {
10587                            verification.putExtra(Intent.EXTRA_REFERRER,
10588                                  verificationParams.getReferrer());
10589                        }
10590                        if (verificationParams.getOriginatingUid() >= 0) {
10591                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10592                                  verificationParams.getOriginatingUid());
10593                        }
10594                        if (verificationParams.getInstallerUid() >= 0) {
10595                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10596                                  verificationParams.getInstallerUid());
10597                        }
10598                    }
10599
10600                    final PackageVerificationState verificationState = new PackageVerificationState(
10601                            requiredUid, args);
10602
10603                    mPendingVerification.append(verificationId, verificationState);
10604
10605                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10606                            receivers, verificationState);
10607
10608                    /*
10609                     * If any sufficient verifiers were listed in the package
10610                     * manifest, attempt to ask them.
10611                     */
10612                    if (sufficientVerifiers != null) {
10613                        final int N = sufficientVerifiers.size();
10614                        if (N == 0) {
10615                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10616                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10617                        } else {
10618                            for (int i = 0; i < N; i++) {
10619                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10620
10621                                final Intent sufficientIntent = new Intent(verification);
10622                                sufficientIntent.setComponent(verifierComponent);
10623
10624                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10625                            }
10626                        }
10627                    }
10628
10629                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10630                            mRequiredVerifierPackage, receivers);
10631                    if (ret == PackageManager.INSTALL_SUCCEEDED
10632                            && mRequiredVerifierPackage != null) {
10633                        /*
10634                         * Send the intent to the required verification agent,
10635                         * but only start the verification timeout after the
10636                         * target BroadcastReceivers have run.
10637                         */
10638                        verification.setComponent(requiredVerifierComponent);
10639                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10640                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10641                                new BroadcastReceiver() {
10642                                    @Override
10643                                    public void onReceive(Context context, Intent intent) {
10644                                        final Message msg = mHandler
10645                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10646                                        msg.arg1 = verificationId;
10647                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10648                                    }
10649                                }, null, 0, null, null);
10650
10651                        /*
10652                         * We don't want the copy to proceed until verification
10653                         * succeeds, so null out this field.
10654                         */
10655                        mArgs = null;
10656                    }
10657                } else {
10658                    /*
10659                     * No package verification is enabled, so immediately start
10660                     * the remote call to initiate copy using temporary file.
10661                     */
10662                    ret = args.copyApk(mContainerService, true);
10663                }
10664            }
10665
10666            mRet = ret;
10667        }
10668
10669        @Override
10670        void handleReturnCode() {
10671            // If mArgs is null, then MCS couldn't be reached. When it
10672            // reconnects, it will try again to install. At that point, this
10673            // will succeed.
10674            if (mArgs != null) {
10675                processPendingInstall(mArgs, mRet);
10676            }
10677        }
10678
10679        @Override
10680        void handleServiceError() {
10681            mArgs = createInstallArgs(this);
10682            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10683        }
10684
10685        public boolean isForwardLocked() {
10686            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10687        }
10688    }
10689
10690    /**
10691     * Used during creation of InstallArgs
10692     *
10693     * @param installFlags package installation flags
10694     * @return true if should be installed on external storage
10695     */
10696    private static boolean installOnExternalAsec(int installFlags) {
10697        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10698            return false;
10699        }
10700        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10701            return true;
10702        }
10703        return false;
10704    }
10705
10706    /**
10707     * Used during creation of InstallArgs
10708     *
10709     * @param installFlags package installation flags
10710     * @return true if should be installed as forward locked
10711     */
10712    private static boolean installForwardLocked(int installFlags) {
10713        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10714    }
10715
10716    private InstallArgs createInstallArgs(InstallParams params) {
10717        if (params.move != null) {
10718            return new MoveInstallArgs(params);
10719        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10720            return new AsecInstallArgs(params);
10721        } else {
10722            return new FileInstallArgs(params);
10723        }
10724    }
10725
10726    /**
10727     * Create args that describe an existing installed package. Typically used
10728     * when cleaning up old installs, or used as a move source.
10729     */
10730    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10731            String resourcePath, String[] instructionSets) {
10732        final boolean isInAsec;
10733        if (installOnExternalAsec(installFlags)) {
10734            /* Apps on SD card are always in ASEC containers. */
10735            isInAsec = true;
10736        } else if (installForwardLocked(installFlags)
10737                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10738            /*
10739             * Forward-locked apps are only in ASEC containers if they're the
10740             * new style
10741             */
10742            isInAsec = true;
10743        } else {
10744            isInAsec = false;
10745        }
10746
10747        if (isInAsec) {
10748            return new AsecInstallArgs(codePath, instructionSets,
10749                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10750        } else {
10751            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10752        }
10753    }
10754
10755    static abstract class InstallArgs {
10756        /** @see InstallParams#origin */
10757        final OriginInfo origin;
10758        /** @see InstallParams#move */
10759        final MoveInfo move;
10760
10761        final IPackageInstallObserver2 observer;
10762        // Always refers to PackageManager flags only
10763        final int installFlags;
10764        final String installerPackageName;
10765        final String volumeUuid;
10766        final ManifestDigest manifestDigest;
10767        final UserHandle user;
10768        final String abiOverride;
10769
10770        // The list of instruction sets supported by this app. This is currently
10771        // only used during the rmdex() phase to clean up resources. We can get rid of this
10772        // if we move dex files under the common app path.
10773        /* nullable */ String[] instructionSets;
10774
10775        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10776                int installFlags, String installerPackageName, String volumeUuid,
10777                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10778                String abiOverride) {
10779            this.origin = origin;
10780            this.move = move;
10781            this.installFlags = installFlags;
10782            this.observer = observer;
10783            this.installerPackageName = installerPackageName;
10784            this.volumeUuid = volumeUuid;
10785            this.manifestDigest = manifestDigest;
10786            this.user = user;
10787            this.instructionSets = instructionSets;
10788            this.abiOverride = abiOverride;
10789        }
10790
10791        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10792        abstract int doPreInstall(int status);
10793
10794        /**
10795         * Rename package into final resting place. All paths on the given
10796         * scanned package should be updated to reflect the rename.
10797         */
10798        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10799        abstract int doPostInstall(int status, int uid);
10800
10801        /** @see PackageSettingBase#codePathString */
10802        abstract String getCodePath();
10803        /** @see PackageSettingBase#resourcePathString */
10804        abstract String getResourcePath();
10805
10806        // Need installer lock especially for dex file removal.
10807        abstract void cleanUpResourcesLI();
10808        abstract boolean doPostDeleteLI(boolean delete);
10809
10810        /**
10811         * Called before the source arguments are copied. This is used mostly
10812         * for MoveParams when it needs to read the source file to put it in the
10813         * destination.
10814         */
10815        int doPreCopy() {
10816            return PackageManager.INSTALL_SUCCEEDED;
10817        }
10818
10819        /**
10820         * Called after the source arguments are copied. This is used mostly for
10821         * MoveParams when it needs to read the source file to put it in the
10822         * destination.
10823         *
10824         * @return
10825         */
10826        int doPostCopy(int uid) {
10827            return PackageManager.INSTALL_SUCCEEDED;
10828        }
10829
10830        protected boolean isFwdLocked() {
10831            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10832        }
10833
10834        protected boolean isExternalAsec() {
10835            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10836        }
10837
10838        UserHandle getUser() {
10839            return user;
10840        }
10841    }
10842
10843    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10844        if (!allCodePaths.isEmpty()) {
10845            if (instructionSets == null) {
10846                throw new IllegalStateException("instructionSet == null");
10847            }
10848            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10849            for (String codePath : allCodePaths) {
10850                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10851                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10852                    if (retCode < 0) {
10853                        Slog.w(TAG, "Couldn't remove dex file for package: "
10854                                + " at location " + codePath + ", retcode=" + retCode);
10855                        // we don't consider this to be a failure of the core package deletion
10856                    }
10857                }
10858            }
10859        }
10860    }
10861
10862    /**
10863     * Logic to handle installation of non-ASEC applications, including copying
10864     * and renaming logic.
10865     */
10866    class FileInstallArgs extends InstallArgs {
10867        private File codeFile;
10868        private File resourceFile;
10869
10870        // Example topology:
10871        // /data/app/com.example/base.apk
10872        // /data/app/com.example/split_foo.apk
10873        // /data/app/com.example/lib/arm/libfoo.so
10874        // /data/app/com.example/lib/arm64/libfoo.so
10875        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10876
10877        /** New install */
10878        FileInstallArgs(InstallParams params) {
10879            super(params.origin, params.move, params.observer, params.installFlags,
10880                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10881                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10882            if (isFwdLocked()) {
10883                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10884            }
10885        }
10886
10887        /** Existing install */
10888        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10889            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10890                    null);
10891            this.codeFile = (codePath != null) ? new File(codePath) : null;
10892            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10893        }
10894
10895        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10896            if (origin.staged) {
10897                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10898                codeFile = origin.file;
10899                resourceFile = origin.file;
10900                return PackageManager.INSTALL_SUCCEEDED;
10901            }
10902
10903            try {
10904                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10905                codeFile = tempDir;
10906                resourceFile = tempDir;
10907            } catch (IOException e) {
10908                Slog.w(TAG, "Failed to create copy file: " + e);
10909                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10910            }
10911
10912            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10913                @Override
10914                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10915                    if (!FileUtils.isValidExtFilename(name)) {
10916                        throw new IllegalArgumentException("Invalid filename: " + name);
10917                    }
10918                    try {
10919                        final File file = new File(codeFile, name);
10920                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10921                                O_RDWR | O_CREAT, 0644);
10922                        Os.chmod(file.getAbsolutePath(), 0644);
10923                        return new ParcelFileDescriptor(fd);
10924                    } catch (ErrnoException e) {
10925                        throw new RemoteException("Failed to open: " + e.getMessage());
10926                    }
10927                }
10928            };
10929
10930            int ret = PackageManager.INSTALL_SUCCEEDED;
10931            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10932            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10933                Slog.e(TAG, "Failed to copy package");
10934                return ret;
10935            }
10936
10937            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10938            NativeLibraryHelper.Handle handle = null;
10939            try {
10940                handle = NativeLibraryHelper.Handle.create(codeFile);
10941                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10942                        abiOverride);
10943            } catch (IOException e) {
10944                Slog.e(TAG, "Copying native libraries failed", e);
10945                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10946            } finally {
10947                IoUtils.closeQuietly(handle);
10948            }
10949
10950            return ret;
10951        }
10952
10953        int doPreInstall(int status) {
10954            if (status != PackageManager.INSTALL_SUCCEEDED) {
10955                cleanUp();
10956            }
10957            return status;
10958        }
10959
10960        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10961            if (status != PackageManager.INSTALL_SUCCEEDED) {
10962                cleanUp();
10963                return false;
10964            }
10965
10966            final File targetDir = codeFile.getParentFile();
10967            final File beforeCodeFile = codeFile;
10968            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10969
10970            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10971            try {
10972                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10973            } catch (ErrnoException e) {
10974                Slog.w(TAG, "Failed to rename", e);
10975                return false;
10976            }
10977
10978            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10979                Slog.w(TAG, "Failed to restorecon");
10980                return false;
10981            }
10982
10983            // Reflect the rename internally
10984            codeFile = afterCodeFile;
10985            resourceFile = afterCodeFile;
10986
10987            // Reflect the rename in scanned details
10988            pkg.codePath = afterCodeFile.getAbsolutePath();
10989            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10990                    pkg.baseCodePath);
10991            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10992                    pkg.splitCodePaths);
10993
10994            // Reflect the rename in app info
10995            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10996            pkg.applicationInfo.setCodePath(pkg.codePath);
10997            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10998            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10999            pkg.applicationInfo.setResourcePath(pkg.codePath);
11000            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11001            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11002
11003            return true;
11004        }
11005
11006        int doPostInstall(int status, int uid) {
11007            if (status != PackageManager.INSTALL_SUCCEEDED) {
11008                cleanUp();
11009            }
11010            return status;
11011        }
11012
11013        @Override
11014        String getCodePath() {
11015            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11016        }
11017
11018        @Override
11019        String getResourcePath() {
11020            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11021        }
11022
11023        private boolean cleanUp() {
11024            if (codeFile == null || !codeFile.exists()) {
11025                return false;
11026            }
11027
11028            if (codeFile.isDirectory()) {
11029                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11030            } else {
11031                codeFile.delete();
11032            }
11033
11034            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11035                resourceFile.delete();
11036            }
11037
11038            return true;
11039        }
11040
11041        void cleanUpResourcesLI() {
11042            // Try enumerating all code paths before deleting
11043            List<String> allCodePaths = Collections.EMPTY_LIST;
11044            if (codeFile != null && codeFile.exists()) {
11045                try {
11046                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11047                    allCodePaths = pkg.getAllCodePaths();
11048                } catch (PackageParserException e) {
11049                    // Ignored; we tried our best
11050                }
11051            }
11052
11053            cleanUp();
11054            removeDexFiles(allCodePaths, instructionSets);
11055        }
11056
11057        boolean doPostDeleteLI(boolean delete) {
11058            // XXX err, shouldn't we respect the delete flag?
11059            cleanUpResourcesLI();
11060            return true;
11061        }
11062    }
11063
11064    private boolean isAsecExternal(String cid) {
11065        final String asecPath = PackageHelper.getSdFilesystem(cid);
11066        return !asecPath.startsWith(mAsecInternalPath);
11067    }
11068
11069    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11070            PackageManagerException {
11071        if (copyRet < 0) {
11072            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11073                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11074                throw new PackageManagerException(copyRet, message);
11075            }
11076        }
11077    }
11078
11079    /**
11080     * Extract the MountService "container ID" from the full code path of an
11081     * .apk.
11082     */
11083    static String cidFromCodePath(String fullCodePath) {
11084        int eidx = fullCodePath.lastIndexOf("/");
11085        String subStr1 = fullCodePath.substring(0, eidx);
11086        int sidx = subStr1.lastIndexOf("/");
11087        return subStr1.substring(sidx+1, eidx);
11088    }
11089
11090    /**
11091     * Logic to handle installation of ASEC applications, including copying and
11092     * renaming logic.
11093     */
11094    class AsecInstallArgs extends InstallArgs {
11095        static final String RES_FILE_NAME = "pkg.apk";
11096        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11097
11098        String cid;
11099        String packagePath;
11100        String resourcePath;
11101
11102        /** New install */
11103        AsecInstallArgs(InstallParams params) {
11104            super(params.origin, params.move, params.observer, params.installFlags,
11105                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11106                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11107        }
11108
11109        /** Existing install */
11110        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11111                        boolean isExternal, boolean isForwardLocked) {
11112            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11113                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11114                    instructionSets, null);
11115            // Hackily pretend we're still looking at a full code path
11116            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11117                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11118            }
11119
11120            // Extract cid from fullCodePath
11121            int eidx = fullCodePath.lastIndexOf("/");
11122            String subStr1 = fullCodePath.substring(0, eidx);
11123            int sidx = subStr1.lastIndexOf("/");
11124            cid = subStr1.substring(sidx+1, eidx);
11125            setMountPath(subStr1);
11126        }
11127
11128        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11129            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11130                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11131                    instructionSets, null);
11132            this.cid = cid;
11133            setMountPath(PackageHelper.getSdDir(cid));
11134        }
11135
11136        void createCopyFile() {
11137            cid = mInstallerService.allocateExternalStageCidLegacy();
11138        }
11139
11140        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11141            if (origin.staged) {
11142                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11143                cid = origin.cid;
11144                setMountPath(PackageHelper.getSdDir(cid));
11145                return PackageManager.INSTALL_SUCCEEDED;
11146            }
11147
11148            if (temp) {
11149                createCopyFile();
11150            } else {
11151                /*
11152                 * Pre-emptively destroy the container since it's destroyed if
11153                 * copying fails due to it existing anyway.
11154                 */
11155                PackageHelper.destroySdDir(cid);
11156            }
11157
11158            final String newMountPath = imcs.copyPackageToContainer(
11159                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11160                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11161
11162            if (newMountPath != null) {
11163                setMountPath(newMountPath);
11164                return PackageManager.INSTALL_SUCCEEDED;
11165            } else {
11166                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11167            }
11168        }
11169
11170        @Override
11171        String getCodePath() {
11172            return packagePath;
11173        }
11174
11175        @Override
11176        String getResourcePath() {
11177            return resourcePath;
11178        }
11179
11180        int doPreInstall(int status) {
11181            if (status != PackageManager.INSTALL_SUCCEEDED) {
11182                // Destroy container
11183                PackageHelper.destroySdDir(cid);
11184            } else {
11185                boolean mounted = PackageHelper.isContainerMounted(cid);
11186                if (!mounted) {
11187                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11188                            Process.SYSTEM_UID);
11189                    if (newMountPath != null) {
11190                        setMountPath(newMountPath);
11191                    } else {
11192                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11193                    }
11194                }
11195            }
11196            return status;
11197        }
11198
11199        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11200            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11201            String newMountPath = null;
11202            if (PackageHelper.isContainerMounted(cid)) {
11203                // Unmount the container
11204                if (!PackageHelper.unMountSdDir(cid)) {
11205                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11206                    return false;
11207                }
11208            }
11209            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11210                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11211                        " which might be stale. Will try to clean up.");
11212                // Clean up the stale container and proceed to recreate.
11213                if (!PackageHelper.destroySdDir(newCacheId)) {
11214                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11215                    return false;
11216                }
11217                // Successfully cleaned up stale container. Try to rename again.
11218                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11219                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11220                            + " inspite of cleaning it up.");
11221                    return false;
11222                }
11223            }
11224            if (!PackageHelper.isContainerMounted(newCacheId)) {
11225                Slog.w(TAG, "Mounting container " + newCacheId);
11226                newMountPath = PackageHelper.mountSdDir(newCacheId,
11227                        getEncryptKey(), Process.SYSTEM_UID);
11228            } else {
11229                newMountPath = PackageHelper.getSdDir(newCacheId);
11230            }
11231            if (newMountPath == null) {
11232                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11233                return false;
11234            }
11235            Log.i(TAG, "Succesfully renamed " + cid +
11236                    " to " + newCacheId +
11237                    " at new path: " + newMountPath);
11238            cid = newCacheId;
11239
11240            final File beforeCodeFile = new File(packagePath);
11241            setMountPath(newMountPath);
11242            final File afterCodeFile = new File(packagePath);
11243
11244            // Reflect the rename in scanned details
11245            pkg.codePath = afterCodeFile.getAbsolutePath();
11246            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11247                    pkg.baseCodePath);
11248            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11249                    pkg.splitCodePaths);
11250
11251            // Reflect the rename in app info
11252            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11253            pkg.applicationInfo.setCodePath(pkg.codePath);
11254            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11255            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11256            pkg.applicationInfo.setResourcePath(pkg.codePath);
11257            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11258            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11259
11260            return true;
11261        }
11262
11263        private void setMountPath(String mountPath) {
11264            final File mountFile = new File(mountPath);
11265
11266            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11267            if (monolithicFile.exists()) {
11268                packagePath = monolithicFile.getAbsolutePath();
11269                if (isFwdLocked()) {
11270                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11271                } else {
11272                    resourcePath = packagePath;
11273                }
11274            } else {
11275                packagePath = mountFile.getAbsolutePath();
11276                resourcePath = packagePath;
11277            }
11278        }
11279
11280        int doPostInstall(int status, int uid) {
11281            if (status != PackageManager.INSTALL_SUCCEEDED) {
11282                cleanUp();
11283            } else {
11284                final int groupOwner;
11285                final String protectedFile;
11286                if (isFwdLocked()) {
11287                    groupOwner = UserHandle.getSharedAppGid(uid);
11288                    protectedFile = RES_FILE_NAME;
11289                } else {
11290                    groupOwner = -1;
11291                    protectedFile = null;
11292                }
11293
11294                if (uid < Process.FIRST_APPLICATION_UID
11295                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11296                    Slog.e(TAG, "Failed to finalize " + cid);
11297                    PackageHelper.destroySdDir(cid);
11298                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11299                }
11300
11301                boolean mounted = PackageHelper.isContainerMounted(cid);
11302                if (!mounted) {
11303                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11304                }
11305            }
11306            return status;
11307        }
11308
11309        private void cleanUp() {
11310            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11311
11312            // Destroy secure container
11313            PackageHelper.destroySdDir(cid);
11314        }
11315
11316        private List<String> getAllCodePaths() {
11317            final File codeFile = new File(getCodePath());
11318            if (codeFile != null && codeFile.exists()) {
11319                try {
11320                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11321                    return pkg.getAllCodePaths();
11322                } catch (PackageParserException e) {
11323                    // Ignored; we tried our best
11324                }
11325            }
11326            return Collections.EMPTY_LIST;
11327        }
11328
11329        void cleanUpResourcesLI() {
11330            // Enumerate all code paths before deleting
11331            cleanUpResourcesLI(getAllCodePaths());
11332        }
11333
11334        private void cleanUpResourcesLI(List<String> allCodePaths) {
11335            cleanUp();
11336            removeDexFiles(allCodePaths, instructionSets);
11337        }
11338
11339        String getPackageName() {
11340            return getAsecPackageName(cid);
11341        }
11342
11343        boolean doPostDeleteLI(boolean delete) {
11344            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11345            final List<String> allCodePaths = getAllCodePaths();
11346            boolean mounted = PackageHelper.isContainerMounted(cid);
11347            if (mounted) {
11348                // Unmount first
11349                if (PackageHelper.unMountSdDir(cid)) {
11350                    mounted = false;
11351                }
11352            }
11353            if (!mounted && delete) {
11354                cleanUpResourcesLI(allCodePaths);
11355            }
11356            return !mounted;
11357        }
11358
11359        @Override
11360        int doPreCopy() {
11361            if (isFwdLocked()) {
11362                if (!PackageHelper.fixSdPermissions(cid,
11363                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11364                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11365                }
11366            }
11367
11368            return PackageManager.INSTALL_SUCCEEDED;
11369        }
11370
11371        @Override
11372        int doPostCopy(int uid) {
11373            if (isFwdLocked()) {
11374                if (uid < Process.FIRST_APPLICATION_UID
11375                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11376                                RES_FILE_NAME)) {
11377                    Slog.e(TAG, "Failed to finalize " + cid);
11378                    PackageHelper.destroySdDir(cid);
11379                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11380                }
11381            }
11382
11383            return PackageManager.INSTALL_SUCCEEDED;
11384        }
11385    }
11386
11387    /**
11388     * Logic to handle movement of existing installed applications.
11389     */
11390    class MoveInstallArgs extends InstallArgs {
11391        private File codeFile;
11392        private File resourceFile;
11393
11394        /** New install */
11395        MoveInstallArgs(InstallParams params) {
11396            super(params.origin, params.move, params.observer, params.installFlags,
11397                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11398                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11399        }
11400
11401        int copyApk(IMediaContainerService imcs, boolean temp) {
11402            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11403                    + move.fromUuid + " to " + move.toUuid);
11404            synchronized (mInstaller) {
11405                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11406                        move.dataAppName, move.appId, move.seinfo) != 0) {
11407                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11408                }
11409            }
11410
11411            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11412            resourceFile = codeFile;
11413            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11414
11415            return PackageManager.INSTALL_SUCCEEDED;
11416        }
11417
11418        int doPreInstall(int status) {
11419            if (status != PackageManager.INSTALL_SUCCEEDED) {
11420                cleanUp(move.toUuid);
11421            }
11422            return status;
11423        }
11424
11425        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11426            if (status != PackageManager.INSTALL_SUCCEEDED) {
11427                cleanUp(move.toUuid);
11428                return false;
11429            }
11430
11431            // Reflect the move in app info
11432            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11433            pkg.applicationInfo.setCodePath(pkg.codePath);
11434            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11435            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11436            pkg.applicationInfo.setResourcePath(pkg.codePath);
11437            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11438            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11439
11440            return true;
11441        }
11442
11443        int doPostInstall(int status, int uid) {
11444            if (status == PackageManager.INSTALL_SUCCEEDED) {
11445                cleanUp(move.fromUuid);
11446            } else {
11447                cleanUp(move.toUuid);
11448            }
11449            return status;
11450        }
11451
11452        @Override
11453        String getCodePath() {
11454            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11455        }
11456
11457        @Override
11458        String getResourcePath() {
11459            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11460        }
11461
11462        private boolean cleanUp(String volumeUuid) {
11463            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11464                    move.dataAppName);
11465            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11466            synchronized (mInstallLock) {
11467                // Clean up both app data and code
11468                removeDataDirsLI(volumeUuid, move.packageName);
11469                if (codeFile.isDirectory()) {
11470                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11471                } else {
11472                    codeFile.delete();
11473                }
11474            }
11475            return true;
11476        }
11477
11478        void cleanUpResourcesLI() {
11479            throw new UnsupportedOperationException();
11480        }
11481
11482        boolean doPostDeleteLI(boolean delete) {
11483            throw new UnsupportedOperationException();
11484        }
11485    }
11486
11487    static String getAsecPackageName(String packageCid) {
11488        int idx = packageCid.lastIndexOf("-");
11489        if (idx == -1) {
11490            return packageCid;
11491        }
11492        return packageCid.substring(0, idx);
11493    }
11494
11495    // Utility method used to create code paths based on package name and available index.
11496    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11497        String idxStr = "";
11498        int idx = 1;
11499        // Fall back to default value of idx=1 if prefix is not
11500        // part of oldCodePath
11501        if (oldCodePath != null) {
11502            String subStr = oldCodePath;
11503            // Drop the suffix right away
11504            if (suffix != null && subStr.endsWith(suffix)) {
11505                subStr = subStr.substring(0, subStr.length() - suffix.length());
11506            }
11507            // If oldCodePath already contains prefix find out the
11508            // ending index to either increment or decrement.
11509            int sidx = subStr.lastIndexOf(prefix);
11510            if (sidx != -1) {
11511                subStr = subStr.substring(sidx + prefix.length());
11512                if (subStr != null) {
11513                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11514                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11515                    }
11516                    try {
11517                        idx = Integer.parseInt(subStr);
11518                        if (idx <= 1) {
11519                            idx++;
11520                        } else {
11521                            idx--;
11522                        }
11523                    } catch(NumberFormatException e) {
11524                    }
11525                }
11526            }
11527        }
11528        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11529        return prefix + idxStr;
11530    }
11531
11532    private File getNextCodePath(File targetDir, String packageName) {
11533        int suffix = 1;
11534        File result;
11535        do {
11536            result = new File(targetDir, packageName + "-" + suffix);
11537            suffix++;
11538        } while (result.exists());
11539        return result;
11540    }
11541
11542    // Utility method that returns the relative package path with respect
11543    // to the installation directory. Like say for /data/data/com.test-1.apk
11544    // string com.test-1 is returned.
11545    static String deriveCodePathName(String codePath) {
11546        if (codePath == null) {
11547            return null;
11548        }
11549        final File codeFile = new File(codePath);
11550        final String name = codeFile.getName();
11551        if (codeFile.isDirectory()) {
11552            return name;
11553        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11554            final int lastDot = name.lastIndexOf('.');
11555            return name.substring(0, lastDot);
11556        } else {
11557            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11558            return null;
11559        }
11560    }
11561
11562    class PackageInstalledInfo {
11563        String name;
11564        int uid;
11565        // The set of users that originally had this package installed.
11566        int[] origUsers;
11567        // The set of users that now have this package installed.
11568        int[] newUsers;
11569        PackageParser.Package pkg;
11570        int returnCode;
11571        String returnMsg;
11572        PackageRemovedInfo removedInfo;
11573
11574        public void setError(int code, String msg) {
11575            returnCode = code;
11576            returnMsg = msg;
11577            Slog.w(TAG, msg);
11578        }
11579
11580        public void setError(String msg, PackageParserException e) {
11581            returnCode = e.error;
11582            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11583            Slog.w(TAG, msg, e);
11584        }
11585
11586        public void setError(String msg, PackageManagerException e) {
11587            returnCode = e.error;
11588            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11589            Slog.w(TAG, msg, e);
11590        }
11591
11592        // In some error cases we want to convey more info back to the observer
11593        String origPackage;
11594        String origPermission;
11595    }
11596
11597    /*
11598     * Install a non-existing package.
11599     */
11600    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11601            UserHandle user, String installerPackageName, String volumeUuid,
11602            PackageInstalledInfo res) {
11603        // Remember this for later, in case we need to rollback this install
11604        String pkgName = pkg.packageName;
11605
11606        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11607        final boolean dataDirExists = Environment
11608                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11609        synchronized(mPackages) {
11610            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11611                // A package with the same name is already installed, though
11612                // it has been renamed to an older name.  The package we
11613                // are trying to install should be installed as an update to
11614                // the existing one, but that has not been requested, so bail.
11615                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11616                        + " without first uninstalling package running as "
11617                        + mSettings.mRenamedPackages.get(pkgName));
11618                return;
11619            }
11620            if (mPackages.containsKey(pkgName)) {
11621                // Don't allow installation over an existing package with the same name.
11622                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11623                        + " without first uninstalling.");
11624                return;
11625            }
11626        }
11627
11628        try {
11629            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11630                    System.currentTimeMillis(), user);
11631
11632            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11633            // delete the partially installed application. the data directory will have to be
11634            // restored if it was already existing
11635            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11636                // remove package from internal structures.  Note that we want deletePackageX to
11637                // delete the package data and cache directories that it created in
11638                // scanPackageLocked, unless those directories existed before we even tried to
11639                // install.
11640                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11641                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11642                                res.removedInfo, true);
11643            }
11644
11645        } catch (PackageManagerException e) {
11646            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11647        }
11648    }
11649
11650    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11651        // Can't rotate keys during boot or if sharedUser.
11652        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11653                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11654            return false;
11655        }
11656        // app is using upgradeKeySets; make sure all are valid
11657        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11658        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11659        for (int i = 0; i < upgradeKeySets.length; i++) {
11660            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11661                Slog.wtf(TAG, "Package "
11662                         + (oldPs.name != null ? oldPs.name : "<null>")
11663                         + " contains upgrade-key-set reference to unknown key-set: "
11664                         + upgradeKeySets[i]
11665                         + " reverting to signatures check.");
11666                return false;
11667            }
11668        }
11669        return true;
11670    }
11671
11672    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11673        // Upgrade keysets are being used.  Determine if new package has a superset of the
11674        // required keys.
11675        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11676        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11677        for (int i = 0; i < upgradeKeySets.length; i++) {
11678            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11679            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11680                return true;
11681            }
11682        }
11683        return false;
11684    }
11685
11686    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11687            UserHandle user, String installerPackageName, String volumeUuid,
11688            PackageInstalledInfo res) {
11689        final PackageParser.Package oldPackage;
11690        final String pkgName = pkg.packageName;
11691        final int[] allUsers;
11692        final boolean[] perUserInstalled;
11693        final boolean weFroze;
11694
11695        // First find the old package info and check signatures
11696        synchronized(mPackages) {
11697            oldPackage = mPackages.get(pkgName);
11698            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11699            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11700            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11701                if(!checkUpgradeKeySetLP(ps, pkg)) {
11702                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11703                            "New package not signed by keys specified by upgrade-keysets: "
11704                            + pkgName);
11705                    return;
11706                }
11707            } else {
11708                // default to original signature matching
11709                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11710                    != PackageManager.SIGNATURE_MATCH) {
11711                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11712                            "New package has a different signature: " + pkgName);
11713                    return;
11714                }
11715            }
11716
11717            // In case of rollback, remember per-user/profile install state
11718            allUsers = sUserManager.getUserIds();
11719            perUserInstalled = new boolean[allUsers.length];
11720            for (int i = 0; i < allUsers.length; i++) {
11721                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11722            }
11723
11724            // Mark the app as frozen to prevent launching during the upgrade
11725            // process, and then kill all running instances
11726            if (!ps.frozen) {
11727                ps.frozen = true;
11728                weFroze = true;
11729            } else {
11730                weFroze = false;
11731            }
11732        }
11733
11734        // Now that we're guarded by frozen state, kill app during upgrade
11735        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11736
11737        try {
11738            boolean sysPkg = (isSystemApp(oldPackage));
11739            if (sysPkg) {
11740                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11741                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11742            } else {
11743                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11744                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11745            }
11746        } finally {
11747            // Regardless of success or failure of upgrade steps above, always
11748            // unfreeze the package if we froze it
11749            if (weFroze) {
11750                unfreezePackage(pkgName);
11751            }
11752        }
11753    }
11754
11755    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11756            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11757            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11758            String volumeUuid, PackageInstalledInfo res) {
11759        String pkgName = deletedPackage.packageName;
11760        boolean deletedPkg = true;
11761        boolean updatedSettings = false;
11762
11763        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11764                + deletedPackage);
11765        long origUpdateTime;
11766        if (pkg.mExtras != null) {
11767            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11768        } else {
11769            origUpdateTime = 0;
11770        }
11771
11772        // First delete the existing package while retaining the data directory
11773        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11774                res.removedInfo, true)) {
11775            // If the existing package wasn't successfully deleted
11776            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11777            deletedPkg = false;
11778        } else {
11779            // Successfully deleted the old package; proceed with replace.
11780
11781            // If deleted package lived in a container, give users a chance to
11782            // relinquish resources before killing.
11783            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11784                if (DEBUG_INSTALL) {
11785                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11786                }
11787                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11788                final ArrayList<String> pkgList = new ArrayList<String>(1);
11789                pkgList.add(deletedPackage.applicationInfo.packageName);
11790                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11791            }
11792
11793            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11794            try {
11795                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11796                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11797                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11798                        perUserInstalled, res, user);
11799                updatedSettings = true;
11800            } catch (PackageManagerException e) {
11801                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11802            }
11803        }
11804
11805        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11806            // remove package from internal structures.  Note that we want deletePackageX to
11807            // delete the package data and cache directories that it created in
11808            // scanPackageLocked, unless those directories existed before we even tried to
11809            // install.
11810            if(updatedSettings) {
11811                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11812                deletePackageLI(
11813                        pkgName, null, true, allUsers, perUserInstalled,
11814                        PackageManager.DELETE_KEEP_DATA,
11815                                res.removedInfo, true);
11816            }
11817            // Since we failed to install the new package we need to restore the old
11818            // package that we deleted.
11819            if (deletedPkg) {
11820                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11821                File restoreFile = new File(deletedPackage.codePath);
11822                // Parse old package
11823                boolean oldExternal = isExternal(deletedPackage);
11824                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11825                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11826                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11827                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11828                try {
11829                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11830                } catch (PackageManagerException e) {
11831                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11832                            + e.getMessage());
11833                    return;
11834                }
11835                // Restore of old package succeeded. Update permissions.
11836                // writer
11837                synchronized (mPackages) {
11838                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11839                            UPDATE_PERMISSIONS_ALL);
11840                    // can downgrade to reader
11841                    mSettings.writeLPr();
11842                }
11843                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11844            }
11845        }
11846    }
11847
11848    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11849            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11850            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11851            String volumeUuid, PackageInstalledInfo res) {
11852        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11853                + ", old=" + deletedPackage);
11854        boolean disabledSystem = false;
11855        boolean updatedSettings = false;
11856        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11857        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11858                != 0) {
11859            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11860        }
11861        String packageName = deletedPackage.packageName;
11862        if (packageName == null) {
11863            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11864                    "Attempt to delete null packageName.");
11865            return;
11866        }
11867        PackageParser.Package oldPkg;
11868        PackageSetting oldPkgSetting;
11869        // reader
11870        synchronized (mPackages) {
11871            oldPkg = mPackages.get(packageName);
11872            oldPkgSetting = mSettings.mPackages.get(packageName);
11873            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11874                    (oldPkgSetting == null)) {
11875                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11876                        "Couldn't find package:" + packageName + " information");
11877                return;
11878            }
11879        }
11880
11881        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11882        res.removedInfo.removedPackage = packageName;
11883        // Remove existing system package
11884        removePackageLI(oldPkgSetting, true);
11885        // writer
11886        synchronized (mPackages) {
11887            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11888            if (!disabledSystem && deletedPackage != null) {
11889                // We didn't need to disable the .apk as a current system package,
11890                // which means we are replacing another update that is already
11891                // installed.  We need to make sure to delete the older one's .apk.
11892                res.removedInfo.args = createInstallArgsForExisting(0,
11893                        deletedPackage.applicationInfo.getCodePath(),
11894                        deletedPackage.applicationInfo.getResourcePath(),
11895                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11896            } else {
11897                res.removedInfo.args = null;
11898            }
11899        }
11900
11901        // Successfully disabled the old package. Now proceed with re-installation
11902        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11903
11904        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11905        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11906
11907        PackageParser.Package newPackage = null;
11908        try {
11909            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11910            if (newPackage.mExtras != null) {
11911                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11912                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11913                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11914
11915                // is the update attempting to change shared user? that isn't going to work...
11916                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11917                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11918                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11919                            + " to " + newPkgSetting.sharedUser);
11920                    updatedSettings = true;
11921                }
11922            }
11923
11924            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11925                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11926                        perUserInstalled, res, user);
11927                updatedSettings = true;
11928            }
11929
11930        } catch (PackageManagerException e) {
11931            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11932        }
11933
11934        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11935            // Re installation failed. Restore old information
11936            // Remove new pkg information
11937            if (newPackage != null) {
11938                removeInstalledPackageLI(newPackage, true);
11939            }
11940            // Add back the old system package
11941            try {
11942                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11943            } catch (PackageManagerException e) {
11944                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11945            }
11946            // Restore the old system information in Settings
11947            synchronized (mPackages) {
11948                if (disabledSystem) {
11949                    mSettings.enableSystemPackageLPw(packageName);
11950                }
11951                if (updatedSettings) {
11952                    mSettings.setInstallerPackageName(packageName,
11953                            oldPkgSetting.installerPackageName);
11954                }
11955                mSettings.writeLPr();
11956            }
11957        }
11958    }
11959
11960    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11961            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11962            UserHandle user) {
11963        String pkgName = newPackage.packageName;
11964        synchronized (mPackages) {
11965            //write settings. the installStatus will be incomplete at this stage.
11966            //note that the new package setting would have already been
11967            //added to mPackages. It hasn't been persisted yet.
11968            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11969            mSettings.writeLPr();
11970        }
11971
11972        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11973
11974        synchronized (mPackages) {
11975            updatePermissionsLPw(newPackage.packageName, newPackage,
11976                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11977                            ? UPDATE_PERMISSIONS_ALL : 0));
11978            // For system-bundled packages, we assume that installing an upgraded version
11979            // of the package implies that the user actually wants to run that new code,
11980            // so we enable the package.
11981            PackageSetting ps = mSettings.mPackages.get(pkgName);
11982            if (ps != null) {
11983                if (isSystemApp(newPackage)) {
11984                    // NB: implicit assumption that system package upgrades apply to all users
11985                    if (DEBUG_INSTALL) {
11986                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11987                    }
11988                    if (res.origUsers != null) {
11989                        for (int userHandle : res.origUsers) {
11990                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11991                                    userHandle, installerPackageName);
11992                        }
11993                    }
11994                    // Also convey the prior install/uninstall state
11995                    if (allUsers != null && perUserInstalled != null) {
11996                        for (int i = 0; i < allUsers.length; i++) {
11997                            if (DEBUG_INSTALL) {
11998                                Slog.d(TAG, "    user " + allUsers[i]
11999                                        + " => " + perUserInstalled[i]);
12000                            }
12001                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12002                        }
12003                        // these install state changes will be persisted in the
12004                        // upcoming call to mSettings.writeLPr().
12005                    }
12006                }
12007                // It's implied that when a user requests installation, they want the app to be
12008                // installed and enabled.
12009                int userId = user.getIdentifier();
12010                if (userId != UserHandle.USER_ALL) {
12011                    ps.setInstalled(true, userId);
12012                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12013                }
12014            }
12015            res.name = pkgName;
12016            res.uid = newPackage.applicationInfo.uid;
12017            res.pkg = newPackage;
12018            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12019            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12020            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12021            //to update install status
12022            mSettings.writeLPr();
12023        }
12024    }
12025
12026    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12027        final int installFlags = args.installFlags;
12028        final String installerPackageName = args.installerPackageName;
12029        final String volumeUuid = args.volumeUuid;
12030        final File tmpPackageFile = new File(args.getCodePath());
12031        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12032        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12033                || (args.volumeUuid != null));
12034        boolean replace = false;
12035        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12036        if (args.move != null) {
12037            // moving a complete application; perfom an initial scan on the new install location
12038            scanFlags |= SCAN_INITIAL;
12039        }
12040        // Result object to be returned
12041        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12042
12043        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12044        // Retrieve PackageSettings and parse package
12045        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12046                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12047                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12048        PackageParser pp = new PackageParser();
12049        pp.setSeparateProcesses(mSeparateProcesses);
12050        pp.setDisplayMetrics(mMetrics);
12051
12052        final PackageParser.Package pkg;
12053        try {
12054            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12055        } catch (PackageParserException e) {
12056            res.setError("Failed parse during installPackageLI", e);
12057            return;
12058        }
12059
12060        // Mark that we have an install time CPU ABI override.
12061        pkg.cpuAbiOverride = args.abiOverride;
12062
12063        String pkgName = res.name = pkg.packageName;
12064        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12065            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12066                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12067                return;
12068            }
12069        }
12070
12071        try {
12072            pp.collectCertificates(pkg, parseFlags);
12073            pp.collectManifestDigest(pkg);
12074        } catch (PackageParserException e) {
12075            res.setError("Failed collect during installPackageLI", e);
12076            return;
12077        }
12078
12079        /* If the installer passed in a manifest digest, compare it now. */
12080        if (args.manifestDigest != null) {
12081            if (DEBUG_INSTALL) {
12082                final String parsedManifest = pkg.manifestDigest == null ? "null"
12083                        : pkg.manifestDigest.toString();
12084                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12085                        + parsedManifest);
12086            }
12087
12088            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12089                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12090                return;
12091            }
12092        } else if (DEBUG_INSTALL) {
12093            final String parsedManifest = pkg.manifestDigest == null
12094                    ? "null" : pkg.manifestDigest.toString();
12095            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12096        }
12097
12098        // Get rid of all references to package scan path via parser.
12099        pp = null;
12100        String oldCodePath = null;
12101        boolean systemApp = false;
12102        synchronized (mPackages) {
12103            // Check if installing already existing package
12104            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12105                String oldName = mSettings.mRenamedPackages.get(pkgName);
12106                if (pkg.mOriginalPackages != null
12107                        && pkg.mOriginalPackages.contains(oldName)
12108                        && mPackages.containsKey(oldName)) {
12109                    // This package is derived from an original package,
12110                    // and this device has been updating from that original
12111                    // name.  We must continue using the original name, so
12112                    // rename the new package here.
12113                    pkg.setPackageName(oldName);
12114                    pkgName = pkg.packageName;
12115                    replace = true;
12116                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12117                            + oldName + " pkgName=" + pkgName);
12118                } else if (mPackages.containsKey(pkgName)) {
12119                    // This package, under its official name, already exists
12120                    // on the device; we should replace it.
12121                    replace = true;
12122                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12123                }
12124
12125                // Prevent apps opting out from runtime permissions
12126                if (replace) {
12127                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12128                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12129                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12130                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12131                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12132                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12133                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12134                                        + " doesn't support runtime permissions but the old"
12135                                        + " target SDK " + oldTargetSdk + " does.");
12136                        return;
12137                    }
12138                }
12139            }
12140
12141            PackageSetting ps = mSettings.mPackages.get(pkgName);
12142            if (ps != null) {
12143                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12144
12145                // Quick sanity check that we're signed correctly if updating;
12146                // we'll check this again later when scanning, but we want to
12147                // bail early here before tripping over redefined permissions.
12148                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12149                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12150                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12151                                + pkg.packageName + " upgrade keys do not match the "
12152                                + "previously installed version");
12153                        return;
12154                    }
12155                } else {
12156                    try {
12157                        verifySignaturesLP(ps, pkg);
12158                    } catch (PackageManagerException e) {
12159                        res.setError(e.error, e.getMessage());
12160                        return;
12161                    }
12162                }
12163
12164                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12165                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12166                    systemApp = (ps.pkg.applicationInfo.flags &
12167                            ApplicationInfo.FLAG_SYSTEM) != 0;
12168                }
12169                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12170            }
12171
12172            // Check whether the newly-scanned package wants to define an already-defined perm
12173            int N = pkg.permissions.size();
12174            for (int i = N-1; i >= 0; i--) {
12175                PackageParser.Permission perm = pkg.permissions.get(i);
12176                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12177                if (bp != null) {
12178                    // If the defining package is signed with our cert, it's okay.  This
12179                    // also includes the "updating the same package" case, of course.
12180                    // "updating same package" could also involve key-rotation.
12181                    final boolean sigsOk;
12182                    if (bp.sourcePackage.equals(pkg.packageName)
12183                            && (bp.packageSetting instanceof PackageSetting)
12184                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12185                                    scanFlags))) {
12186                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12187                    } else {
12188                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12189                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12190                    }
12191                    if (!sigsOk) {
12192                        // If the owning package is the system itself, we log but allow
12193                        // install to proceed; we fail the install on all other permission
12194                        // redefinitions.
12195                        if (!bp.sourcePackage.equals("android")) {
12196                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12197                                    + pkg.packageName + " attempting to redeclare permission "
12198                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12199                            res.origPermission = perm.info.name;
12200                            res.origPackage = bp.sourcePackage;
12201                            return;
12202                        } else {
12203                            Slog.w(TAG, "Package " + pkg.packageName
12204                                    + " attempting to redeclare system permission "
12205                                    + perm.info.name + "; ignoring new declaration");
12206                            pkg.permissions.remove(i);
12207                        }
12208                    }
12209                }
12210            }
12211
12212        }
12213
12214        if (systemApp && onExternal) {
12215            // Disable updates to system apps on sdcard
12216            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12217                    "Cannot install updates to system apps on sdcard");
12218            return;
12219        }
12220
12221        if (args.move != null) {
12222            // We did an in-place move, so dex is ready to roll
12223            scanFlags |= SCAN_NO_DEX;
12224            scanFlags |= SCAN_MOVE;
12225        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12226            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12227            scanFlags |= SCAN_NO_DEX;
12228
12229            try {
12230                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12231                        true /* extract libs */);
12232            } catch (PackageManagerException pme) {
12233                Slog.e(TAG, "Error deriving application ABI", pme);
12234                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12235                return;
12236            }
12237
12238            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12239            int result = mPackageDexOptimizer
12240                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12241                            false /* defer */, false /* inclDependencies */);
12242            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12243                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12244                return;
12245            }
12246        }
12247
12248        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12249            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12250            return;
12251        }
12252
12253        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12254
12255        if (replace) {
12256            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12257                    installerPackageName, volumeUuid, res);
12258        } else {
12259            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12260                    args.user, installerPackageName, volumeUuid, res);
12261        }
12262        synchronized (mPackages) {
12263            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12264            if (ps != null) {
12265                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12266            }
12267        }
12268    }
12269
12270    private void startIntentFilterVerifications(int userId, boolean replacing,
12271            PackageParser.Package pkg) {
12272        if (mIntentFilterVerifierComponent == null) {
12273            Slog.w(TAG, "No IntentFilter verification will not be done as "
12274                    + "there is no IntentFilterVerifier available!");
12275            return;
12276        }
12277
12278        final int verifierUid = getPackageUid(
12279                mIntentFilterVerifierComponent.getPackageName(),
12280                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12281
12282        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12283        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12284        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12285        mHandler.sendMessage(msg);
12286    }
12287
12288    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12289            PackageParser.Package pkg) {
12290        int size = pkg.activities.size();
12291        if (size == 0) {
12292            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12293                    "No activity, so no need to verify any IntentFilter!");
12294            return;
12295        }
12296
12297        final boolean hasDomainURLs = hasDomainURLs(pkg);
12298        if (!hasDomainURLs) {
12299            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12300                    "No domain URLs, so no need to verify any IntentFilter!");
12301            return;
12302        }
12303
12304        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12305                + " if any IntentFilter from the " + size
12306                + " Activities needs verification ...");
12307
12308        int count = 0;
12309        final String packageName = pkg.packageName;
12310
12311        synchronized (mPackages) {
12312            // If this is a new install and we see that we've already run verification for this
12313            // package, we have nothing to do: it means the state was restored from backup.
12314            if (!replacing) {
12315                IntentFilterVerificationInfo ivi =
12316                        mSettings.getIntentFilterVerificationLPr(packageName);
12317                if (ivi != null) {
12318                    if (DEBUG_DOMAIN_VERIFICATION) {
12319                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12320                                + ivi.getStatusString());
12321                    }
12322                    return;
12323                }
12324            }
12325
12326            // If any filters need to be verified, then all need to be.
12327            boolean needToVerify = false;
12328            for (PackageParser.Activity a : pkg.activities) {
12329                for (ActivityIntentInfo filter : a.intents) {
12330                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12331                        if (DEBUG_DOMAIN_VERIFICATION) {
12332                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12333                        }
12334                        needToVerify = true;
12335                        break;
12336                    }
12337                }
12338            }
12339
12340            if (needToVerify) {
12341                final int verificationId = mIntentFilterVerificationToken++;
12342                for (PackageParser.Activity a : pkg.activities) {
12343                    for (ActivityIntentInfo filter : a.intents) {
12344                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12345                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12346                                    "Verification needed for IntentFilter:" + filter.toString());
12347                            mIntentFilterVerifier.addOneIntentFilterVerification(
12348                                    verifierUid, userId, verificationId, filter, packageName);
12349                            count++;
12350                        }
12351                    }
12352                }
12353            }
12354        }
12355
12356        if (count > 0) {
12357            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12358                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12359                    +  " for userId:" + userId);
12360            mIntentFilterVerifier.startVerifications(userId);
12361        } else {
12362            if (DEBUG_DOMAIN_VERIFICATION) {
12363                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12364            }
12365        }
12366    }
12367
12368    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12369        final ComponentName cn  = filter.activity.getComponentName();
12370        final String packageName = cn.getPackageName();
12371
12372        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12373                packageName);
12374        if (ivi == null) {
12375            return true;
12376        }
12377        int status = ivi.getStatus();
12378        switch (status) {
12379            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12380            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12381                return true;
12382
12383            default:
12384                // Nothing to do
12385                return false;
12386        }
12387    }
12388
12389    private static boolean isMultiArch(PackageSetting ps) {
12390        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12391    }
12392
12393    private static boolean isMultiArch(ApplicationInfo info) {
12394        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12395    }
12396
12397    private static boolean isExternal(PackageParser.Package pkg) {
12398        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12399    }
12400
12401    private static boolean isExternal(PackageSetting ps) {
12402        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12403    }
12404
12405    private static boolean isExternal(ApplicationInfo info) {
12406        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12407    }
12408
12409    private static boolean isSystemApp(PackageParser.Package pkg) {
12410        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12411    }
12412
12413    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12414        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12415    }
12416
12417    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12418        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12419    }
12420
12421    private static boolean isSystemApp(PackageSetting ps) {
12422        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12423    }
12424
12425    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12426        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12427    }
12428
12429    private int packageFlagsToInstallFlags(PackageSetting ps) {
12430        int installFlags = 0;
12431        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12432            // This existing package was an external ASEC install when we have
12433            // the external flag without a UUID
12434            installFlags |= PackageManager.INSTALL_EXTERNAL;
12435        }
12436        if (ps.isForwardLocked()) {
12437            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12438        }
12439        return installFlags;
12440    }
12441
12442    private void deleteTempPackageFiles() {
12443        final FilenameFilter filter = new FilenameFilter() {
12444            public boolean accept(File dir, String name) {
12445                return name.startsWith("vmdl") && name.endsWith(".tmp");
12446            }
12447        };
12448        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12449            file.delete();
12450        }
12451    }
12452
12453    @Override
12454    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12455            int flags) {
12456        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12457                flags);
12458    }
12459
12460    @Override
12461    public void deletePackage(final String packageName,
12462            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12463        mContext.enforceCallingOrSelfPermission(
12464                android.Manifest.permission.DELETE_PACKAGES, null);
12465        Preconditions.checkNotNull(packageName);
12466        Preconditions.checkNotNull(observer);
12467        final int uid = Binder.getCallingUid();
12468        if (UserHandle.getUserId(uid) != userId) {
12469            mContext.enforceCallingPermission(
12470                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12471                    "deletePackage for user " + userId);
12472        }
12473        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12474            try {
12475                observer.onPackageDeleted(packageName,
12476                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12477            } catch (RemoteException re) {
12478            }
12479            return;
12480        }
12481
12482        boolean uninstallBlocked = false;
12483        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12484            int[] users = sUserManager.getUserIds();
12485            for (int i = 0; i < users.length; ++i) {
12486                if (getBlockUninstallForUser(packageName, users[i])) {
12487                    uninstallBlocked = true;
12488                    break;
12489                }
12490            }
12491        } else {
12492            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12493        }
12494        if (uninstallBlocked) {
12495            try {
12496                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12497                        null);
12498            } catch (RemoteException re) {
12499            }
12500            return;
12501        }
12502
12503        if (DEBUG_REMOVE) {
12504            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12505        }
12506        // Queue up an async operation since the package deletion may take a little while.
12507        mHandler.post(new Runnable() {
12508            public void run() {
12509                mHandler.removeCallbacks(this);
12510                final int returnCode = deletePackageX(packageName, userId, flags);
12511                if (observer != null) {
12512                    try {
12513                        observer.onPackageDeleted(packageName, returnCode, null);
12514                    } catch (RemoteException e) {
12515                        Log.i(TAG, "Observer no longer exists.");
12516                    } //end catch
12517                } //end if
12518            } //end run
12519        });
12520    }
12521
12522    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12523        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12524                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12525        try {
12526            if (dpm != null) {
12527                if (dpm.isDeviceOwner(packageName)) {
12528                    return true;
12529                }
12530                int[] users;
12531                if (userId == UserHandle.USER_ALL) {
12532                    users = sUserManager.getUserIds();
12533                } else {
12534                    users = new int[]{userId};
12535                }
12536                for (int i = 0; i < users.length; ++i) {
12537                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12538                        return true;
12539                    }
12540                }
12541            }
12542        } catch (RemoteException e) {
12543        }
12544        return false;
12545    }
12546
12547    /**
12548     *  This method is an internal method that could be get invoked either
12549     *  to delete an installed package or to clean up a failed installation.
12550     *  After deleting an installed package, a broadcast is sent to notify any
12551     *  listeners that the package has been installed. For cleaning up a failed
12552     *  installation, the broadcast is not necessary since the package's
12553     *  installation wouldn't have sent the initial broadcast either
12554     *  The key steps in deleting a package are
12555     *  deleting the package information in internal structures like mPackages,
12556     *  deleting the packages base directories through installd
12557     *  updating mSettings to reflect current status
12558     *  persisting settings for later use
12559     *  sending a broadcast if necessary
12560     */
12561    private int deletePackageX(String packageName, int userId, int flags) {
12562        final PackageRemovedInfo info = new PackageRemovedInfo();
12563        final boolean res;
12564
12565        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12566                ? UserHandle.ALL : new UserHandle(userId);
12567
12568        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12569            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12570            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12571        }
12572
12573        boolean removedForAllUsers = false;
12574        boolean systemUpdate = false;
12575
12576        // for the uninstall-updates case and restricted profiles, remember the per-
12577        // userhandle installed state
12578        int[] allUsers;
12579        boolean[] perUserInstalled;
12580        synchronized (mPackages) {
12581            PackageSetting ps = mSettings.mPackages.get(packageName);
12582            allUsers = sUserManager.getUserIds();
12583            perUserInstalled = new boolean[allUsers.length];
12584            for (int i = 0; i < allUsers.length; i++) {
12585                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12586            }
12587        }
12588
12589        synchronized (mInstallLock) {
12590            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12591            res = deletePackageLI(packageName, removeForUser,
12592                    true, allUsers, perUserInstalled,
12593                    flags | REMOVE_CHATTY, info, true);
12594            systemUpdate = info.isRemovedPackageSystemUpdate;
12595            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12596                removedForAllUsers = true;
12597            }
12598            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12599                    + " removedForAllUsers=" + removedForAllUsers);
12600        }
12601
12602        if (res) {
12603            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12604
12605            // If the removed package was a system update, the old system package
12606            // was re-enabled; we need to broadcast this information
12607            if (systemUpdate) {
12608                Bundle extras = new Bundle(1);
12609                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12610                        ? info.removedAppId : info.uid);
12611                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12612
12613                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12614                        extras, null, null, null);
12615                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12616                        extras, null, null, null);
12617                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12618                        null, packageName, null, null);
12619            }
12620        }
12621        // Force a gc here.
12622        Runtime.getRuntime().gc();
12623        // Delete the resources here after sending the broadcast to let
12624        // other processes clean up before deleting resources.
12625        if (info.args != null) {
12626            synchronized (mInstallLock) {
12627                info.args.doPostDeleteLI(true);
12628            }
12629        }
12630
12631        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12632    }
12633
12634    class PackageRemovedInfo {
12635        String removedPackage;
12636        int uid = -1;
12637        int removedAppId = -1;
12638        int[] removedUsers = null;
12639        boolean isRemovedPackageSystemUpdate = false;
12640        // Clean up resources deleted packages.
12641        InstallArgs args = null;
12642
12643        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12644            Bundle extras = new Bundle(1);
12645            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12646            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12647            if (replacing) {
12648                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12649            }
12650            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12651            if (removedPackage != null) {
12652                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12653                        extras, null, null, removedUsers);
12654                if (fullRemove && !replacing) {
12655                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12656                            extras, null, null, removedUsers);
12657                }
12658            }
12659            if (removedAppId >= 0) {
12660                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12661                        removedUsers);
12662            }
12663        }
12664    }
12665
12666    /*
12667     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12668     * flag is not set, the data directory is removed as well.
12669     * make sure this flag is set for partially installed apps. If not its meaningless to
12670     * delete a partially installed application.
12671     */
12672    private void removePackageDataLI(PackageSetting ps,
12673            int[] allUserHandles, boolean[] perUserInstalled,
12674            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12675        String packageName = ps.name;
12676        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12677        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12678        // Retrieve object to delete permissions for shared user later on
12679        final PackageSetting deletedPs;
12680        // reader
12681        synchronized (mPackages) {
12682            deletedPs = mSettings.mPackages.get(packageName);
12683            if (outInfo != null) {
12684                outInfo.removedPackage = packageName;
12685                outInfo.removedUsers = deletedPs != null
12686                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12687                        : null;
12688            }
12689        }
12690        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12691            removeDataDirsLI(ps.volumeUuid, packageName);
12692            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12693        }
12694        // writer
12695        synchronized (mPackages) {
12696            if (deletedPs != null) {
12697                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12698                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12699                    clearDefaultBrowserIfNeeded(packageName);
12700                    if (outInfo != null) {
12701                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12702                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12703                    }
12704                    updatePermissionsLPw(deletedPs.name, null, 0);
12705                    if (deletedPs.sharedUser != null) {
12706                        // Remove permissions associated with package. Since runtime
12707                        // permissions are per user we have to kill the removed package
12708                        // or packages running under the shared user of the removed
12709                        // package if revoking the permissions requested only by the removed
12710                        // package is successful and this causes a change in gids.
12711                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12712                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12713                                    userId);
12714                            if (userIdToKill == UserHandle.USER_ALL
12715                                    || userIdToKill >= UserHandle.USER_OWNER) {
12716                                // If gids changed for this user, kill all affected packages.
12717                                mHandler.post(new Runnable() {
12718                                    @Override
12719                                    public void run() {
12720                                        // This has to happen with no lock held.
12721                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12722                                                KILL_APP_REASON_GIDS_CHANGED);
12723                                    }
12724                                });
12725                                break;
12726                            }
12727                        }
12728                    }
12729                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12730                }
12731                // make sure to preserve per-user disabled state if this removal was just
12732                // a downgrade of a system app to the factory package
12733                if (allUserHandles != null && perUserInstalled != null) {
12734                    if (DEBUG_REMOVE) {
12735                        Slog.d(TAG, "Propagating install state across downgrade");
12736                    }
12737                    for (int i = 0; i < allUserHandles.length; i++) {
12738                        if (DEBUG_REMOVE) {
12739                            Slog.d(TAG, "    user " + allUserHandles[i]
12740                                    + " => " + perUserInstalled[i]);
12741                        }
12742                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12743                    }
12744                }
12745            }
12746            // can downgrade to reader
12747            if (writeSettings) {
12748                // Save settings now
12749                mSettings.writeLPr();
12750            }
12751        }
12752        if (outInfo != null) {
12753            // A user ID was deleted here. Go through all users and remove it
12754            // from KeyStore.
12755            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12756        }
12757    }
12758
12759    static boolean locationIsPrivileged(File path) {
12760        try {
12761            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12762                    .getCanonicalPath();
12763            return path.getCanonicalPath().startsWith(privilegedAppDir);
12764        } catch (IOException e) {
12765            Slog.e(TAG, "Unable to access code path " + path);
12766        }
12767        return false;
12768    }
12769
12770    /*
12771     * Tries to delete system package.
12772     */
12773    private boolean deleteSystemPackageLI(PackageSetting newPs,
12774            int[] allUserHandles, boolean[] perUserInstalled,
12775            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12776        final boolean applyUserRestrictions
12777                = (allUserHandles != null) && (perUserInstalled != null);
12778        PackageSetting disabledPs = null;
12779        // Confirm if the system package has been updated
12780        // An updated system app can be deleted. This will also have to restore
12781        // the system pkg from system partition
12782        // reader
12783        synchronized (mPackages) {
12784            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12785        }
12786        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12787                + " disabledPs=" + disabledPs);
12788        if (disabledPs == null) {
12789            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12790            return false;
12791        } else if (DEBUG_REMOVE) {
12792            Slog.d(TAG, "Deleting system pkg from data partition");
12793        }
12794        if (DEBUG_REMOVE) {
12795            if (applyUserRestrictions) {
12796                Slog.d(TAG, "Remembering install states:");
12797                for (int i = 0; i < allUserHandles.length; i++) {
12798                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12799                }
12800            }
12801        }
12802        // Delete the updated package
12803        outInfo.isRemovedPackageSystemUpdate = true;
12804        if (disabledPs.versionCode < newPs.versionCode) {
12805            // Delete data for downgrades
12806            flags &= ~PackageManager.DELETE_KEEP_DATA;
12807        } else {
12808            // Preserve data by setting flag
12809            flags |= PackageManager.DELETE_KEEP_DATA;
12810        }
12811        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12812                allUserHandles, perUserInstalled, outInfo, writeSettings);
12813        if (!ret) {
12814            return false;
12815        }
12816        // writer
12817        synchronized (mPackages) {
12818            // Reinstate the old system package
12819            mSettings.enableSystemPackageLPw(newPs.name);
12820            // Remove any native libraries from the upgraded package.
12821            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12822        }
12823        // Install the system package
12824        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12825        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12826        if (locationIsPrivileged(disabledPs.codePath)) {
12827            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12828        }
12829
12830        final PackageParser.Package newPkg;
12831        try {
12832            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12833        } catch (PackageManagerException e) {
12834            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12835            return false;
12836        }
12837
12838        // writer
12839        synchronized (mPackages) {
12840            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12841
12842            // Propagate the permissions state as we do want to drop on the floor
12843            // runtime permissions. The update permissions method below will take
12844            // care of removing obsolete permissions and grant install permissions.
12845            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12846            updatePermissionsLPw(newPkg.packageName, newPkg,
12847                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12848
12849            if (applyUserRestrictions) {
12850                if (DEBUG_REMOVE) {
12851                    Slog.d(TAG, "Propagating install state across reinstall");
12852                }
12853                for (int i = 0; i < allUserHandles.length; i++) {
12854                    if (DEBUG_REMOVE) {
12855                        Slog.d(TAG, "    user " + allUserHandles[i]
12856                                + " => " + perUserInstalled[i]);
12857                    }
12858                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12859                }
12860                // Regardless of writeSettings we need to ensure that this restriction
12861                // state propagation is persisted
12862                mSettings.writeAllUsersPackageRestrictionsLPr();
12863            }
12864            // can downgrade to reader here
12865            if (writeSettings) {
12866                mSettings.writeLPr();
12867            }
12868        }
12869        return true;
12870    }
12871
12872    private boolean deleteInstalledPackageLI(PackageSetting ps,
12873            boolean deleteCodeAndResources, int flags,
12874            int[] allUserHandles, boolean[] perUserInstalled,
12875            PackageRemovedInfo outInfo, boolean writeSettings) {
12876        if (outInfo != null) {
12877            outInfo.uid = ps.appId;
12878        }
12879
12880        // Delete package data from internal structures and also remove data if flag is set
12881        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12882
12883        // Delete application code and resources
12884        if (deleteCodeAndResources && (outInfo != null)) {
12885            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12886                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12887            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12888        }
12889        return true;
12890    }
12891
12892    @Override
12893    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12894            int userId) {
12895        mContext.enforceCallingOrSelfPermission(
12896                android.Manifest.permission.DELETE_PACKAGES, null);
12897        synchronized (mPackages) {
12898            PackageSetting ps = mSettings.mPackages.get(packageName);
12899            if (ps == null) {
12900                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12901                return false;
12902            }
12903            if (!ps.getInstalled(userId)) {
12904                // Can't block uninstall for an app that is not installed or enabled.
12905                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12906                return false;
12907            }
12908            ps.setBlockUninstall(blockUninstall, userId);
12909            mSettings.writePackageRestrictionsLPr(userId);
12910        }
12911        return true;
12912    }
12913
12914    @Override
12915    public boolean getBlockUninstallForUser(String packageName, int userId) {
12916        synchronized (mPackages) {
12917            PackageSetting ps = mSettings.mPackages.get(packageName);
12918            if (ps == null) {
12919                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12920                return false;
12921            }
12922            return ps.getBlockUninstall(userId);
12923        }
12924    }
12925
12926    /*
12927     * This method handles package deletion in general
12928     */
12929    private boolean deletePackageLI(String packageName, UserHandle user,
12930            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12931            int flags, PackageRemovedInfo outInfo,
12932            boolean writeSettings) {
12933        if (packageName == null) {
12934            Slog.w(TAG, "Attempt to delete null packageName.");
12935            return false;
12936        }
12937        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12938        PackageSetting ps;
12939        boolean dataOnly = false;
12940        int removeUser = -1;
12941        int appId = -1;
12942        synchronized (mPackages) {
12943            ps = mSettings.mPackages.get(packageName);
12944            if (ps == null) {
12945                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12946                return false;
12947            }
12948            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12949                    && user.getIdentifier() != UserHandle.USER_ALL) {
12950                // The caller is asking that the package only be deleted for a single
12951                // user.  To do this, we just mark its uninstalled state and delete
12952                // its data.  If this is a system app, we only allow this to happen if
12953                // they have set the special DELETE_SYSTEM_APP which requests different
12954                // semantics than normal for uninstalling system apps.
12955                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12956                ps.setUserState(user.getIdentifier(),
12957                        COMPONENT_ENABLED_STATE_DEFAULT,
12958                        false, //installed
12959                        true,  //stopped
12960                        true,  //notLaunched
12961                        false, //hidden
12962                        null, null, null,
12963                        false, // blockUninstall
12964                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12965                if (!isSystemApp(ps)) {
12966                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12967                        // Other user still have this package installed, so all
12968                        // we need to do is clear this user's data and save that
12969                        // it is uninstalled.
12970                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12971                        removeUser = user.getIdentifier();
12972                        appId = ps.appId;
12973                        scheduleWritePackageRestrictionsLocked(removeUser);
12974                    } else {
12975                        // We need to set it back to 'installed' so the uninstall
12976                        // broadcasts will be sent correctly.
12977                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12978                        ps.setInstalled(true, user.getIdentifier());
12979                    }
12980                } else {
12981                    // This is a system app, so we assume that the
12982                    // other users still have this package installed, so all
12983                    // we need to do is clear this user's data and save that
12984                    // it is uninstalled.
12985                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12986                    removeUser = user.getIdentifier();
12987                    appId = ps.appId;
12988                    scheduleWritePackageRestrictionsLocked(removeUser);
12989                }
12990            }
12991        }
12992
12993        if (removeUser >= 0) {
12994            // From above, we determined that we are deleting this only
12995            // for a single user.  Continue the work here.
12996            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12997            if (outInfo != null) {
12998                outInfo.removedPackage = packageName;
12999                outInfo.removedAppId = appId;
13000                outInfo.removedUsers = new int[] {removeUser};
13001            }
13002            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13003            removeKeystoreDataIfNeeded(removeUser, appId);
13004            schedulePackageCleaning(packageName, removeUser, false);
13005            synchronized (mPackages) {
13006                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13007                    scheduleWritePackageRestrictionsLocked(removeUser);
13008                }
13009                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13010            }
13011            return true;
13012        }
13013
13014        if (dataOnly) {
13015            // Delete application data first
13016            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13017            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13018            return true;
13019        }
13020
13021        boolean ret = false;
13022        if (isSystemApp(ps)) {
13023            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13024            // When an updated system application is deleted we delete the existing resources as well and
13025            // fall back to existing code in system partition
13026            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13027                    flags, outInfo, writeSettings);
13028        } else {
13029            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13030            // Kill application pre-emptively especially for apps on sd.
13031            killApplication(packageName, ps.appId, "uninstall pkg");
13032            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13033                    allUserHandles, perUserInstalled,
13034                    outInfo, writeSettings);
13035        }
13036
13037        return ret;
13038    }
13039
13040    private final class ClearStorageConnection implements ServiceConnection {
13041        IMediaContainerService mContainerService;
13042
13043        @Override
13044        public void onServiceConnected(ComponentName name, IBinder service) {
13045            synchronized (this) {
13046                mContainerService = IMediaContainerService.Stub.asInterface(service);
13047                notifyAll();
13048            }
13049        }
13050
13051        @Override
13052        public void onServiceDisconnected(ComponentName name) {
13053        }
13054    }
13055
13056    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13057        final boolean mounted;
13058        if (Environment.isExternalStorageEmulated()) {
13059            mounted = true;
13060        } else {
13061            final String status = Environment.getExternalStorageState();
13062
13063            mounted = status.equals(Environment.MEDIA_MOUNTED)
13064                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13065        }
13066
13067        if (!mounted) {
13068            return;
13069        }
13070
13071        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13072        int[] users;
13073        if (userId == UserHandle.USER_ALL) {
13074            users = sUserManager.getUserIds();
13075        } else {
13076            users = new int[] { userId };
13077        }
13078        final ClearStorageConnection conn = new ClearStorageConnection();
13079        if (mContext.bindServiceAsUser(
13080                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13081            try {
13082                for (int curUser : users) {
13083                    long timeout = SystemClock.uptimeMillis() + 5000;
13084                    synchronized (conn) {
13085                        long now = SystemClock.uptimeMillis();
13086                        while (conn.mContainerService == null && now < timeout) {
13087                            try {
13088                                conn.wait(timeout - now);
13089                            } catch (InterruptedException e) {
13090                            }
13091                        }
13092                    }
13093                    if (conn.mContainerService == null) {
13094                        return;
13095                    }
13096
13097                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13098                    clearDirectory(conn.mContainerService,
13099                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13100                    if (allData) {
13101                        clearDirectory(conn.mContainerService,
13102                                userEnv.buildExternalStorageAppDataDirs(packageName));
13103                        clearDirectory(conn.mContainerService,
13104                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13105                    }
13106                }
13107            } finally {
13108                mContext.unbindService(conn);
13109            }
13110        }
13111    }
13112
13113    @Override
13114    public void clearApplicationUserData(final String packageName,
13115            final IPackageDataObserver observer, final int userId) {
13116        mContext.enforceCallingOrSelfPermission(
13117                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13118        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13119        // Queue up an async operation since the package deletion may take a little while.
13120        mHandler.post(new Runnable() {
13121            public void run() {
13122                mHandler.removeCallbacks(this);
13123                final boolean succeeded;
13124                synchronized (mInstallLock) {
13125                    succeeded = clearApplicationUserDataLI(packageName, userId);
13126                }
13127                clearExternalStorageDataSync(packageName, userId, true);
13128                if (succeeded) {
13129                    // invoke DeviceStorageMonitor's update method to clear any notifications
13130                    DeviceStorageMonitorInternal
13131                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13132                    if (dsm != null) {
13133                        dsm.checkMemory();
13134                    }
13135                }
13136                if(observer != null) {
13137                    try {
13138                        observer.onRemoveCompleted(packageName, succeeded);
13139                    } catch (RemoteException e) {
13140                        Log.i(TAG, "Observer no longer exists.");
13141                    }
13142                } //end if observer
13143            } //end run
13144        });
13145    }
13146
13147    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13148        if (packageName == null) {
13149            Slog.w(TAG, "Attempt to delete null packageName.");
13150            return false;
13151        }
13152
13153        // Try finding details about the requested package
13154        PackageParser.Package pkg;
13155        synchronized (mPackages) {
13156            pkg = mPackages.get(packageName);
13157            if (pkg == null) {
13158                final PackageSetting ps = mSettings.mPackages.get(packageName);
13159                if (ps != null) {
13160                    pkg = ps.pkg;
13161                }
13162            }
13163
13164            if (pkg == null) {
13165                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13166                return false;
13167            }
13168
13169            PackageSetting ps = (PackageSetting) pkg.mExtras;
13170            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13171        }
13172
13173        // Always delete data directories for package, even if we found no other
13174        // record of app. This helps users recover from UID mismatches without
13175        // resorting to a full data wipe.
13176        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13177        if (retCode < 0) {
13178            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13179            return false;
13180        }
13181
13182        final int appId = pkg.applicationInfo.uid;
13183        removeKeystoreDataIfNeeded(userId, appId);
13184
13185        // Create a native library symlink only if we have native libraries
13186        // and if the native libraries are 32 bit libraries. We do not provide
13187        // this symlink for 64 bit libraries.
13188        if (pkg.applicationInfo.primaryCpuAbi != null &&
13189                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13190            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13191            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13192                    nativeLibPath, userId) < 0) {
13193                Slog.w(TAG, "Failed linking native library dir");
13194                return false;
13195            }
13196        }
13197
13198        return true;
13199    }
13200
13201    /**
13202     * Reverts user permission state changes (permissions and flags).
13203     *
13204     * @param ps The package for which to reset.
13205     * @param userId The device user for which to do a reset.
13206     */
13207    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13208            final PackageSetting ps, final int userId) {
13209        if (ps.pkg == null) {
13210            return;
13211        }
13212
13213        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13214                | FLAG_PERMISSION_USER_FIXED
13215                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13216
13217        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13218                | FLAG_PERMISSION_POLICY_FIXED;
13219
13220        boolean writeInstallPermissions = false;
13221        boolean writeRuntimePermissions = false;
13222
13223        final int permissionCount = ps.pkg.requestedPermissions.size();
13224        for (int i = 0; i < permissionCount; i++) {
13225            String permission = ps.pkg.requestedPermissions.get(i);
13226
13227            BasePermission bp = mSettings.mPermissions.get(permission);
13228            if (bp == null) {
13229                continue;
13230            }
13231
13232            // If shared user we just reset the state to which only this app contributed.
13233            if (ps.sharedUser != null) {
13234                boolean used = false;
13235                final int packageCount = ps.sharedUser.packages.size();
13236                for (int j = 0; j < packageCount; j++) {
13237                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13238                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13239                            && pkg.pkg.requestedPermissions.contains(permission)) {
13240                        used = true;
13241                        break;
13242                    }
13243                }
13244                if (used) {
13245                    continue;
13246                }
13247            }
13248
13249            PermissionsState permissionsState = ps.getPermissionsState();
13250
13251            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13252
13253            // Always clear the user settable flags.
13254            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13255                    bp.name) != null;
13256            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13257                if (hasInstallState) {
13258                    writeInstallPermissions = true;
13259                } else {
13260                    writeRuntimePermissions = true;
13261                }
13262            }
13263
13264            // Below is only runtime permission handling.
13265            if (!bp.isRuntime()) {
13266                continue;
13267            }
13268
13269            // Never clobber system or policy.
13270            if ((oldFlags & policyOrSystemFlags) != 0) {
13271                continue;
13272            }
13273
13274            // If this permission was granted by default, make sure it is.
13275            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13276                if (permissionsState.grantRuntimePermission(bp, userId)
13277                        != PERMISSION_OPERATION_FAILURE) {
13278                    writeRuntimePermissions = true;
13279                }
13280            } else {
13281                // Otherwise, reset the permission.
13282                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13283                switch (revokeResult) {
13284                    case PERMISSION_OPERATION_SUCCESS: {
13285                        writeRuntimePermissions = true;
13286                    } break;
13287
13288                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13289                        writeRuntimePermissions = true;
13290                        // If gids changed for this user, kill all affected packages.
13291                        mHandler.post(new Runnable() {
13292                            @Override
13293                            public void run() {
13294                                // This has to happen with no lock held.
13295                                killSettingPackagesForUser(ps, userId,
13296                                        KILL_APP_REASON_GIDS_CHANGED);
13297                            }
13298                        });
13299                    } break;
13300                }
13301            }
13302        }
13303
13304        // Synchronously write as we are taking permissions away.
13305        if (writeRuntimePermissions) {
13306            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13307        }
13308
13309        // Synchronously write as we are taking permissions away.
13310        if (writeInstallPermissions) {
13311            mSettings.writeLPr();
13312        }
13313    }
13314
13315    /**
13316     * Remove entries from the keystore daemon. Will only remove it if the
13317     * {@code appId} is valid.
13318     */
13319    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13320        if (appId < 0) {
13321            return;
13322        }
13323
13324        final KeyStore keyStore = KeyStore.getInstance();
13325        if (keyStore != null) {
13326            if (userId == UserHandle.USER_ALL) {
13327                for (final int individual : sUserManager.getUserIds()) {
13328                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13329                }
13330            } else {
13331                keyStore.clearUid(UserHandle.getUid(userId, appId));
13332            }
13333        } else {
13334            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13335        }
13336    }
13337
13338    @Override
13339    public void deleteApplicationCacheFiles(final String packageName,
13340            final IPackageDataObserver observer) {
13341        mContext.enforceCallingOrSelfPermission(
13342                android.Manifest.permission.DELETE_CACHE_FILES, null);
13343        // Queue up an async operation since the package deletion may take a little while.
13344        final int userId = UserHandle.getCallingUserId();
13345        mHandler.post(new Runnable() {
13346            public void run() {
13347                mHandler.removeCallbacks(this);
13348                final boolean succeded;
13349                synchronized (mInstallLock) {
13350                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13351                }
13352                clearExternalStorageDataSync(packageName, userId, false);
13353                if (observer != null) {
13354                    try {
13355                        observer.onRemoveCompleted(packageName, succeded);
13356                    } catch (RemoteException e) {
13357                        Log.i(TAG, "Observer no longer exists.");
13358                    }
13359                } //end if observer
13360            } //end run
13361        });
13362    }
13363
13364    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13365        if (packageName == null) {
13366            Slog.w(TAG, "Attempt to delete null packageName.");
13367            return false;
13368        }
13369        PackageParser.Package p;
13370        synchronized (mPackages) {
13371            p = mPackages.get(packageName);
13372        }
13373        if (p == null) {
13374            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13375            return false;
13376        }
13377        final ApplicationInfo applicationInfo = p.applicationInfo;
13378        if (applicationInfo == null) {
13379            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13380            return false;
13381        }
13382        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13383        if (retCode < 0) {
13384            Slog.w(TAG, "Couldn't remove cache files for package: "
13385                       + packageName + " u" + userId);
13386            return false;
13387        }
13388        return true;
13389    }
13390
13391    @Override
13392    public void getPackageSizeInfo(final String packageName, int userHandle,
13393            final IPackageStatsObserver observer) {
13394        mContext.enforceCallingOrSelfPermission(
13395                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13396        if (packageName == null) {
13397            throw new IllegalArgumentException("Attempt to get size of null packageName");
13398        }
13399
13400        PackageStats stats = new PackageStats(packageName, userHandle);
13401
13402        /*
13403         * Queue up an async operation since the package measurement may take a
13404         * little while.
13405         */
13406        Message msg = mHandler.obtainMessage(INIT_COPY);
13407        msg.obj = new MeasureParams(stats, observer);
13408        mHandler.sendMessage(msg);
13409    }
13410
13411    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13412            PackageStats pStats) {
13413        if (packageName == null) {
13414            Slog.w(TAG, "Attempt to get size of null packageName.");
13415            return false;
13416        }
13417        PackageParser.Package p;
13418        boolean dataOnly = false;
13419        String libDirRoot = null;
13420        String asecPath = null;
13421        PackageSetting ps = null;
13422        synchronized (mPackages) {
13423            p = mPackages.get(packageName);
13424            ps = mSettings.mPackages.get(packageName);
13425            if(p == null) {
13426                dataOnly = true;
13427                if((ps == null) || (ps.pkg == null)) {
13428                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13429                    return false;
13430                }
13431                p = ps.pkg;
13432            }
13433            if (ps != null) {
13434                libDirRoot = ps.legacyNativeLibraryPathString;
13435            }
13436            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13437                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13438                if (secureContainerId != null) {
13439                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13440                }
13441            }
13442        }
13443        String publicSrcDir = null;
13444        if(!dataOnly) {
13445            final ApplicationInfo applicationInfo = p.applicationInfo;
13446            if (applicationInfo == null) {
13447                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13448                return false;
13449            }
13450            if (p.isForwardLocked()) {
13451                publicSrcDir = applicationInfo.getBaseResourcePath();
13452            }
13453        }
13454        // TODO: extend to measure size of split APKs
13455        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13456        // not just the first level.
13457        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13458        // just the primary.
13459        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13460        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13461                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13462        if (res < 0) {
13463            return false;
13464        }
13465
13466        // Fix-up for forward-locked applications in ASEC containers.
13467        if (!isExternal(p)) {
13468            pStats.codeSize += pStats.externalCodeSize;
13469            pStats.externalCodeSize = 0L;
13470        }
13471
13472        return true;
13473    }
13474
13475
13476    @Override
13477    public void addPackageToPreferred(String packageName) {
13478        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13479    }
13480
13481    @Override
13482    public void removePackageFromPreferred(String packageName) {
13483        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13484    }
13485
13486    @Override
13487    public List<PackageInfo> getPreferredPackages(int flags) {
13488        return new ArrayList<PackageInfo>();
13489    }
13490
13491    private int getUidTargetSdkVersionLockedLPr(int uid) {
13492        Object obj = mSettings.getUserIdLPr(uid);
13493        if (obj instanceof SharedUserSetting) {
13494            final SharedUserSetting sus = (SharedUserSetting) obj;
13495            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13496            final Iterator<PackageSetting> it = sus.packages.iterator();
13497            while (it.hasNext()) {
13498                final PackageSetting ps = it.next();
13499                if (ps.pkg != null) {
13500                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13501                    if (v < vers) vers = v;
13502                }
13503            }
13504            return vers;
13505        } else if (obj instanceof PackageSetting) {
13506            final PackageSetting ps = (PackageSetting) obj;
13507            if (ps.pkg != null) {
13508                return ps.pkg.applicationInfo.targetSdkVersion;
13509            }
13510        }
13511        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13512    }
13513
13514    @Override
13515    public void addPreferredActivity(IntentFilter filter, int match,
13516            ComponentName[] set, ComponentName activity, int userId) {
13517        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13518                "Adding preferred");
13519    }
13520
13521    private void addPreferredActivityInternal(IntentFilter filter, int match,
13522            ComponentName[] set, ComponentName activity, boolean always, int userId,
13523            String opname) {
13524        // writer
13525        int callingUid = Binder.getCallingUid();
13526        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13527        if (filter.countActions() == 0) {
13528            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13529            return;
13530        }
13531        synchronized (mPackages) {
13532            if (mContext.checkCallingOrSelfPermission(
13533                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13534                    != PackageManager.PERMISSION_GRANTED) {
13535                if (getUidTargetSdkVersionLockedLPr(callingUid)
13536                        < Build.VERSION_CODES.FROYO) {
13537                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13538                            + callingUid);
13539                    return;
13540                }
13541                mContext.enforceCallingOrSelfPermission(
13542                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13543            }
13544
13545            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13546            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13547                    + userId + ":");
13548            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13549            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13550            scheduleWritePackageRestrictionsLocked(userId);
13551        }
13552    }
13553
13554    @Override
13555    public void replacePreferredActivity(IntentFilter filter, int match,
13556            ComponentName[] set, ComponentName activity, int userId) {
13557        if (filter.countActions() != 1) {
13558            throw new IllegalArgumentException(
13559                    "replacePreferredActivity expects filter to have only 1 action.");
13560        }
13561        if (filter.countDataAuthorities() != 0
13562                || filter.countDataPaths() != 0
13563                || filter.countDataSchemes() > 1
13564                || filter.countDataTypes() != 0) {
13565            throw new IllegalArgumentException(
13566                    "replacePreferredActivity expects filter to have no data authorities, " +
13567                    "paths, or types; and at most one scheme.");
13568        }
13569
13570        final int callingUid = Binder.getCallingUid();
13571        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13572        synchronized (mPackages) {
13573            if (mContext.checkCallingOrSelfPermission(
13574                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13575                    != PackageManager.PERMISSION_GRANTED) {
13576                if (getUidTargetSdkVersionLockedLPr(callingUid)
13577                        < Build.VERSION_CODES.FROYO) {
13578                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13579                            + Binder.getCallingUid());
13580                    return;
13581                }
13582                mContext.enforceCallingOrSelfPermission(
13583                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13584            }
13585
13586            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13587            if (pir != null) {
13588                // Get all of the existing entries that exactly match this filter.
13589                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13590                if (existing != null && existing.size() == 1) {
13591                    PreferredActivity cur = existing.get(0);
13592                    if (DEBUG_PREFERRED) {
13593                        Slog.i(TAG, "Checking replace of preferred:");
13594                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13595                        if (!cur.mPref.mAlways) {
13596                            Slog.i(TAG, "  -- CUR; not mAlways!");
13597                        } else {
13598                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13599                            Slog.i(TAG, "  -- CUR: mSet="
13600                                    + Arrays.toString(cur.mPref.mSetComponents));
13601                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13602                            Slog.i(TAG, "  -- NEW: mMatch="
13603                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13604                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13605                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13606                        }
13607                    }
13608                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13609                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13610                            && cur.mPref.sameSet(set)) {
13611                        // Setting the preferred activity to what it happens to be already
13612                        if (DEBUG_PREFERRED) {
13613                            Slog.i(TAG, "Replacing with same preferred activity "
13614                                    + cur.mPref.mShortComponent + " for user "
13615                                    + userId + ":");
13616                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13617                        }
13618                        return;
13619                    }
13620                }
13621
13622                if (existing != null) {
13623                    if (DEBUG_PREFERRED) {
13624                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13625                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13626                    }
13627                    for (int i = 0; i < existing.size(); i++) {
13628                        PreferredActivity pa = existing.get(i);
13629                        if (DEBUG_PREFERRED) {
13630                            Slog.i(TAG, "Removing existing preferred activity "
13631                                    + pa.mPref.mComponent + ":");
13632                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13633                        }
13634                        pir.removeFilter(pa);
13635                    }
13636                }
13637            }
13638            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13639                    "Replacing preferred");
13640        }
13641    }
13642
13643    @Override
13644    public void clearPackagePreferredActivities(String packageName) {
13645        final int uid = Binder.getCallingUid();
13646        // writer
13647        synchronized (mPackages) {
13648            PackageParser.Package pkg = mPackages.get(packageName);
13649            if (pkg == null || pkg.applicationInfo.uid != uid) {
13650                if (mContext.checkCallingOrSelfPermission(
13651                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13652                        != PackageManager.PERMISSION_GRANTED) {
13653                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13654                            < Build.VERSION_CODES.FROYO) {
13655                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13656                                + Binder.getCallingUid());
13657                        return;
13658                    }
13659                    mContext.enforceCallingOrSelfPermission(
13660                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13661                }
13662            }
13663
13664            int user = UserHandle.getCallingUserId();
13665            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13666                scheduleWritePackageRestrictionsLocked(user);
13667            }
13668        }
13669    }
13670
13671    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13672    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13673        ArrayList<PreferredActivity> removed = null;
13674        boolean changed = false;
13675        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13676            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13677            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13678            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13679                continue;
13680            }
13681            Iterator<PreferredActivity> it = pir.filterIterator();
13682            while (it.hasNext()) {
13683                PreferredActivity pa = it.next();
13684                // Mark entry for removal only if it matches the package name
13685                // and the entry is of type "always".
13686                if (packageName == null ||
13687                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13688                                && pa.mPref.mAlways)) {
13689                    if (removed == null) {
13690                        removed = new ArrayList<PreferredActivity>();
13691                    }
13692                    removed.add(pa);
13693                }
13694            }
13695            if (removed != null) {
13696                for (int j=0; j<removed.size(); j++) {
13697                    PreferredActivity pa = removed.get(j);
13698                    pir.removeFilter(pa);
13699                }
13700                changed = true;
13701            }
13702        }
13703        return changed;
13704    }
13705
13706    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13707    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13708        if (userId == UserHandle.USER_ALL) {
13709            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13710                    sUserManager.getUserIds())) {
13711                for (int oneUserId : sUserManager.getUserIds()) {
13712                    scheduleWritePackageRestrictionsLocked(oneUserId);
13713                }
13714            }
13715        } else {
13716            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13717                scheduleWritePackageRestrictionsLocked(userId);
13718            }
13719        }
13720    }
13721
13722
13723    void clearDefaultBrowserIfNeeded(String packageName) {
13724        for (int oneUserId : sUserManager.getUserIds()) {
13725            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13726            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13727            if (packageName.equals(defaultBrowserPackageName)) {
13728                setDefaultBrowserPackageName(null, oneUserId);
13729            }
13730        }
13731    }
13732
13733    @Override
13734    public void resetPreferredActivities(int userId) {
13735        mContext.enforceCallingOrSelfPermission(
13736                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13737        // writer
13738        synchronized (mPackages) {
13739            clearPackagePreferredActivitiesLPw(null, userId);
13740            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13741            applyFactoryDefaultBrowserLPw(userId);
13742            primeDomainVerificationsLPw(userId);
13743
13744            scheduleWritePackageRestrictionsLocked(userId);
13745        }
13746    }
13747
13748    @Override
13749    public int getPreferredActivities(List<IntentFilter> outFilters,
13750            List<ComponentName> outActivities, String packageName) {
13751
13752        int num = 0;
13753        final int userId = UserHandle.getCallingUserId();
13754        // reader
13755        synchronized (mPackages) {
13756            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13757            if (pir != null) {
13758                final Iterator<PreferredActivity> it = pir.filterIterator();
13759                while (it.hasNext()) {
13760                    final PreferredActivity pa = it.next();
13761                    if (packageName == null
13762                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13763                                    && pa.mPref.mAlways)) {
13764                        if (outFilters != null) {
13765                            outFilters.add(new IntentFilter(pa));
13766                        }
13767                        if (outActivities != null) {
13768                            outActivities.add(pa.mPref.mComponent);
13769                        }
13770                    }
13771                }
13772            }
13773        }
13774
13775        return num;
13776    }
13777
13778    @Override
13779    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13780            int userId) {
13781        int callingUid = Binder.getCallingUid();
13782        if (callingUid != Process.SYSTEM_UID) {
13783            throw new SecurityException(
13784                    "addPersistentPreferredActivity can only be run by the system");
13785        }
13786        if (filter.countActions() == 0) {
13787            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13788            return;
13789        }
13790        synchronized (mPackages) {
13791            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13792                    " :");
13793            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13794            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13795                    new PersistentPreferredActivity(filter, activity));
13796            scheduleWritePackageRestrictionsLocked(userId);
13797        }
13798    }
13799
13800    @Override
13801    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13802        int callingUid = Binder.getCallingUid();
13803        if (callingUid != Process.SYSTEM_UID) {
13804            throw new SecurityException(
13805                    "clearPackagePersistentPreferredActivities can only be run by the system");
13806        }
13807        ArrayList<PersistentPreferredActivity> removed = null;
13808        boolean changed = false;
13809        synchronized (mPackages) {
13810            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13811                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13812                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13813                        .valueAt(i);
13814                if (userId != thisUserId) {
13815                    continue;
13816                }
13817                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13818                while (it.hasNext()) {
13819                    PersistentPreferredActivity ppa = it.next();
13820                    // Mark entry for removal only if it matches the package name.
13821                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13822                        if (removed == null) {
13823                            removed = new ArrayList<PersistentPreferredActivity>();
13824                        }
13825                        removed.add(ppa);
13826                    }
13827                }
13828                if (removed != null) {
13829                    for (int j=0; j<removed.size(); j++) {
13830                        PersistentPreferredActivity ppa = removed.get(j);
13831                        ppir.removeFilter(ppa);
13832                    }
13833                    changed = true;
13834                }
13835            }
13836
13837            if (changed) {
13838                scheduleWritePackageRestrictionsLocked(userId);
13839            }
13840        }
13841    }
13842
13843    /**
13844     * Common machinery for picking apart a restored XML blob and passing
13845     * it to a caller-supplied functor to be applied to the running system.
13846     */
13847    private void restoreFromXml(XmlPullParser parser, int userId,
13848            String expectedStartTag, BlobXmlRestorer functor)
13849            throws IOException, XmlPullParserException {
13850        int type;
13851        while ((type = parser.next()) != XmlPullParser.START_TAG
13852                && type != XmlPullParser.END_DOCUMENT) {
13853        }
13854        if (type != XmlPullParser.START_TAG) {
13855            // oops didn't find a start tag?!
13856            if (DEBUG_BACKUP) {
13857                Slog.e(TAG, "Didn't find start tag during restore");
13858            }
13859            return;
13860        }
13861
13862        // this is supposed to be TAG_PREFERRED_BACKUP
13863        if (!expectedStartTag.equals(parser.getName())) {
13864            if (DEBUG_BACKUP) {
13865                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13866            }
13867            return;
13868        }
13869
13870        // skip interfering stuff, then we're aligned with the backing implementation
13871        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13872        functor.apply(parser, userId);
13873    }
13874
13875    private interface BlobXmlRestorer {
13876        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13877    }
13878
13879    /**
13880     * Non-Binder method, support for the backup/restore mechanism: write the
13881     * full set of preferred activities in its canonical XML format.  Returns the
13882     * XML output as a byte array, or null if there is none.
13883     */
13884    @Override
13885    public byte[] getPreferredActivityBackup(int userId) {
13886        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13887            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13888        }
13889
13890        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13891        try {
13892            final XmlSerializer serializer = new FastXmlSerializer();
13893            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13894            serializer.startDocument(null, true);
13895            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13896
13897            synchronized (mPackages) {
13898                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13899            }
13900
13901            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13902            serializer.endDocument();
13903            serializer.flush();
13904        } catch (Exception e) {
13905            if (DEBUG_BACKUP) {
13906                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13907            }
13908            return null;
13909        }
13910
13911        return dataStream.toByteArray();
13912    }
13913
13914    @Override
13915    public void restorePreferredActivities(byte[] backup, int userId) {
13916        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13917            throw new SecurityException("Only the system may call restorePreferredActivities()");
13918        }
13919
13920        try {
13921            final XmlPullParser parser = Xml.newPullParser();
13922            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13923            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13924                    new BlobXmlRestorer() {
13925                        @Override
13926                        public void apply(XmlPullParser parser, int userId)
13927                                throws XmlPullParserException, IOException {
13928                            synchronized (mPackages) {
13929                                mSettings.readPreferredActivitiesLPw(parser, userId);
13930                            }
13931                        }
13932                    } );
13933        } catch (Exception e) {
13934            if (DEBUG_BACKUP) {
13935                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13936            }
13937        }
13938    }
13939
13940    /**
13941     * Non-Binder method, support for the backup/restore mechanism: write the
13942     * default browser (etc) settings in its canonical XML format.  Returns the default
13943     * browser XML representation as a byte array, or null if there is none.
13944     */
13945    @Override
13946    public byte[] getDefaultAppsBackup(int userId) {
13947        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13948            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13949        }
13950
13951        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13952        try {
13953            final XmlSerializer serializer = new FastXmlSerializer();
13954            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13955            serializer.startDocument(null, true);
13956            serializer.startTag(null, TAG_DEFAULT_APPS);
13957
13958            synchronized (mPackages) {
13959                mSettings.writeDefaultAppsLPr(serializer, userId);
13960            }
13961
13962            serializer.endTag(null, TAG_DEFAULT_APPS);
13963            serializer.endDocument();
13964            serializer.flush();
13965        } catch (Exception e) {
13966            if (DEBUG_BACKUP) {
13967                Slog.e(TAG, "Unable to write default apps for backup", e);
13968            }
13969            return null;
13970        }
13971
13972        return dataStream.toByteArray();
13973    }
13974
13975    @Override
13976    public void restoreDefaultApps(byte[] backup, int userId) {
13977        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13978            throw new SecurityException("Only the system may call restoreDefaultApps()");
13979        }
13980
13981        try {
13982            final XmlPullParser parser = Xml.newPullParser();
13983            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13984            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13985                    new BlobXmlRestorer() {
13986                        @Override
13987                        public void apply(XmlPullParser parser, int userId)
13988                                throws XmlPullParserException, IOException {
13989                            synchronized (mPackages) {
13990                                mSettings.readDefaultAppsLPw(parser, userId);
13991                            }
13992                        }
13993                    } );
13994        } catch (Exception e) {
13995            if (DEBUG_BACKUP) {
13996                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13997            }
13998        }
13999    }
14000
14001    @Override
14002    public byte[] getIntentFilterVerificationBackup(int userId) {
14003        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14004            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14005        }
14006
14007        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14008        try {
14009            final XmlSerializer serializer = new FastXmlSerializer();
14010            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14011            serializer.startDocument(null, true);
14012            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14013
14014            synchronized (mPackages) {
14015                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14016            }
14017
14018            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14019            serializer.endDocument();
14020            serializer.flush();
14021        } catch (Exception e) {
14022            if (DEBUG_BACKUP) {
14023                Slog.e(TAG, "Unable to write default apps for backup", e);
14024            }
14025            return null;
14026        }
14027
14028        return dataStream.toByteArray();
14029    }
14030
14031    @Override
14032    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14033        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14034            throw new SecurityException("Only the system may call restorePreferredActivities()");
14035        }
14036
14037        try {
14038            final XmlPullParser parser = Xml.newPullParser();
14039            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14040            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14041                    new BlobXmlRestorer() {
14042                        @Override
14043                        public void apply(XmlPullParser parser, int userId)
14044                                throws XmlPullParserException, IOException {
14045                            synchronized (mPackages) {
14046                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14047                                mSettings.writeLPr();
14048                            }
14049                        }
14050                    } );
14051        } catch (Exception e) {
14052            if (DEBUG_BACKUP) {
14053                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14054            }
14055        }
14056    }
14057
14058    @Override
14059    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14060            int sourceUserId, int targetUserId, int flags) {
14061        mContext.enforceCallingOrSelfPermission(
14062                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14063        int callingUid = Binder.getCallingUid();
14064        enforceOwnerRights(ownerPackage, callingUid);
14065        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14066        if (intentFilter.countActions() == 0) {
14067            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14068            return;
14069        }
14070        synchronized (mPackages) {
14071            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14072                    ownerPackage, targetUserId, flags);
14073            CrossProfileIntentResolver resolver =
14074                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14075            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14076            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14077            if (existing != null) {
14078                int size = existing.size();
14079                for (int i = 0; i < size; i++) {
14080                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14081                        return;
14082                    }
14083                }
14084            }
14085            resolver.addFilter(newFilter);
14086            scheduleWritePackageRestrictionsLocked(sourceUserId);
14087        }
14088    }
14089
14090    @Override
14091    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14092        mContext.enforceCallingOrSelfPermission(
14093                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14094        int callingUid = Binder.getCallingUid();
14095        enforceOwnerRights(ownerPackage, callingUid);
14096        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14097        synchronized (mPackages) {
14098            CrossProfileIntentResolver resolver =
14099                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14100            ArraySet<CrossProfileIntentFilter> set =
14101                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14102            for (CrossProfileIntentFilter filter : set) {
14103                if (filter.getOwnerPackage().equals(ownerPackage)) {
14104                    resolver.removeFilter(filter);
14105                }
14106            }
14107            scheduleWritePackageRestrictionsLocked(sourceUserId);
14108        }
14109    }
14110
14111    // Enforcing that callingUid is owning pkg on userId
14112    private void enforceOwnerRights(String pkg, int callingUid) {
14113        // The system owns everything.
14114        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14115            return;
14116        }
14117        int callingUserId = UserHandle.getUserId(callingUid);
14118        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14119        if (pi == null) {
14120            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14121                    + callingUserId);
14122        }
14123        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14124            throw new SecurityException("Calling uid " + callingUid
14125                    + " does not own package " + pkg);
14126        }
14127    }
14128
14129    @Override
14130    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14131        Intent intent = new Intent(Intent.ACTION_MAIN);
14132        intent.addCategory(Intent.CATEGORY_HOME);
14133
14134        final int callingUserId = UserHandle.getCallingUserId();
14135        List<ResolveInfo> list = queryIntentActivities(intent, null,
14136                PackageManager.GET_META_DATA, callingUserId);
14137        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14138                true, false, false, callingUserId);
14139
14140        allHomeCandidates.clear();
14141        if (list != null) {
14142            for (ResolveInfo ri : list) {
14143                allHomeCandidates.add(ri);
14144            }
14145        }
14146        return (preferred == null || preferred.activityInfo == null)
14147                ? null
14148                : new ComponentName(preferred.activityInfo.packageName,
14149                        preferred.activityInfo.name);
14150    }
14151
14152    @Override
14153    public void setApplicationEnabledSetting(String appPackageName,
14154            int newState, int flags, int userId, String callingPackage) {
14155        if (!sUserManager.exists(userId)) return;
14156        if (callingPackage == null) {
14157            callingPackage = Integer.toString(Binder.getCallingUid());
14158        }
14159        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14160    }
14161
14162    @Override
14163    public void setComponentEnabledSetting(ComponentName componentName,
14164            int newState, int flags, int userId) {
14165        if (!sUserManager.exists(userId)) return;
14166        setEnabledSetting(componentName.getPackageName(),
14167                componentName.getClassName(), newState, flags, userId, null);
14168    }
14169
14170    private void setEnabledSetting(final String packageName, String className, int newState,
14171            final int flags, int userId, String callingPackage) {
14172        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14173              || newState == COMPONENT_ENABLED_STATE_ENABLED
14174              || newState == COMPONENT_ENABLED_STATE_DISABLED
14175              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14176              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14177            throw new IllegalArgumentException("Invalid new component state: "
14178                    + newState);
14179        }
14180        PackageSetting pkgSetting;
14181        final int uid = Binder.getCallingUid();
14182        final int permission = mContext.checkCallingOrSelfPermission(
14183                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14184        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14185        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14186        boolean sendNow = false;
14187        boolean isApp = (className == null);
14188        String componentName = isApp ? packageName : className;
14189        int packageUid = -1;
14190        ArrayList<String> components;
14191
14192        // writer
14193        synchronized (mPackages) {
14194            pkgSetting = mSettings.mPackages.get(packageName);
14195            if (pkgSetting == null) {
14196                if (className == null) {
14197                    throw new IllegalArgumentException(
14198                            "Unknown package: " + packageName);
14199                }
14200                throw new IllegalArgumentException(
14201                        "Unknown component: " + packageName
14202                        + "/" + className);
14203            }
14204            // Allow root and verify that userId is not being specified by a different user
14205            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14206                throw new SecurityException(
14207                        "Permission Denial: attempt to change component state from pid="
14208                        + Binder.getCallingPid()
14209                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14210            }
14211            if (className == null) {
14212                // We're dealing with an application/package level state change
14213                if (pkgSetting.getEnabled(userId) == newState) {
14214                    // Nothing to do
14215                    return;
14216                }
14217                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14218                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14219                    // Don't care about who enables an app.
14220                    callingPackage = null;
14221                }
14222                pkgSetting.setEnabled(newState, userId, callingPackage);
14223                // pkgSetting.pkg.mSetEnabled = newState;
14224            } else {
14225                // We're dealing with a component level state change
14226                // First, verify that this is a valid class name.
14227                PackageParser.Package pkg = pkgSetting.pkg;
14228                if (pkg == null || !pkg.hasComponentClassName(className)) {
14229                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14230                        throw new IllegalArgumentException("Component class " + className
14231                                + " does not exist in " + packageName);
14232                    } else {
14233                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14234                                + className + " does not exist in " + packageName);
14235                    }
14236                }
14237                switch (newState) {
14238                case COMPONENT_ENABLED_STATE_ENABLED:
14239                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14240                        return;
14241                    }
14242                    break;
14243                case COMPONENT_ENABLED_STATE_DISABLED:
14244                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14245                        return;
14246                    }
14247                    break;
14248                case COMPONENT_ENABLED_STATE_DEFAULT:
14249                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14250                        return;
14251                    }
14252                    break;
14253                default:
14254                    Slog.e(TAG, "Invalid new component state: " + newState);
14255                    return;
14256                }
14257            }
14258            scheduleWritePackageRestrictionsLocked(userId);
14259            components = mPendingBroadcasts.get(userId, packageName);
14260            final boolean newPackage = components == null;
14261            if (newPackage) {
14262                components = new ArrayList<String>();
14263            }
14264            if (!components.contains(componentName)) {
14265                components.add(componentName);
14266            }
14267            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14268                sendNow = true;
14269                // Purge entry from pending broadcast list if another one exists already
14270                // since we are sending one right away.
14271                mPendingBroadcasts.remove(userId, packageName);
14272            } else {
14273                if (newPackage) {
14274                    mPendingBroadcasts.put(userId, packageName, components);
14275                }
14276                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14277                    // Schedule a message
14278                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14279                }
14280            }
14281        }
14282
14283        long callingId = Binder.clearCallingIdentity();
14284        try {
14285            if (sendNow) {
14286                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14287                sendPackageChangedBroadcast(packageName,
14288                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14289            }
14290        } finally {
14291            Binder.restoreCallingIdentity(callingId);
14292        }
14293    }
14294
14295    private void sendPackageChangedBroadcast(String packageName,
14296            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14297        if (DEBUG_INSTALL)
14298            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14299                    + componentNames);
14300        Bundle extras = new Bundle(4);
14301        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14302        String nameList[] = new String[componentNames.size()];
14303        componentNames.toArray(nameList);
14304        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14305        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14306        extras.putInt(Intent.EXTRA_UID, packageUid);
14307        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14308                new int[] {UserHandle.getUserId(packageUid)});
14309    }
14310
14311    @Override
14312    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14313        if (!sUserManager.exists(userId)) return;
14314        final int uid = Binder.getCallingUid();
14315        final int permission = mContext.checkCallingOrSelfPermission(
14316                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14317        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14318        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14319        // writer
14320        synchronized (mPackages) {
14321            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14322                    allowedByPermission, uid, userId)) {
14323                scheduleWritePackageRestrictionsLocked(userId);
14324            }
14325        }
14326    }
14327
14328    @Override
14329    public String getInstallerPackageName(String packageName) {
14330        // reader
14331        synchronized (mPackages) {
14332            return mSettings.getInstallerPackageNameLPr(packageName);
14333        }
14334    }
14335
14336    @Override
14337    public int getApplicationEnabledSetting(String packageName, int userId) {
14338        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14339        int uid = Binder.getCallingUid();
14340        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14341        // reader
14342        synchronized (mPackages) {
14343            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14344        }
14345    }
14346
14347    @Override
14348    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14349        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14350        int uid = Binder.getCallingUid();
14351        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14352        // reader
14353        synchronized (mPackages) {
14354            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14355        }
14356    }
14357
14358    @Override
14359    public void enterSafeMode() {
14360        enforceSystemOrRoot("Only the system can request entering safe mode");
14361
14362        if (!mSystemReady) {
14363            mSafeMode = true;
14364        }
14365    }
14366
14367    @Override
14368    public void systemReady() {
14369        mSystemReady = true;
14370
14371        // Read the compatibilty setting when the system is ready.
14372        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14373                mContext.getContentResolver(),
14374                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14375        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14376        if (DEBUG_SETTINGS) {
14377            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14378        }
14379
14380        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14381
14382        synchronized (mPackages) {
14383            // Verify that all of the preferred activity components actually
14384            // exist.  It is possible for applications to be updated and at
14385            // that point remove a previously declared activity component that
14386            // had been set as a preferred activity.  We try to clean this up
14387            // the next time we encounter that preferred activity, but it is
14388            // possible for the user flow to never be able to return to that
14389            // situation so here we do a sanity check to make sure we haven't
14390            // left any junk around.
14391            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14392            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14393                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14394                removed.clear();
14395                for (PreferredActivity pa : pir.filterSet()) {
14396                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14397                        removed.add(pa);
14398                    }
14399                }
14400                if (removed.size() > 0) {
14401                    for (int r=0; r<removed.size(); r++) {
14402                        PreferredActivity pa = removed.get(r);
14403                        Slog.w(TAG, "Removing dangling preferred activity: "
14404                                + pa.mPref.mComponent);
14405                        pir.removeFilter(pa);
14406                    }
14407                    mSettings.writePackageRestrictionsLPr(
14408                            mSettings.mPreferredActivities.keyAt(i));
14409                }
14410            }
14411
14412            for (int userId : UserManagerService.getInstance().getUserIds()) {
14413                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14414                    grantPermissionsUserIds = ArrayUtils.appendInt(
14415                            grantPermissionsUserIds, userId);
14416                }
14417            }
14418        }
14419        sUserManager.systemReady();
14420
14421        // If we upgraded grant all default permissions before kicking off.
14422        for (int userId : grantPermissionsUserIds) {
14423            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14424        }
14425
14426        // Kick off any messages waiting for system ready
14427        if (mPostSystemReadyMessages != null) {
14428            for (Message msg : mPostSystemReadyMessages) {
14429                msg.sendToTarget();
14430            }
14431            mPostSystemReadyMessages = null;
14432        }
14433
14434        // Watch for external volumes that come and go over time
14435        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14436        storage.registerListener(mStorageListener);
14437
14438        mInstallerService.systemReady();
14439        mPackageDexOptimizer.systemReady();
14440    }
14441
14442    @Override
14443    public boolean isSafeMode() {
14444        return mSafeMode;
14445    }
14446
14447    @Override
14448    public boolean hasSystemUidErrors() {
14449        return mHasSystemUidErrors;
14450    }
14451
14452    static String arrayToString(int[] array) {
14453        StringBuffer buf = new StringBuffer(128);
14454        buf.append('[');
14455        if (array != null) {
14456            for (int i=0; i<array.length; i++) {
14457                if (i > 0) buf.append(", ");
14458                buf.append(array[i]);
14459            }
14460        }
14461        buf.append(']');
14462        return buf.toString();
14463    }
14464
14465    static class DumpState {
14466        public static final int DUMP_LIBS = 1 << 0;
14467        public static final int DUMP_FEATURES = 1 << 1;
14468        public static final int DUMP_RESOLVERS = 1 << 2;
14469        public static final int DUMP_PERMISSIONS = 1 << 3;
14470        public static final int DUMP_PACKAGES = 1 << 4;
14471        public static final int DUMP_SHARED_USERS = 1 << 5;
14472        public static final int DUMP_MESSAGES = 1 << 6;
14473        public static final int DUMP_PROVIDERS = 1 << 7;
14474        public static final int DUMP_VERIFIERS = 1 << 8;
14475        public static final int DUMP_PREFERRED = 1 << 9;
14476        public static final int DUMP_PREFERRED_XML = 1 << 10;
14477        public static final int DUMP_KEYSETS = 1 << 11;
14478        public static final int DUMP_VERSION = 1 << 12;
14479        public static final int DUMP_INSTALLS = 1 << 13;
14480        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14481        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14482
14483        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14484
14485        private int mTypes;
14486
14487        private int mOptions;
14488
14489        private boolean mTitlePrinted;
14490
14491        private SharedUserSetting mSharedUser;
14492
14493        public boolean isDumping(int type) {
14494            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14495                return true;
14496            }
14497
14498            return (mTypes & type) != 0;
14499        }
14500
14501        public void setDump(int type) {
14502            mTypes |= type;
14503        }
14504
14505        public boolean isOptionEnabled(int option) {
14506            return (mOptions & option) != 0;
14507        }
14508
14509        public void setOptionEnabled(int option) {
14510            mOptions |= option;
14511        }
14512
14513        public boolean onTitlePrinted() {
14514            final boolean printed = mTitlePrinted;
14515            mTitlePrinted = true;
14516            return printed;
14517        }
14518
14519        public boolean getTitlePrinted() {
14520            return mTitlePrinted;
14521        }
14522
14523        public void setTitlePrinted(boolean enabled) {
14524            mTitlePrinted = enabled;
14525        }
14526
14527        public SharedUserSetting getSharedUser() {
14528            return mSharedUser;
14529        }
14530
14531        public void setSharedUser(SharedUserSetting user) {
14532            mSharedUser = user;
14533        }
14534    }
14535
14536    @Override
14537    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14538        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14539                != PackageManager.PERMISSION_GRANTED) {
14540            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14541                    + Binder.getCallingPid()
14542                    + ", uid=" + Binder.getCallingUid()
14543                    + " without permission "
14544                    + android.Manifest.permission.DUMP);
14545            return;
14546        }
14547
14548        DumpState dumpState = new DumpState();
14549        boolean fullPreferred = false;
14550        boolean checkin = false;
14551
14552        String packageName = null;
14553        ArraySet<String> permissionNames = null;
14554
14555        int opti = 0;
14556        while (opti < args.length) {
14557            String opt = args[opti];
14558            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14559                break;
14560            }
14561            opti++;
14562
14563            if ("-a".equals(opt)) {
14564                // Right now we only know how to print all.
14565            } else if ("-h".equals(opt)) {
14566                pw.println("Package manager dump options:");
14567                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14568                pw.println("    --checkin: dump for a checkin");
14569                pw.println("    -f: print details of intent filters");
14570                pw.println("    -h: print this help");
14571                pw.println("  cmd may be one of:");
14572                pw.println("    l[ibraries]: list known shared libraries");
14573                pw.println("    f[ibraries]: list device features");
14574                pw.println("    k[eysets]: print known keysets");
14575                pw.println("    r[esolvers]: dump intent resolvers");
14576                pw.println("    perm[issions]: dump permissions");
14577                pw.println("    permission [name ...]: dump declaration and use of given permission");
14578                pw.println("    pref[erred]: print preferred package settings");
14579                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14580                pw.println("    prov[iders]: dump content providers");
14581                pw.println("    p[ackages]: dump installed packages");
14582                pw.println("    s[hared-users]: dump shared user IDs");
14583                pw.println("    m[essages]: print collected runtime messages");
14584                pw.println("    v[erifiers]: print package verifier info");
14585                pw.println("    version: print database version info");
14586                pw.println("    write: write current settings now");
14587                pw.println("    <package.name>: info about given package");
14588                pw.println("    installs: details about install sessions");
14589                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14590                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14591                return;
14592            } else if ("--checkin".equals(opt)) {
14593                checkin = true;
14594            } else if ("-f".equals(opt)) {
14595                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14596            } else {
14597                pw.println("Unknown argument: " + opt + "; use -h for help");
14598            }
14599        }
14600
14601        // Is the caller requesting to dump a particular piece of data?
14602        if (opti < args.length) {
14603            String cmd = args[opti];
14604            opti++;
14605            // Is this a package name?
14606            if ("android".equals(cmd) || cmd.contains(".")) {
14607                packageName = cmd;
14608                // When dumping a single package, we always dump all of its
14609                // filter information since the amount of data will be reasonable.
14610                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14611            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14612                dumpState.setDump(DumpState.DUMP_LIBS);
14613            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14614                dumpState.setDump(DumpState.DUMP_FEATURES);
14615            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14616                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14617            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14618                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14619            } else if ("permission".equals(cmd)) {
14620                if (opti >= args.length) {
14621                    pw.println("Error: permission requires permission name");
14622                    return;
14623                }
14624                permissionNames = new ArraySet<>();
14625                while (opti < args.length) {
14626                    permissionNames.add(args[opti]);
14627                    opti++;
14628                }
14629                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14630                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14631            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14632                dumpState.setDump(DumpState.DUMP_PREFERRED);
14633            } else if ("preferred-xml".equals(cmd)) {
14634                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14635                if (opti < args.length && "--full".equals(args[opti])) {
14636                    fullPreferred = true;
14637                    opti++;
14638                }
14639            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14640                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14641            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14642                dumpState.setDump(DumpState.DUMP_PACKAGES);
14643            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14644                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14645            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14646                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14647            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14648                dumpState.setDump(DumpState.DUMP_MESSAGES);
14649            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14650                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14651            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14652                    || "intent-filter-verifiers".equals(cmd)) {
14653                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14654            } else if ("version".equals(cmd)) {
14655                dumpState.setDump(DumpState.DUMP_VERSION);
14656            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14657                dumpState.setDump(DumpState.DUMP_KEYSETS);
14658            } else if ("installs".equals(cmd)) {
14659                dumpState.setDump(DumpState.DUMP_INSTALLS);
14660            } else if ("write".equals(cmd)) {
14661                synchronized (mPackages) {
14662                    mSettings.writeLPr();
14663                    pw.println("Settings written.");
14664                    return;
14665                }
14666            }
14667        }
14668
14669        if (checkin) {
14670            pw.println("vers,1");
14671        }
14672
14673        // reader
14674        synchronized (mPackages) {
14675            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14676                if (!checkin) {
14677                    if (dumpState.onTitlePrinted())
14678                        pw.println();
14679                    pw.println("Database versions:");
14680                    pw.print("  SDK Version:");
14681                    pw.print(" internal=");
14682                    pw.print(mSettings.mInternalSdkPlatform);
14683                    pw.print(" external=");
14684                    pw.println(mSettings.mExternalSdkPlatform);
14685                    pw.print("  DB Version:");
14686                    pw.print(" internal=");
14687                    pw.print(mSettings.mInternalDatabaseVersion);
14688                    pw.print(" external=");
14689                    pw.println(mSettings.mExternalDatabaseVersion);
14690                }
14691            }
14692
14693            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14694                if (!checkin) {
14695                    if (dumpState.onTitlePrinted())
14696                        pw.println();
14697                    pw.println("Verifiers:");
14698                    pw.print("  Required: ");
14699                    pw.print(mRequiredVerifierPackage);
14700                    pw.print(" (uid=");
14701                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14702                    pw.println(")");
14703                } else if (mRequiredVerifierPackage != null) {
14704                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14705                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14706                }
14707            }
14708
14709            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14710                    packageName == null) {
14711                if (mIntentFilterVerifierComponent != null) {
14712                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14713                    if (!checkin) {
14714                        if (dumpState.onTitlePrinted())
14715                            pw.println();
14716                        pw.println("Intent Filter Verifier:");
14717                        pw.print("  Using: ");
14718                        pw.print(verifierPackageName);
14719                        pw.print(" (uid=");
14720                        pw.print(getPackageUid(verifierPackageName, 0));
14721                        pw.println(")");
14722                    } else if (verifierPackageName != null) {
14723                        pw.print("ifv,"); pw.print(verifierPackageName);
14724                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14725                    }
14726                } else {
14727                    pw.println();
14728                    pw.println("No Intent Filter Verifier available!");
14729                }
14730            }
14731
14732            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14733                boolean printedHeader = false;
14734                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14735                while (it.hasNext()) {
14736                    String name = it.next();
14737                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14738                    if (!checkin) {
14739                        if (!printedHeader) {
14740                            if (dumpState.onTitlePrinted())
14741                                pw.println();
14742                            pw.println("Libraries:");
14743                            printedHeader = true;
14744                        }
14745                        pw.print("  ");
14746                    } else {
14747                        pw.print("lib,");
14748                    }
14749                    pw.print(name);
14750                    if (!checkin) {
14751                        pw.print(" -> ");
14752                    }
14753                    if (ent.path != null) {
14754                        if (!checkin) {
14755                            pw.print("(jar) ");
14756                            pw.print(ent.path);
14757                        } else {
14758                            pw.print(",jar,");
14759                            pw.print(ent.path);
14760                        }
14761                    } else {
14762                        if (!checkin) {
14763                            pw.print("(apk) ");
14764                            pw.print(ent.apk);
14765                        } else {
14766                            pw.print(",apk,");
14767                            pw.print(ent.apk);
14768                        }
14769                    }
14770                    pw.println();
14771                }
14772            }
14773
14774            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14775                if (dumpState.onTitlePrinted())
14776                    pw.println();
14777                if (!checkin) {
14778                    pw.println("Features:");
14779                }
14780                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14781                while (it.hasNext()) {
14782                    String name = it.next();
14783                    if (!checkin) {
14784                        pw.print("  ");
14785                    } else {
14786                        pw.print("feat,");
14787                    }
14788                    pw.println(name);
14789                }
14790            }
14791
14792            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14793                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14794                        : "Activity Resolver Table:", "  ", packageName,
14795                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14796                    dumpState.setTitlePrinted(true);
14797                }
14798                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14799                        : "Receiver Resolver Table:", "  ", packageName,
14800                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14801                    dumpState.setTitlePrinted(true);
14802                }
14803                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14804                        : "Service Resolver Table:", "  ", packageName,
14805                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14806                    dumpState.setTitlePrinted(true);
14807                }
14808                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14809                        : "Provider Resolver Table:", "  ", packageName,
14810                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14811                    dumpState.setTitlePrinted(true);
14812                }
14813            }
14814
14815            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14816                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14817                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14818                    int user = mSettings.mPreferredActivities.keyAt(i);
14819                    if (pir.dump(pw,
14820                            dumpState.getTitlePrinted()
14821                                ? "\nPreferred Activities User " + user + ":"
14822                                : "Preferred Activities User " + user + ":", "  ",
14823                            packageName, true, false)) {
14824                        dumpState.setTitlePrinted(true);
14825                    }
14826                }
14827            }
14828
14829            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14830                pw.flush();
14831                FileOutputStream fout = new FileOutputStream(fd);
14832                BufferedOutputStream str = new BufferedOutputStream(fout);
14833                XmlSerializer serializer = new FastXmlSerializer();
14834                try {
14835                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14836                    serializer.startDocument(null, true);
14837                    serializer.setFeature(
14838                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14839                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14840                    serializer.endDocument();
14841                    serializer.flush();
14842                } catch (IllegalArgumentException e) {
14843                    pw.println("Failed writing: " + e);
14844                } catch (IllegalStateException e) {
14845                    pw.println("Failed writing: " + e);
14846                } catch (IOException e) {
14847                    pw.println("Failed writing: " + e);
14848                }
14849            }
14850
14851            if (!checkin
14852                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14853                    && packageName == null) {
14854                pw.println();
14855                int count = mSettings.mPackages.size();
14856                if (count == 0) {
14857                    pw.println("No applications!");
14858                    pw.println();
14859                } else {
14860                    final String prefix = "  ";
14861                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14862                    if (allPackageSettings.size() == 0) {
14863                        pw.println("No domain preferred apps!");
14864                        pw.println();
14865                    } else {
14866                        pw.println("App verification status:");
14867                        pw.println();
14868                        count = 0;
14869                        for (PackageSetting ps : allPackageSettings) {
14870                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14871                            if (ivi == null || ivi.getPackageName() == null) continue;
14872                            pw.println(prefix + "Package: " + ivi.getPackageName());
14873                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14874                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14875                            pw.println();
14876                            count++;
14877                        }
14878                        if (count == 0) {
14879                            pw.println(prefix + "No app verification established.");
14880                            pw.println();
14881                        }
14882                        for (int userId : sUserManager.getUserIds()) {
14883                            pw.println("App linkages for user " + userId + ":");
14884                            pw.println();
14885                            count = 0;
14886                            for (PackageSetting ps : allPackageSettings) {
14887                                final int status = ps.getDomainVerificationStatusForUser(userId);
14888                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14889                                    continue;
14890                                }
14891                                pw.println(prefix + "Package: " + ps.name);
14892                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14893                                String statusStr = IntentFilterVerificationInfo.
14894                                        getStatusStringFromValue(status);
14895                                pw.println(prefix + "Status:  " + statusStr);
14896                                pw.println();
14897                                count++;
14898                            }
14899                            if (count == 0) {
14900                                pw.println(prefix + "No configured app linkages.");
14901                                pw.println();
14902                            }
14903                        }
14904                    }
14905                }
14906            }
14907
14908            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14909                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14910                if (packageName == null && permissionNames == null) {
14911                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14912                        if (iperm == 0) {
14913                            if (dumpState.onTitlePrinted())
14914                                pw.println();
14915                            pw.println("AppOp Permissions:");
14916                        }
14917                        pw.print("  AppOp Permission ");
14918                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14919                        pw.println(":");
14920                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14921                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14922                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14923                        }
14924                    }
14925                }
14926            }
14927
14928            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14929                boolean printedSomething = false;
14930                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14931                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14932                        continue;
14933                    }
14934                    if (!printedSomething) {
14935                        if (dumpState.onTitlePrinted())
14936                            pw.println();
14937                        pw.println("Registered ContentProviders:");
14938                        printedSomething = true;
14939                    }
14940                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14941                    pw.print("    "); pw.println(p.toString());
14942                }
14943                printedSomething = false;
14944                for (Map.Entry<String, PackageParser.Provider> entry :
14945                        mProvidersByAuthority.entrySet()) {
14946                    PackageParser.Provider p = entry.getValue();
14947                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14948                        continue;
14949                    }
14950                    if (!printedSomething) {
14951                        if (dumpState.onTitlePrinted())
14952                            pw.println();
14953                        pw.println("ContentProvider Authorities:");
14954                        printedSomething = true;
14955                    }
14956                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14957                    pw.print("    "); pw.println(p.toString());
14958                    if (p.info != null && p.info.applicationInfo != null) {
14959                        final String appInfo = p.info.applicationInfo.toString();
14960                        pw.print("      applicationInfo="); pw.println(appInfo);
14961                    }
14962                }
14963            }
14964
14965            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14966                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14967            }
14968
14969            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14970                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14971            }
14972
14973            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14974                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14975            }
14976
14977            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14978                // XXX should handle packageName != null by dumping only install data that
14979                // the given package is involved with.
14980                if (dumpState.onTitlePrinted()) pw.println();
14981                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14982            }
14983
14984            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14985                if (dumpState.onTitlePrinted()) pw.println();
14986                mSettings.dumpReadMessagesLPr(pw, dumpState);
14987
14988                pw.println();
14989                pw.println("Package warning messages:");
14990                BufferedReader in = null;
14991                String line = null;
14992                try {
14993                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14994                    while ((line = in.readLine()) != null) {
14995                        if (line.contains("ignored: updated version")) continue;
14996                        pw.println(line);
14997                    }
14998                } catch (IOException ignored) {
14999                } finally {
15000                    IoUtils.closeQuietly(in);
15001                }
15002            }
15003
15004            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15005                BufferedReader in = null;
15006                String line = null;
15007                try {
15008                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15009                    while ((line = in.readLine()) != null) {
15010                        if (line.contains("ignored: updated version")) continue;
15011                        pw.print("msg,");
15012                        pw.println(line);
15013                    }
15014                } catch (IOException ignored) {
15015                } finally {
15016                    IoUtils.closeQuietly(in);
15017                }
15018            }
15019        }
15020    }
15021
15022    private String dumpDomainString(String packageName) {
15023        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15024        List<IntentFilter> filters = getAllIntentFilters(packageName);
15025
15026        ArraySet<String> result = new ArraySet<>();
15027        if (iviList.size() > 0) {
15028            for (IntentFilterVerificationInfo ivi : iviList) {
15029                for (String host : ivi.getDomains()) {
15030                    result.add(host);
15031                }
15032            }
15033        }
15034        if (filters != null && filters.size() > 0) {
15035            for (IntentFilter filter : filters) {
15036                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15037                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15038                    result.addAll(filter.getHostsList());
15039                }
15040            }
15041        }
15042
15043        StringBuilder sb = new StringBuilder(result.size() * 16);
15044        for (String domain : result) {
15045            if (sb.length() > 0) sb.append(" ");
15046            sb.append(domain);
15047        }
15048        return sb.toString();
15049    }
15050
15051    // ------- apps on sdcard specific code -------
15052    static final boolean DEBUG_SD_INSTALL = false;
15053
15054    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15055
15056    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15057
15058    private boolean mMediaMounted = false;
15059
15060    static String getEncryptKey() {
15061        try {
15062            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15063                    SD_ENCRYPTION_KEYSTORE_NAME);
15064            if (sdEncKey == null) {
15065                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15066                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15067                if (sdEncKey == null) {
15068                    Slog.e(TAG, "Failed to create encryption keys");
15069                    return null;
15070                }
15071            }
15072            return sdEncKey;
15073        } catch (NoSuchAlgorithmException nsae) {
15074            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15075            return null;
15076        } catch (IOException ioe) {
15077            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15078            return null;
15079        }
15080    }
15081
15082    /*
15083     * Update media status on PackageManager.
15084     */
15085    @Override
15086    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15087        int callingUid = Binder.getCallingUid();
15088        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15089            throw new SecurityException("Media status can only be updated by the system");
15090        }
15091        // reader; this apparently protects mMediaMounted, but should probably
15092        // be a different lock in that case.
15093        synchronized (mPackages) {
15094            Log.i(TAG, "Updating external media status from "
15095                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15096                    + (mediaStatus ? "mounted" : "unmounted"));
15097            if (DEBUG_SD_INSTALL)
15098                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15099                        + ", mMediaMounted=" + mMediaMounted);
15100            if (mediaStatus == mMediaMounted) {
15101                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15102                        : 0, -1);
15103                mHandler.sendMessage(msg);
15104                return;
15105            }
15106            mMediaMounted = mediaStatus;
15107        }
15108        // Queue up an async operation since the package installation may take a
15109        // little while.
15110        mHandler.post(new Runnable() {
15111            public void run() {
15112                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15113            }
15114        });
15115    }
15116
15117    /**
15118     * Called by MountService when the initial ASECs to scan are available.
15119     * Should block until all the ASEC containers are finished being scanned.
15120     */
15121    public void scanAvailableAsecs() {
15122        updateExternalMediaStatusInner(true, false, false);
15123        if (mShouldRestoreconData) {
15124            SELinuxMMAC.setRestoreconDone();
15125            mShouldRestoreconData = false;
15126        }
15127    }
15128
15129    /*
15130     * Collect information of applications on external media, map them against
15131     * existing containers and update information based on current mount status.
15132     * Please note that we always have to report status if reportStatus has been
15133     * set to true especially when unloading packages.
15134     */
15135    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15136            boolean externalStorage) {
15137        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15138        int[] uidArr = EmptyArray.INT;
15139
15140        final String[] list = PackageHelper.getSecureContainerList();
15141        if (ArrayUtils.isEmpty(list)) {
15142            Log.i(TAG, "No secure containers found");
15143        } else {
15144            // Process list of secure containers and categorize them
15145            // as active or stale based on their package internal state.
15146
15147            // reader
15148            synchronized (mPackages) {
15149                for (String cid : list) {
15150                    // Leave stages untouched for now; installer service owns them
15151                    if (PackageInstallerService.isStageName(cid)) continue;
15152
15153                    if (DEBUG_SD_INSTALL)
15154                        Log.i(TAG, "Processing container " + cid);
15155                    String pkgName = getAsecPackageName(cid);
15156                    if (pkgName == null) {
15157                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15158                        continue;
15159                    }
15160                    if (DEBUG_SD_INSTALL)
15161                        Log.i(TAG, "Looking for pkg : " + pkgName);
15162
15163                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15164                    if (ps == null) {
15165                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15166                        continue;
15167                    }
15168
15169                    /*
15170                     * Skip packages that are not external if we're unmounting
15171                     * external storage.
15172                     */
15173                    if (externalStorage && !isMounted && !isExternal(ps)) {
15174                        continue;
15175                    }
15176
15177                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15178                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15179                    // The package status is changed only if the code path
15180                    // matches between settings and the container id.
15181                    if (ps.codePathString != null
15182                            && ps.codePathString.startsWith(args.getCodePath())) {
15183                        if (DEBUG_SD_INSTALL) {
15184                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15185                                    + " at code path: " + ps.codePathString);
15186                        }
15187
15188                        // We do have a valid package installed on sdcard
15189                        processCids.put(args, ps.codePathString);
15190                        final int uid = ps.appId;
15191                        if (uid != -1) {
15192                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15193                        }
15194                    } else {
15195                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15196                                + ps.codePathString);
15197                    }
15198                }
15199            }
15200
15201            Arrays.sort(uidArr);
15202        }
15203
15204        // Process packages with valid entries.
15205        if (isMounted) {
15206            if (DEBUG_SD_INSTALL)
15207                Log.i(TAG, "Loading packages");
15208            loadMediaPackages(processCids, uidArr);
15209            startCleaningPackages();
15210            mInstallerService.onSecureContainersAvailable();
15211        } else {
15212            if (DEBUG_SD_INSTALL)
15213                Log.i(TAG, "Unloading packages");
15214            unloadMediaPackages(processCids, uidArr, reportStatus);
15215        }
15216    }
15217
15218    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15219            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15220        final int size = infos.size();
15221        final String[] packageNames = new String[size];
15222        final int[] packageUids = new int[size];
15223        for (int i = 0; i < size; i++) {
15224            final ApplicationInfo info = infos.get(i);
15225            packageNames[i] = info.packageName;
15226            packageUids[i] = info.uid;
15227        }
15228        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15229                finishedReceiver);
15230    }
15231
15232    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15233            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15234        sendResourcesChangedBroadcast(mediaStatus, replacing,
15235                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15236    }
15237
15238    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15239            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15240        int size = pkgList.length;
15241        if (size > 0) {
15242            // Send broadcasts here
15243            Bundle extras = new Bundle();
15244            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15245            if (uidArr != null) {
15246                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15247            }
15248            if (replacing) {
15249                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15250            }
15251            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15252                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15253            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15254        }
15255    }
15256
15257   /*
15258     * Look at potentially valid container ids from processCids If package
15259     * information doesn't match the one on record or package scanning fails,
15260     * the cid is added to list of removeCids. We currently don't delete stale
15261     * containers.
15262     */
15263    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15264        ArrayList<String> pkgList = new ArrayList<String>();
15265        Set<AsecInstallArgs> keys = processCids.keySet();
15266
15267        for (AsecInstallArgs args : keys) {
15268            String codePath = processCids.get(args);
15269            if (DEBUG_SD_INSTALL)
15270                Log.i(TAG, "Loading container : " + args.cid);
15271            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15272            try {
15273                // Make sure there are no container errors first.
15274                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15275                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15276                            + " when installing from sdcard");
15277                    continue;
15278                }
15279                // Check code path here.
15280                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15281                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15282                            + " does not match one in settings " + codePath);
15283                    continue;
15284                }
15285                // Parse package
15286                int parseFlags = mDefParseFlags;
15287                if (args.isExternalAsec()) {
15288                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15289                }
15290                if (args.isFwdLocked()) {
15291                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15292                }
15293
15294                synchronized (mInstallLock) {
15295                    PackageParser.Package pkg = null;
15296                    try {
15297                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15298                    } catch (PackageManagerException e) {
15299                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15300                    }
15301                    // Scan the package
15302                    if (pkg != null) {
15303                        /*
15304                         * TODO why is the lock being held? doPostInstall is
15305                         * called in other places without the lock. This needs
15306                         * to be straightened out.
15307                         */
15308                        // writer
15309                        synchronized (mPackages) {
15310                            retCode = PackageManager.INSTALL_SUCCEEDED;
15311                            pkgList.add(pkg.packageName);
15312                            // Post process args
15313                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15314                                    pkg.applicationInfo.uid);
15315                        }
15316                    } else {
15317                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15318                    }
15319                }
15320
15321            } finally {
15322                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15323                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15324                }
15325            }
15326        }
15327        // writer
15328        synchronized (mPackages) {
15329            // If the platform SDK has changed since the last time we booted,
15330            // we need to re-grant app permission to catch any new ones that
15331            // appear. This is really a hack, and means that apps can in some
15332            // cases get permissions that the user didn't initially explicitly
15333            // allow... it would be nice to have some better way to handle
15334            // this situation.
15335            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15336            if (regrantPermissions)
15337                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15338                        + mSdkVersion + "; regranting permissions for external storage");
15339            mSettings.mExternalSdkPlatform = mSdkVersion;
15340
15341            // Make sure group IDs have been assigned, and any permission
15342            // changes in other apps are accounted for
15343            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15344                    | (regrantPermissions
15345                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15346                            : 0));
15347
15348            mSettings.updateExternalDatabaseVersion();
15349
15350            // can downgrade to reader
15351            // Persist settings
15352            mSettings.writeLPr();
15353        }
15354        // Send a broadcast to let everyone know we are done processing
15355        if (pkgList.size() > 0) {
15356            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15357        }
15358    }
15359
15360   /*
15361     * Utility method to unload a list of specified containers
15362     */
15363    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15364        // Just unmount all valid containers.
15365        for (AsecInstallArgs arg : cidArgs) {
15366            synchronized (mInstallLock) {
15367                arg.doPostDeleteLI(false);
15368           }
15369       }
15370   }
15371
15372    /*
15373     * Unload packages mounted on external media. This involves deleting package
15374     * data from internal structures, sending broadcasts about diabled packages,
15375     * gc'ing to free up references, unmounting all secure containers
15376     * corresponding to packages on external media, and posting a
15377     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15378     * that we always have to post this message if status has been requested no
15379     * matter what.
15380     */
15381    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15382            final boolean reportStatus) {
15383        if (DEBUG_SD_INSTALL)
15384            Log.i(TAG, "unloading media packages");
15385        ArrayList<String> pkgList = new ArrayList<String>();
15386        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15387        final Set<AsecInstallArgs> keys = processCids.keySet();
15388        for (AsecInstallArgs args : keys) {
15389            String pkgName = args.getPackageName();
15390            if (DEBUG_SD_INSTALL)
15391                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15392            // Delete package internally
15393            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15394            synchronized (mInstallLock) {
15395                boolean res = deletePackageLI(pkgName, null, false, null, null,
15396                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15397                if (res) {
15398                    pkgList.add(pkgName);
15399                } else {
15400                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15401                    failedList.add(args);
15402                }
15403            }
15404        }
15405
15406        // reader
15407        synchronized (mPackages) {
15408            // We didn't update the settings after removing each package;
15409            // write them now for all packages.
15410            mSettings.writeLPr();
15411        }
15412
15413        // We have to absolutely send UPDATED_MEDIA_STATUS only
15414        // after confirming that all the receivers processed the ordered
15415        // broadcast when packages get disabled, force a gc to clean things up.
15416        // and unload all the containers.
15417        if (pkgList.size() > 0) {
15418            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15419                    new IIntentReceiver.Stub() {
15420                public void performReceive(Intent intent, int resultCode, String data,
15421                        Bundle extras, boolean ordered, boolean sticky,
15422                        int sendingUser) throws RemoteException {
15423                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15424                            reportStatus ? 1 : 0, 1, keys);
15425                    mHandler.sendMessage(msg);
15426                }
15427            });
15428        } else {
15429            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15430                    keys);
15431            mHandler.sendMessage(msg);
15432        }
15433    }
15434
15435    private void loadPrivatePackages(VolumeInfo vol) {
15436        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15437        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15438        synchronized (mInstallLock) {
15439        synchronized (mPackages) {
15440            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15441            for (PackageSetting ps : packages) {
15442                final PackageParser.Package pkg;
15443                try {
15444                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15445                    loaded.add(pkg.applicationInfo);
15446                } catch (PackageManagerException e) {
15447                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15448                }
15449            }
15450
15451            // TODO: regrant any permissions that changed based since original install
15452
15453            mSettings.writeLPr();
15454        }
15455        }
15456
15457        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15458        sendResourcesChangedBroadcast(true, false, loaded, null);
15459    }
15460
15461    private void unloadPrivatePackages(VolumeInfo vol) {
15462        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15463        synchronized (mInstallLock) {
15464        synchronized (mPackages) {
15465            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15466            for (PackageSetting ps : packages) {
15467                if (ps.pkg == null) continue;
15468
15469                final ApplicationInfo info = ps.pkg.applicationInfo;
15470                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15471                if (deletePackageLI(ps.name, null, false, null, null,
15472                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15473                    unloaded.add(info);
15474                } else {
15475                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15476                }
15477            }
15478
15479            mSettings.writeLPr();
15480        }
15481        }
15482
15483        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15484        sendResourcesChangedBroadcast(false, false, unloaded, null);
15485    }
15486
15487    /**
15488     * Examine all users present on given mounted volume, and destroy data
15489     * belonging to users that are no longer valid, or whose user ID has been
15490     * recycled.
15491     */
15492    private void reconcileUsers(String volumeUuid) {
15493        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15494        if (ArrayUtils.isEmpty(files)) {
15495            Slog.d(TAG, "No users found on " + volumeUuid);
15496            return;
15497        }
15498
15499        for (File file : files) {
15500            if (!file.isDirectory()) continue;
15501
15502            final int userId;
15503            final UserInfo info;
15504            try {
15505                userId = Integer.parseInt(file.getName());
15506                info = sUserManager.getUserInfo(userId);
15507            } catch (NumberFormatException e) {
15508                Slog.w(TAG, "Invalid user directory " + file);
15509                continue;
15510            }
15511
15512            boolean destroyUser = false;
15513            if (info == null) {
15514                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15515                        + " because no matching user was found");
15516                destroyUser = true;
15517            } else {
15518                try {
15519                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15520                } catch (IOException e) {
15521                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15522                            + " because we failed to enforce serial number: " + e);
15523                    destroyUser = true;
15524                }
15525            }
15526
15527            if (destroyUser) {
15528                synchronized (mInstallLock) {
15529                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15530                }
15531            }
15532        }
15533
15534        final UserManager um = mContext.getSystemService(UserManager.class);
15535        for (UserInfo user : um.getUsers()) {
15536            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15537            if (userDir.exists()) continue;
15538
15539            try {
15540                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15541                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15542            } catch (IOException e) {
15543                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15544            }
15545        }
15546    }
15547
15548    /**
15549     * Examine all apps present on given mounted volume, and destroy apps that
15550     * aren't expected, either due to uninstallation or reinstallation on
15551     * another volume.
15552     */
15553    private void reconcileApps(String volumeUuid) {
15554        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15555        if (ArrayUtils.isEmpty(files)) {
15556            Slog.d(TAG, "No apps found on " + volumeUuid);
15557            return;
15558        }
15559
15560        for (File file : files) {
15561            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15562                    && !PackageInstallerService.isStageName(file.getName());
15563            if (!isPackage) {
15564                // Ignore entries which are not packages
15565                continue;
15566            }
15567
15568            boolean destroyApp = false;
15569            String packageName = null;
15570            try {
15571                final PackageLite pkg = PackageParser.parsePackageLite(file,
15572                        PackageParser.PARSE_MUST_BE_APK);
15573                packageName = pkg.packageName;
15574
15575                synchronized (mPackages) {
15576                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15577                    if (ps == null) {
15578                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15579                                + volumeUuid + " because we found no install record");
15580                        destroyApp = true;
15581                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15582                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15583                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15584                        destroyApp = true;
15585                    }
15586                }
15587
15588            } catch (PackageParserException e) {
15589                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15590                destroyApp = true;
15591            }
15592
15593            if (destroyApp) {
15594                synchronized (mInstallLock) {
15595                    if (packageName != null) {
15596                        removeDataDirsLI(volumeUuid, packageName);
15597                    }
15598                    if (file.isDirectory()) {
15599                        mInstaller.rmPackageDir(file.getAbsolutePath());
15600                    } else {
15601                        file.delete();
15602                    }
15603                }
15604            }
15605        }
15606    }
15607
15608    private void unfreezePackage(String packageName) {
15609        synchronized (mPackages) {
15610            final PackageSetting ps = mSettings.mPackages.get(packageName);
15611            if (ps != null) {
15612                ps.frozen = false;
15613            }
15614        }
15615    }
15616
15617    @Override
15618    public int movePackage(final String packageName, final String volumeUuid) {
15619        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15620
15621        final int moveId = mNextMoveId.getAndIncrement();
15622        try {
15623            movePackageInternal(packageName, volumeUuid, moveId);
15624        } catch (PackageManagerException e) {
15625            Slog.w(TAG, "Failed to move " + packageName, e);
15626            mMoveCallbacks.notifyStatusChanged(moveId,
15627                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15628        }
15629        return moveId;
15630    }
15631
15632    private void movePackageInternal(final String packageName, final String volumeUuid,
15633            final int moveId) throws PackageManagerException {
15634        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15635        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15636        final PackageManager pm = mContext.getPackageManager();
15637
15638        final boolean currentAsec;
15639        final String currentVolumeUuid;
15640        final File codeFile;
15641        final String installerPackageName;
15642        final String packageAbiOverride;
15643        final int appId;
15644        final String seinfo;
15645        final String label;
15646
15647        // reader
15648        synchronized (mPackages) {
15649            final PackageParser.Package pkg = mPackages.get(packageName);
15650            final PackageSetting ps = mSettings.mPackages.get(packageName);
15651            if (pkg == null || ps == null) {
15652                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15653            }
15654
15655            if (pkg.applicationInfo.isSystemApp()) {
15656                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15657                        "Cannot move system application");
15658            }
15659
15660            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15661                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15662                        "Package already moved to " + volumeUuid);
15663            }
15664
15665            final File probe = new File(pkg.codePath);
15666            final File probeOat = new File(probe, "oat");
15667            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15668                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15669                        "Move only supported for modern cluster style installs");
15670            }
15671
15672            if (ps.frozen) {
15673                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15674                        "Failed to move already frozen package");
15675            }
15676            ps.frozen = true;
15677
15678            currentAsec = pkg.applicationInfo.isForwardLocked()
15679                    || pkg.applicationInfo.isExternalAsec();
15680            currentVolumeUuid = ps.volumeUuid;
15681            codeFile = new File(pkg.codePath);
15682            installerPackageName = ps.installerPackageName;
15683            packageAbiOverride = ps.cpuAbiOverrideString;
15684            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15685            seinfo = pkg.applicationInfo.seinfo;
15686            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15687        }
15688
15689        // Now that we're guarded by frozen state, kill app during move
15690        killApplication(packageName, appId, "move pkg");
15691
15692        final Bundle extras = new Bundle();
15693        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15694        extras.putString(Intent.EXTRA_TITLE, label);
15695        mMoveCallbacks.notifyCreated(moveId, extras);
15696
15697        int installFlags;
15698        final boolean moveCompleteApp;
15699        final File measurePath;
15700
15701        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15702            installFlags = INSTALL_INTERNAL;
15703            moveCompleteApp = !currentAsec;
15704            measurePath = Environment.getDataAppDirectory(volumeUuid);
15705        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15706            installFlags = INSTALL_EXTERNAL;
15707            moveCompleteApp = false;
15708            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15709        } else {
15710            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15711            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15712                    || !volume.isMountedWritable()) {
15713                unfreezePackage(packageName);
15714                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15715                        "Move location not mounted private volume");
15716            }
15717
15718            Preconditions.checkState(!currentAsec);
15719
15720            installFlags = INSTALL_INTERNAL;
15721            moveCompleteApp = true;
15722            measurePath = Environment.getDataAppDirectory(volumeUuid);
15723        }
15724
15725        final PackageStats stats = new PackageStats(null, -1);
15726        synchronized (mInstaller) {
15727            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15728                unfreezePackage(packageName);
15729                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15730                        "Failed to measure package size");
15731            }
15732        }
15733
15734        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15735                + stats.dataSize);
15736
15737        final long startFreeBytes = measurePath.getFreeSpace();
15738        final long sizeBytes;
15739        if (moveCompleteApp) {
15740            sizeBytes = stats.codeSize + stats.dataSize;
15741        } else {
15742            sizeBytes = stats.codeSize;
15743        }
15744
15745        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15746            unfreezePackage(packageName);
15747            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15748                    "Not enough free space to move");
15749        }
15750
15751        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15752
15753        final CountDownLatch installedLatch = new CountDownLatch(1);
15754        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15755            @Override
15756            public void onUserActionRequired(Intent intent) throws RemoteException {
15757                throw new IllegalStateException();
15758            }
15759
15760            @Override
15761            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15762                    Bundle extras) throws RemoteException {
15763                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15764                        + PackageManager.installStatusToString(returnCode, msg));
15765
15766                installedLatch.countDown();
15767
15768                // Regardless of success or failure of the move operation,
15769                // always unfreeze the package
15770                unfreezePackage(packageName);
15771
15772                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15773                switch (status) {
15774                    case PackageInstaller.STATUS_SUCCESS:
15775                        mMoveCallbacks.notifyStatusChanged(moveId,
15776                                PackageManager.MOVE_SUCCEEDED);
15777                        break;
15778                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15779                        mMoveCallbacks.notifyStatusChanged(moveId,
15780                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15781                        break;
15782                    default:
15783                        mMoveCallbacks.notifyStatusChanged(moveId,
15784                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15785                        break;
15786                }
15787            }
15788        };
15789
15790        final MoveInfo move;
15791        if (moveCompleteApp) {
15792            // Kick off a thread to report progress estimates
15793            new Thread() {
15794                @Override
15795                public void run() {
15796                    while (true) {
15797                        try {
15798                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15799                                break;
15800                            }
15801                        } catch (InterruptedException ignored) {
15802                        }
15803
15804                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15805                        final int progress = 10 + (int) MathUtils.constrain(
15806                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15807                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15808                    }
15809                }
15810            }.start();
15811
15812            final String dataAppName = codeFile.getName();
15813            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15814                    dataAppName, appId, seinfo);
15815        } else {
15816            move = null;
15817        }
15818
15819        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15820
15821        final Message msg = mHandler.obtainMessage(INIT_COPY);
15822        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15823        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15824                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15825        mHandler.sendMessage(msg);
15826    }
15827
15828    @Override
15829    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15831
15832        final int realMoveId = mNextMoveId.getAndIncrement();
15833        final Bundle extras = new Bundle();
15834        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15835        mMoveCallbacks.notifyCreated(realMoveId, extras);
15836
15837        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15838            @Override
15839            public void onCreated(int moveId, Bundle extras) {
15840                // Ignored
15841            }
15842
15843            @Override
15844            public void onStatusChanged(int moveId, int status, long estMillis) {
15845                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15846            }
15847        };
15848
15849        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15850        storage.setPrimaryStorageUuid(volumeUuid, callback);
15851        return realMoveId;
15852    }
15853
15854    @Override
15855    public int getMoveStatus(int moveId) {
15856        mContext.enforceCallingOrSelfPermission(
15857                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15858        return mMoveCallbacks.mLastStatus.get(moveId);
15859    }
15860
15861    @Override
15862    public void registerMoveCallback(IPackageMoveObserver callback) {
15863        mContext.enforceCallingOrSelfPermission(
15864                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15865        mMoveCallbacks.register(callback);
15866    }
15867
15868    @Override
15869    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15870        mContext.enforceCallingOrSelfPermission(
15871                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15872        mMoveCallbacks.unregister(callback);
15873    }
15874
15875    @Override
15876    public boolean setInstallLocation(int loc) {
15877        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15878                null);
15879        if (getInstallLocation() == loc) {
15880            return true;
15881        }
15882        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15883                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15884            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15885                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15886            return true;
15887        }
15888        return false;
15889   }
15890
15891    @Override
15892    public int getInstallLocation() {
15893        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15894                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15895                PackageHelper.APP_INSTALL_AUTO);
15896    }
15897
15898    /** Called by UserManagerService */
15899    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15900        mDirtyUsers.remove(userHandle);
15901        mSettings.removeUserLPw(userHandle);
15902        mPendingBroadcasts.remove(userHandle);
15903        if (mInstaller != null) {
15904            // Technically, we shouldn't be doing this with the package lock
15905            // held.  However, this is very rare, and there is already so much
15906            // other disk I/O going on, that we'll let it slide for now.
15907            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15908            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15909                final String volumeUuid = vol.getFsUuid();
15910                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15911                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15912            }
15913        }
15914        mUserNeedsBadging.delete(userHandle);
15915        removeUnusedPackagesLILPw(userManager, userHandle);
15916    }
15917
15918    /**
15919     * We're removing userHandle and would like to remove any downloaded packages
15920     * that are no longer in use by any other user.
15921     * @param userHandle the user being removed
15922     */
15923    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15924        final boolean DEBUG_CLEAN_APKS = false;
15925        int [] users = userManager.getUserIdsLPr();
15926        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15927        while (psit.hasNext()) {
15928            PackageSetting ps = psit.next();
15929            if (ps.pkg == null) {
15930                continue;
15931            }
15932            final String packageName = ps.pkg.packageName;
15933            // Skip over if system app
15934            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15935                continue;
15936            }
15937            if (DEBUG_CLEAN_APKS) {
15938                Slog.i(TAG, "Checking package " + packageName);
15939            }
15940            boolean keep = false;
15941            for (int i = 0; i < users.length; i++) {
15942                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15943                    keep = true;
15944                    if (DEBUG_CLEAN_APKS) {
15945                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15946                                + users[i]);
15947                    }
15948                    break;
15949                }
15950            }
15951            if (!keep) {
15952                if (DEBUG_CLEAN_APKS) {
15953                    Slog.i(TAG, "  Removing package " + packageName);
15954                }
15955                mHandler.post(new Runnable() {
15956                    public void run() {
15957                        deletePackageX(packageName, userHandle, 0);
15958                    } //end run
15959                });
15960            }
15961        }
15962    }
15963
15964    /** Called by UserManagerService */
15965    void createNewUserLILPw(int userHandle) {
15966        if (mInstaller != null) {
15967            mInstaller.createUserConfig(userHandle);
15968            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15969            applyFactoryDefaultBrowserLPw(userHandle);
15970            primeDomainVerificationsLPw(userHandle);
15971        }
15972    }
15973
15974    void newUserCreated(final int userHandle) {
15975        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15976    }
15977
15978    @Override
15979    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15980        mContext.enforceCallingOrSelfPermission(
15981                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15982                "Only package verification agents can read the verifier device identity");
15983
15984        synchronized (mPackages) {
15985            return mSettings.getVerifierDeviceIdentityLPw();
15986        }
15987    }
15988
15989    @Override
15990    public void setPermissionEnforced(String permission, boolean enforced) {
15991        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15992        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15993            synchronized (mPackages) {
15994                if (mSettings.mReadExternalStorageEnforced == null
15995                        || mSettings.mReadExternalStorageEnforced != enforced) {
15996                    mSettings.mReadExternalStorageEnforced = enforced;
15997                    mSettings.writeLPr();
15998                }
15999            }
16000            // kill any non-foreground processes so we restart them and
16001            // grant/revoke the GID.
16002            final IActivityManager am = ActivityManagerNative.getDefault();
16003            if (am != null) {
16004                final long token = Binder.clearCallingIdentity();
16005                try {
16006                    am.killProcessesBelowForeground("setPermissionEnforcement");
16007                } catch (RemoteException e) {
16008                } finally {
16009                    Binder.restoreCallingIdentity(token);
16010                }
16011            }
16012        } else {
16013            throw new IllegalArgumentException("No selective enforcement for " + permission);
16014        }
16015    }
16016
16017    @Override
16018    @Deprecated
16019    public boolean isPermissionEnforced(String permission) {
16020        return true;
16021    }
16022
16023    @Override
16024    public boolean isStorageLow() {
16025        final long token = Binder.clearCallingIdentity();
16026        try {
16027            final DeviceStorageMonitorInternal
16028                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16029            if (dsm != null) {
16030                return dsm.isMemoryLow();
16031            } else {
16032                return false;
16033            }
16034        } finally {
16035            Binder.restoreCallingIdentity(token);
16036        }
16037    }
16038
16039    @Override
16040    public IPackageInstaller getPackageInstaller() {
16041        return mInstallerService;
16042    }
16043
16044    private boolean userNeedsBadging(int userId) {
16045        int index = mUserNeedsBadging.indexOfKey(userId);
16046        if (index < 0) {
16047            final UserInfo userInfo;
16048            final long token = Binder.clearCallingIdentity();
16049            try {
16050                userInfo = sUserManager.getUserInfo(userId);
16051            } finally {
16052                Binder.restoreCallingIdentity(token);
16053            }
16054            final boolean b;
16055            if (userInfo != null && userInfo.isManagedProfile()) {
16056                b = true;
16057            } else {
16058                b = false;
16059            }
16060            mUserNeedsBadging.put(userId, b);
16061            return b;
16062        }
16063        return mUserNeedsBadging.valueAt(index);
16064    }
16065
16066    @Override
16067    public KeySet getKeySetByAlias(String packageName, String alias) {
16068        if (packageName == null || alias == null) {
16069            return null;
16070        }
16071        synchronized(mPackages) {
16072            final PackageParser.Package pkg = mPackages.get(packageName);
16073            if (pkg == null) {
16074                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16075                throw new IllegalArgumentException("Unknown package: " + packageName);
16076            }
16077            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16078            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16079        }
16080    }
16081
16082    @Override
16083    public KeySet getSigningKeySet(String packageName) {
16084        if (packageName == null) {
16085            return null;
16086        }
16087        synchronized(mPackages) {
16088            final PackageParser.Package pkg = mPackages.get(packageName);
16089            if (pkg == null) {
16090                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16091                throw new IllegalArgumentException("Unknown package: " + packageName);
16092            }
16093            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16094                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16095                throw new SecurityException("May not access signing KeySet of other apps.");
16096            }
16097            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16098            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16099        }
16100    }
16101
16102    @Override
16103    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16104        if (packageName == null || ks == null) {
16105            return false;
16106        }
16107        synchronized(mPackages) {
16108            final PackageParser.Package pkg = mPackages.get(packageName);
16109            if (pkg == null) {
16110                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16111                throw new IllegalArgumentException("Unknown package: " + packageName);
16112            }
16113            IBinder ksh = ks.getToken();
16114            if (ksh instanceof KeySetHandle) {
16115                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16116                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16117            }
16118            return false;
16119        }
16120    }
16121
16122    @Override
16123    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16124        if (packageName == null || ks == null) {
16125            return false;
16126        }
16127        synchronized(mPackages) {
16128            final PackageParser.Package pkg = mPackages.get(packageName);
16129            if (pkg == null) {
16130                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16131                throw new IllegalArgumentException("Unknown package: " + packageName);
16132            }
16133            IBinder ksh = ks.getToken();
16134            if (ksh instanceof KeySetHandle) {
16135                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16136                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16137            }
16138            return false;
16139        }
16140    }
16141
16142    public void getUsageStatsIfNoPackageUsageInfo() {
16143        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16144            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16145            if (usm == null) {
16146                throw new IllegalStateException("UsageStatsManager must be initialized");
16147            }
16148            long now = System.currentTimeMillis();
16149            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16150            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16151                String packageName = entry.getKey();
16152                PackageParser.Package pkg = mPackages.get(packageName);
16153                if (pkg == null) {
16154                    continue;
16155                }
16156                UsageStats usage = entry.getValue();
16157                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16158                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16159            }
16160        }
16161    }
16162
16163    /**
16164     * Check and throw if the given before/after packages would be considered a
16165     * downgrade.
16166     */
16167    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16168            throws PackageManagerException {
16169        if (after.versionCode < before.mVersionCode) {
16170            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16171                    "Update version code " + after.versionCode + " is older than current "
16172                    + before.mVersionCode);
16173        } else if (after.versionCode == before.mVersionCode) {
16174            if (after.baseRevisionCode < before.baseRevisionCode) {
16175                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16176                        "Update base revision code " + after.baseRevisionCode
16177                        + " is older than current " + before.baseRevisionCode);
16178            }
16179
16180            if (!ArrayUtils.isEmpty(after.splitNames)) {
16181                for (int i = 0; i < after.splitNames.length; i++) {
16182                    final String splitName = after.splitNames[i];
16183                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16184                    if (j != -1) {
16185                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16186                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16187                                    "Update split " + splitName + " revision code "
16188                                    + after.splitRevisionCodes[i] + " is older than current "
16189                                    + before.splitRevisionCodes[j]);
16190                        }
16191                    }
16192                }
16193            }
16194        }
16195    }
16196
16197    private static class MoveCallbacks extends Handler {
16198        private static final int MSG_CREATED = 1;
16199        private static final int MSG_STATUS_CHANGED = 2;
16200
16201        private final RemoteCallbackList<IPackageMoveObserver>
16202                mCallbacks = new RemoteCallbackList<>();
16203
16204        private final SparseIntArray mLastStatus = new SparseIntArray();
16205
16206        public MoveCallbacks(Looper looper) {
16207            super(looper);
16208        }
16209
16210        public void register(IPackageMoveObserver callback) {
16211            mCallbacks.register(callback);
16212        }
16213
16214        public void unregister(IPackageMoveObserver callback) {
16215            mCallbacks.unregister(callback);
16216        }
16217
16218        @Override
16219        public void handleMessage(Message msg) {
16220            final SomeArgs args = (SomeArgs) msg.obj;
16221            final int n = mCallbacks.beginBroadcast();
16222            for (int i = 0; i < n; i++) {
16223                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16224                try {
16225                    invokeCallback(callback, msg.what, args);
16226                } catch (RemoteException ignored) {
16227                }
16228            }
16229            mCallbacks.finishBroadcast();
16230            args.recycle();
16231        }
16232
16233        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16234                throws RemoteException {
16235            switch (what) {
16236                case MSG_CREATED: {
16237                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16238                    break;
16239                }
16240                case MSG_STATUS_CHANGED: {
16241                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16242                    break;
16243                }
16244            }
16245        }
16246
16247        private void notifyCreated(int moveId, Bundle extras) {
16248            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16249
16250            final SomeArgs args = SomeArgs.obtain();
16251            args.argi1 = moveId;
16252            args.arg2 = extras;
16253            obtainMessage(MSG_CREATED, args).sendToTarget();
16254        }
16255
16256        private void notifyStatusChanged(int moveId, int status) {
16257            notifyStatusChanged(moveId, status, -1);
16258        }
16259
16260        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16261            Slog.v(TAG, "Move " + moveId + " status " + status);
16262
16263            final SomeArgs args = SomeArgs.obtain();
16264            args.argi1 = moveId;
16265            args.argi2 = status;
16266            args.arg3 = estMillis;
16267            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16268
16269            synchronized (mLastStatus) {
16270                mLastStatus.put(moveId, status);
16271            }
16272        }
16273    }
16274
16275    private final class OnPermissionChangeListeners extends Handler {
16276        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16277
16278        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16279                new RemoteCallbackList<>();
16280
16281        public OnPermissionChangeListeners(Looper looper) {
16282            super(looper);
16283        }
16284
16285        @Override
16286        public void handleMessage(Message msg) {
16287            switch (msg.what) {
16288                case MSG_ON_PERMISSIONS_CHANGED: {
16289                    final int uid = msg.arg1;
16290                    handleOnPermissionsChanged(uid);
16291                } break;
16292            }
16293        }
16294
16295        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16296            mPermissionListeners.register(listener);
16297
16298        }
16299
16300        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16301            mPermissionListeners.unregister(listener);
16302        }
16303
16304        public void onPermissionsChanged(int uid) {
16305            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16306                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16307            }
16308        }
16309
16310        private void handleOnPermissionsChanged(int uid) {
16311            final int count = mPermissionListeners.beginBroadcast();
16312            try {
16313                for (int i = 0; i < count; i++) {
16314                    IOnPermissionsChangeListener callback = mPermissionListeners
16315                            .getBroadcastItem(i);
16316                    try {
16317                        callback.onPermissionsChanged(uid);
16318                    } catch (RemoteException e) {
16319                        Log.e(TAG, "Permission listener is dead", e);
16320                    }
16321                }
16322            } finally {
16323                mPermissionListeners.finishBroadcast();
16324            }
16325        }
16326    }
16327
16328    private class PackageManagerInternalImpl extends PackageManagerInternal {
16329        @Override
16330        public void setLocationPackagesProvider(PackagesProvider provider) {
16331            synchronized (mPackages) {
16332                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16333            }
16334        }
16335
16336        @Override
16337        public void setImePackagesProvider(PackagesProvider provider) {
16338            synchronized (mPackages) {
16339                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16340            }
16341        }
16342
16343        @Override
16344        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16345            synchronized (mPackages) {
16346                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16347            }
16348        }
16349
16350        @Override
16351        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16352            synchronized (mPackages) {
16353                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16354            }
16355        }
16356
16357        @Override
16358        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16359            synchronized (mPackages) {
16360                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16361            }
16362        }
16363
16364        @Override
16365        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16366            synchronized (mPackages) {
16367                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16368            }
16369        }
16370
16371        @Override
16372        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16373            synchronized (mPackages) {
16374                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16375                        packageName, userId);
16376            }
16377        }
16378
16379        @Override
16380        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16381            synchronized (mPackages) {
16382                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16383                        packageName, userId);
16384            }
16385        }
16386    }
16387
16388    @Override
16389    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16390        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16391        synchronized (mPackages) {
16392            final long identity = Binder.clearCallingIdentity();
16393            try {
16394                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16395                        packageNames, userId);
16396            } finally {
16397                Binder.restoreCallingIdentity(identity);
16398            }
16399        }
16400    }
16401
16402    private static void enforceSystemOrPhoneCaller(String tag) {
16403        int callingUid = Binder.getCallingUid();
16404        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16405            throw new SecurityException(
16406                    "Cannot call " + tag + " from UID " + callingUid);
16407        }
16408    }
16409}
16410