PackageManagerService.java revision 3ec12db0f5155be41d60694f0ac3c9284ff29002
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 *
275mmm frameworks/base/tests/AndroidTests
276adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
277adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
278 *
279 * {@hide}
280 */
281public class PackageManagerService extends IPackageManager.Stub {
282    static final String TAG = "PackageManager";
283    static final boolean DEBUG_SETTINGS = false;
284    static final boolean DEBUG_PREFERRED = false;
285    static final boolean DEBUG_UPGRADE = false;
286    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
287    private static final boolean DEBUG_BACKUP = true;
288    private static final boolean DEBUG_INSTALL = false;
289    private static final boolean DEBUG_REMOVE = false;
290    private static final boolean DEBUG_BROADCASTS = false;
291    private static final boolean DEBUG_SHOW_INFO = false;
292    private static final boolean DEBUG_PACKAGE_INFO = false;
293    private static final boolean DEBUG_INTENT_MATCHING = false;
294    private static final boolean DEBUG_PACKAGE_SCANNING = false;
295    private static final boolean DEBUG_VERIFY = false;
296    private static final boolean DEBUG_DEXOPT = false;
297    private static final boolean DEBUG_ABI_SELECTION = false;
298
299    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
300
301    private static final int RADIO_UID = Process.PHONE_UID;
302    private static final int LOG_UID = Process.LOG_UID;
303    private static final int NFC_UID = Process.NFC_UID;
304    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
305    private static final int SHELL_UID = Process.SHELL_UID;
306
307    // Cap the size of permission trees that 3rd party apps can define
308    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
309
310    // Suffix used during package installation when copying/moving
311    // package apks to install directory.
312    private static final String INSTALL_PACKAGE_SUFFIX = "-";
313
314    static final int SCAN_NO_DEX = 1<<1;
315    static final int SCAN_FORCE_DEX = 1<<2;
316    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
317    static final int SCAN_NEW_INSTALL = 1<<4;
318    static final int SCAN_NO_PATHS = 1<<5;
319    static final int SCAN_UPDATE_TIME = 1<<6;
320    static final int SCAN_DEFER_DEX = 1<<7;
321    static final int SCAN_BOOTING = 1<<8;
322    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
323    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
324    static final int SCAN_REQUIRE_KNOWN = 1<<12;
325    static final int SCAN_MOVE = 1<<13;
326    static final int SCAN_INITIAL = 1<<14;
327
328    static final int REMOVE_CHATTY = 1<<16;
329
330    private static final int[] EMPTY_INT_ARRAY = new int[0];
331
332    /**
333     * Timeout (in milliseconds) after which the watchdog should declare that
334     * our handler thread is wedged.  The usual default for such things is one
335     * minute but we sometimes do very lengthy I/O operations on this thread,
336     * such as installing multi-gigabyte applications, so ours needs to be longer.
337     */
338    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
339
340    /**
341     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
342     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
343     * settings entry if available, otherwise we use the hardcoded default.  If it's been
344     * more than this long since the last fstrim, we force one during the boot sequence.
345     *
346     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
347     * one gets run at the next available charging+idle time.  This final mandatory
348     * no-fstrim check kicks in only of the other scheduling criteria is never met.
349     */
350    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
351
352    /**
353     * Whether verification is enabled by default.
354     */
355    private static final boolean DEFAULT_VERIFY_ENABLE = true;
356
357    /**
358     * The default maximum time to wait for the verification agent to return in
359     * milliseconds.
360     */
361    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
362
363    /**
364     * The default response for package verification timeout.
365     *
366     * This can be either PackageManager.VERIFICATION_ALLOW or
367     * PackageManager.VERIFICATION_REJECT.
368     */
369    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
370
371    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
372
373    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
374            DEFAULT_CONTAINER_PACKAGE,
375            "com.android.defcontainer.DefaultContainerService");
376
377    private static final String KILL_APP_REASON_GIDS_CHANGED =
378            "permission grant or revoke changed gids";
379
380    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
381            "permissions revoked";
382
383    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
384
385    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
386
387    /** Permission grant: not grant the permission. */
388    private static final int GRANT_DENIED = 1;
389
390    /** Permission grant: grant the permission as an install permission. */
391    private static final int GRANT_INSTALL = 2;
392
393    /** Permission grant: grant the permission as an install permission for a legacy app. */
394    private static final int GRANT_INSTALL_LEGACY = 3;
395
396    /** Permission grant: grant the permission as a runtime one. */
397    private static final int GRANT_RUNTIME = 4;
398
399    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
400    private static final int GRANT_UPGRADE = 5;
401
402    /** Canonical intent used to identify what counts as a "web browser" app */
403    private static final Intent sBrowserIntent;
404    static {
405        sBrowserIntent = new Intent();
406        sBrowserIntent.setAction(Intent.ACTION_VIEW);
407        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
408        sBrowserIntent.setData(Uri.parse("http:"));
409    }
410
411    final ServiceThread mHandlerThread;
412
413    final PackageHandler mHandler;
414
415    /**
416     * Messages for {@link #mHandler} that need to wait for system ready before
417     * being dispatched.
418     */
419    private ArrayList<Message> mPostSystemReadyMessages;
420
421    final int mSdkVersion = Build.VERSION.SDK_INT;
422
423    final Context mContext;
424    final boolean mFactoryTest;
425    final boolean mOnlyCore;
426    final boolean mLazyDexOpt;
427    final long mDexOptLRUThresholdInMills;
428    final DisplayMetrics mMetrics;
429    final int mDefParseFlags;
430    final String[] mSeparateProcesses;
431    final boolean mIsUpgrade;
432
433    // This is where all application persistent data goes.
434    final File mAppDataDir;
435
436    // This is where all application persistent data goes for secondary users.
437    final File mUserAppDataDir;
438
439    /** The location for ASEC container files on internal storage. */
440    final String mAsecInternalPath;
441
442    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
443    // LOCK HELD.  Can be called with mInstallLock held.
444    @GuardedBy("mInstallLock")
445    final Installer mInstaller;
446
447    /** Directory where installed third-party apps stored */
448    final File mAppInstallDir;
449
450    /**
451     * Directory to which applications installed internally have their
452     * 32 bit native libraries copied.
453     */
454    private File mAppLib32InstallDir;
455
456    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
457    // apps.
458    final File mDrmAppPrivateInstallDir;
459
460    // ----------------------------------------------------------------
461
462    // Lock for state used when installing and doing other long running
463    // operations.  Methods that must be called with this lock held have
464    // the suffix "LI".
465    final Object mInstallLock = new Object();
466
467    // ----------------------------------------------------------------
468
469    // Keys are String (package name), values are Package.  This also serves
470    // as the lock for the global state.  Methods that must be called with
471    // this lock held have the prefix "LP".
472    @GuardedBy("mPackages")
473    final ArrayMap<String, PackageParser.Package> mPackages =
474            new ArrayMap<String, PackageParser.Package>();
475
476    // Tracks available target package names -> overlay package paths.
477    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
478        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
479
480    final Settings mSettings;
481    boolean mRestoredSettings;
482
483    // System configuration read by SystemConfig.
484    final int[] mGlobalGids;
485    final SparseArray<ArraySet<String>> mSystemPermissions;
486    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
487
488    // If mac_permissions.xml was found for seinfo labeling.
489    boolean mFoundPolicyFile;
490
491    // If a recursive restorecon of /data/data/<pkg> is needed.
492    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
493
494    public static final class SharedLibraryEntry {
495        public final String path;
496        public final String apk;
497
498        SharedLibraryEntry(String _path, String _apk) {
499            path = _path;
500            apk = _apk;
501        }
502    }
503
504    // Currently known shared libraries.
505    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
506            new ArrayMap<String, SharedLibraryEntry>();
507
508    // All available activities, for your resolving pleasure.
509    final ActivityIntentResolver mActivities =
510            new ActivityIntentResolver();
511
512    // All available receivers, for your resolving pleasure.
513    final ActivityIntentResolver mReceivers =
514            new ActivityIntentResolver();
515
516    // All available services, for your resolving pleasure.
517    final ServiceIntentResolver mServices = new ServiceIntentResolver();
518
519    // All available providers, for your resolving pleasure.
520    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
521
522    // Mapping from provider base names (first directory in content URI codePath)
523    // to the provider information.
524    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
525            new ArrayMap<String, PackageParser.Provider>();
526
527    // Mapping from instrumentation class names to info about them.
528    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
529            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
530
531    // Mapping from permission names to info about them.
532    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
533            new ArrayMap<String, PackageParser.PermissionGroup>();
534
535    // Packages whose data we have transfered into another package, thus
536    // should no longer exist.
537    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
538
539    // Broadcast actions that are only available to the system.
540    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
541
542    /** List of packages waiting for verification. */
543    final SparseArray<PackageVerificationState> mPendingVerification
544            = new SparseArray<PackageVerificationState>();
545
546    /** Set of packages associated with each app op permission. */
547    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
548
549    final PackageInstallerService mInstallerService;
550
551    private final PackageDexOptimizer mPackageDexOptimizer;
552
553    private AtomicInteger mNextMoveId = new AtomicInteger();
554    private final MoveCallbacks mMoveCallbacks;
555
556    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
557
558    // Cache of users who need badging.
559    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
560
561    /** Token for keys in mPendingVerification. */
562    private int mPendingVerificationToken = 0;
563
564    volatile boolean mSystemReady;
565    volatile boolean mSafeMode;
566    volatile boolean mHasSystemUidErrors;
567
568    ApplicationInfo mAndroidApplication;
569    final ActivityInfo mResolveActivity = new ActivityInfo();
570    final ResolveInfo mResolveInfo = new ResolveInfo();
571    ComponentName mResolveComponentName;
572    PackageParser.Package mPlatformPackage;
573    ComponentName mCustomResolverComponentName;
574
575    boolean mResolverReplaced = false;
576
577    private final ComponentName mIntentFilterVerifierComponent;
578    private int mIntentFilterVerificationToken = 0;
579
580    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
581            = new SparseArray<IntentFilterVerificationState>();
582
583    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
584            new DefaultPermissionGrantPolicy(this);
585
586    private static class IFVerificationParams {
587        PackageParser.Package pkg;
588        boolean replacing;
589        int userId;
590        int verifierUid;
591
592        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
593                int _userId, int _verifierUid) {
594            pkg = _pkg;
595            replacing = _replacing;
596            userId = _userId;
597            replacing = _replacing;
598            verifierUid = _verifierUid;
599        }
600    }
601
602    private interface IntentFilterVerifier<T extends IntentFilter> {
603        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
604                                               T filter, String packageName);
605        void startVerifications(int userId);
606        void receiveVerificationResponse(int verificationId);
607    }
608
609    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
610        private Context mContext;
611        private ComponentName mIntentFilterVerifierComponent;
612        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
613
614        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
615            mContext = context;
616            mIntentFilterVerifierComponent = verifierComponent;
617        }
618
619        private String getDefaultScheme() {
620            return IntentFilter.SCHEME_HTTPS;
621        }
622
623        @Override
624        public void startVerifications(int userId) {
625            // Launch verifications requests
626            int count = mCurrentIntentFilterVerifications.size();
627            for (int n=0; n<count; n++) {
628                int verificationId = mCurrentIntentFilterVerifications.get(n);
629                final IntentFilterVerificationState ivs =
630                        mIntentFilterVerificationStates.get(verificationId);
631
632                String packageName = ivs.getPackageName();
633
634                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
635                final int filterCount = filters.size();
636                ArraySet<String> domainsSet = new ArraySet<>();
637                for (int m=0; m<filterCount; m++) {
638                    PackageParser.ActivityIntentInfo filter = filters.get(m);
639                    domainsSet.addAll(filter.getHostsList());
640                }
641                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
642                synchronized (mPackages) {
643                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
644                            packageName, domainsList) != null) {
645                        scheduleWriteSettingsLocked();
646                    }
647                }
648                sendVerificationRequest(userId, verificationId, ivs);
649            }
650            mCurrentIntentFilterVerifications.clear();
651        }
652
653        private void sendVerificationRequest(int userId, int verificationId,
654                IntentFilterVerificationState ivs) {
655
656            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
657            verificationIntent.putExtra(
658                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
659                    verificationId);
660            verificationIntent.putExtra(
661                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
662                    getDefaultScheme());
663            verificationIntent.putExtra(
664                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
665                    ivs.getHostsString());
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
668                    ivs.getPackageName());
669            verificationIntent.setComponent(mIntentFilterVerifierComponent);
670            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
671
672            UserHandle user = new UserHandle(userId);
673            mContext.sendBroadcastAsUser(verificationIntent, user);
674            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
675                    "Sending IntentFilter verification broadcast");
676        }
677
678        public void receiveVerificationResponse(int verificationId) {
679            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
680
681            final boolean verified = ivs.isVerified();
682
683            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
684            final int count = filters.size();
685            if (DEBUG_DOMAIN_VERIFICATION) {
686                Slog.i(TAG, "Received verification response " + verificationId
687                        + " for " + count + " filters, verified=" + verified);
688            }
689            for (int n=0; n<count; n++) {
690                PackageParser.ActivityIntentInfo filter = filters.get(n);
691                filter.setVerified(verified);
692
693                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
694                        + " verified with result:" + verified + " and hosts:"
695                        + ivs.getHostsString());
696            }
697
698            mIntentFilterVerificationStates.remove(verificationId);
699
700            final String packageName = ivs.getPackageName();
701            IntentFilterVerificationInfo ivi = null;
702
703            synchronized (mPackages) {
704                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
705            }
706            if (ivi == null) {
707                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
708                        + verificationId + " packageName:" + packageName);
709                return;
710            }
711            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
712                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
713
714            synchronized (mPackages) {
715                if (verified) {
716                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
717                } else {
718                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
719                }
720                scheduleWriteSettingsLocked();
721
722                final int userId = ivs.getUserId();
723                if (userId != UserHandle.USER_ALL) {
724                    final int userStatus =
725                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
726
727                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
728                    boolean needUpdate = false;
729
730                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
731                    // already been set by the User thru the Disambiguation dialog
732                    switch (userStatus) {
733                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
734                            if (verified) {
735                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
736                            } else {
737                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
738                            }
739                            needUpdate = true;
740                            break;
741
742                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
743                            if (verified) {
744                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
745                                needUpdate = true;
746                            }
747                            break;
748
749                        default:
750                            // Nothing to do
751                    }
752
753                    if (needUpdate) {
754                        mSettings.updateIntentFilterVerificationStatusLPw(
755                                packageName, updatedStatus, userId);
756                        scheduleWritePackageRestrictionsLocked(userId);
757                    }
758                }
759            }
760        }
761
762        @Override
763        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
764                    ActivityIntentInfo filter, String packageName) {
765            if (!hasValidDomains(filter)) {
766                return false;
767            }
768            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
769            if (ivs == null) {
770                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
771                        packageName);
772            }
773            if (DEBUG_DOMAIN_VERIFICATION) {
774                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
775            }
776            ivs.addFilter(filter);
777            return true;
778        }
779
780        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
781                int userId, int verificationId, String packageName) {
782            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
783                    verifierUid, userId, packageName);
784            ivs.setPendingState();
785            synchronized (mPackages) {
786                mIntentFilterVerificationStates.append(verificationId, ivs);
787                mCurrentIntentFilterVerifications.add(verificationId);
788            }
789            return ivs;
790        }
791    }
792
793    private static boolean hasValidDomains(ActivityIntentInfo filter) {
794        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
795                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
796        if (!hasHTTPorHTTPS) {
797            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
798                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
799            return false;
800        }
801        return true;
802    }
803
804    private IntentFilterVerifier mIntentFilterVerifier;
805
806    // Set of pending broadcasts for aggregating enable/disable of components.
807    static class PendingPackageBroadcasts {
808        // for each user id, a map of <package name -> components within that package>
809        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
810
811        public PendingPackageBroadcasts() {
812            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
813        }
814
815        public ArrayList<String> get(int userId, String packageName) {
816            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
817            return packages.get(packageName);
818        }
819
820        public void put(int userId, String packageName, ArrayList<String> components) {
821            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
822            packages.put(packageName, components);
823        }
824
825        public void remove(int userId, String packageName) {
826            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
827            if (packages != null) {
828                packages.remove(packageName);
829            }
830        }
831
832        public void remove(int userId) {
833            mUidMap.remove(userId);
834        }
835
836        public int userIdCount() {
837            return mUidMap.size();
838        }
839
840        public int userIdAt(int n) {
841            return mUidMap.keyAt(n);
842        }
843
844        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
845            return mUidMap.get(userId);
846        }
847
848        public int size() {
849            // total number of pending broadcast entries across all userIds
850            int num = 0;
851            for (int i = 0; i< mUidMap.size(); i++) {
852                num += mUidMap.valueAt(i).size();
853            }
854            return num;
855        }
856
857        public void clear() {
858            mUidMap.clear();
859        }
860
861        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
862            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
863            if (map == null) {
864                map = new ArrayMap<String, ArrayList<String>>();
865                mUidMap.put(userId, map);
866            }
867            return map;
868        }
869    }
870    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
871
872    // Service Connection to remote media container service to copy
873    // package uri's from external media onto secure containers
874    // or internal storage.
875    private IMediaContainerService mContainerService = null;
876
877    static final int SEND_PENDING_BROADCAST = 1;
878    static final int MCS_BOUND = 3;
879    static final int END_COPY = 4;
880    static final int INIT_COPY = 5;
881    static final int MCS_UNBIND = 6;
882    static final int START_CLEANING_PACKAGE = 7;
883    static final int FIND_INSTALL_LOC = 8;
884    static final int POST_INSTALL = 9;
885    static final int MCS_RECONNECT = 10;
886    static final int MCS_GIVE_UP = 11;
887    static final int UPDATED_MEDIA_STATUS = 12;
888    static final int WRITE_SETTINGS = 13;
889    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
890    static final int PACKAGE_VERIFIED = 15;
891    static final int CHECK_PENDING_VERIFICATION = 16;
892    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
893    static final int INTENT_FILTER_VERIFIED = 18;
894
895    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
896
897    // Delay time in millisecs
898    static final int BROADCAST_DELAY = 10 * 1000;
899
900    static UserManagerService sUserManager;
901
902    // Stores a list of users whose package restrictions file needs to be updated
903    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
904
905    final private DefaultContainerConnection mDefContainerConn =
906            new DefaultContainerConnection();
907    class DefaultContainerConnection implements ServiceConnection {
908        public void onServiceConnected(ComponentName name, IBinder service) {
909            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
910            IMediaContainerService imcs =
911                IMediaContainerService.Stub.asInterface(service);
912            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
913        }
914
915        public void onServiceDisconnected(ComponentName name) {
916            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
917        }
918    }
919
920    // Recordkeeping of restore-after-install operations that are currently in flight
921    // between the Package Manager and the Backup Manager
922    class PostInstallData {
923        public InstallArgs args;
924        public PackageInstalledInfo res;
925
926        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
927            args = _a;
928            res = _r;
929        }
930    }
931
932    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
933    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
934
935    // XML tags for backup/restore of various bits of state
936    private static final String TAG_PREFERRED_BACKUP = "pa";
937    private static final String TAG_DEFAULT_APPS = "da";
938    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
939
940    final String mRequiredVerifierPackage;
941    final String mRequiredInstallerPackage;
942
943    private final PackageUsage mPackageUsage = new PackageUsage();
944
945    private class PackageUsage {
946        private static final int WRITE_INTERVAL
947            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
948
949        private final Object mFileLock = new Object();
950        private final AtomicLong mLastWritten = new AtomicLong(0);
951        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
952
953        private boolean mIsHistoricalPackageUsageAvailable = true;
954
955        boolean isHistoricalPackageUsageAvailable() {
956            return mIsHistoricalPackageUsageAvailable;
957        }
958
959        void write(boolean force) {
960            if (force) {
961                writeInternal();
962                return;
963            }
964            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
965                && !DEBUG_DEXOPT) {
966                return;
967            }
968            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
969                new Thread("PackageUsage_DiskWriter") {
970                    @Override
971                    public void run() {
972                        try {
973                            writeInternal();
974                        } finally {
975                            mBackgroundWriteRunning.set(false);
976                        }
977                    }
978                }.start();
979            }
980        }
981
982        private void writeInternal() {
983            synchronized (mPackages) {
984                synchronized (mFileLock) {
985                    AtomicFile file = getFile();
986                    FileOutputStream f = null;
987                    try {
988                        f = file.startWrite();
989                        BufferedOutputStream out = new BufferedOutputStream(f);
990                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
991                        StringBuilder sb = new StringBuilder();
992                        for (PackageParser.Package pkg : mPackages.values()) {
993                            if (pkg.mLastPackageUsageTimeInMills == 0) {
994                                continue;
995                            }
996                            sb.setLength(0);
997                            sb.append(pkg.packageName);
998                            sb.append(' ');
999                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1000                            sb.append('\n');
1001                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1002                        }
1003                        out.flush();
1004                        file.finishWrite(f);
1005                    } catch (IOException e) {
1006                        if (f != null) {
1007                            file.failWrite(f);
1008                        }
1009                        Log.e(TAG, "Failed to write package usage times", e);
1010                    }
1011                }
1012            }
1013            mLastWritten.set(SystemClock.elapsedRealtime());
1014        }
1015
1016        void readLP() {
1017            synchronized (mFileLock) {
1018                AtomicFile file = getFile();
1019                BufferedInputStream in = null;
1020                try {
1021                    in = new BufferedInputStream(file.openRead());
1022                    StringBuffer sb = new StringBuffer();
1023                    while (true) {
1024                        String packageName = readToken(in, sb, ' ');
1025                        if (packageName == null) {
1026                            break;
1027                        }
1028                        String timeInMillisString = readToken(in, sb, '\n');
1029                        if (timeInMillisString == null) {
1030                            throw new IOException("Failed to find last usage time for package "
1031                                                  + packageName);
1032                        }
1033                        PackageParser.Package pkg = mPackages.get(packageName);
1034                        if (pkg == null) {
1035                            continue;
1036                        }
1037                        long timeInMillis;
1038                        try {
1039                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1040                        } catch (NumberFormatException e) {
1041                            throw new IOException("Failed to parse " + timeInMillisString
1042                                                  + " as a long.", e);
1043                        }
1044                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1045                    }
1046                } catch (FileNotFoundException expected) {
1047                    mIsHistoricalPackageUsageAvailable = false;
1048                } catch (IOException e) {
1049                    Log.w(TAG, "Failed to read package usage times", e);
1050                } finally {
1051                    IoUtils.closeQuietly(in);
1052                }
1053            }
1054            mLastWritten.set(SystemClock.elapsedRealtime());
1055        }
1056
1057        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1058                throws IOException {
1059            sb.setLength(0);
1060            while (true) {
1061                int ch = in.read();
1062                if (ch == -1) {
1063                    if (sb.length() == 0) {
1064                        return null;
1065                    }
1066                    throw new IOException("Unexpected EOF");
1067                }
1068                if (ch == endOfToken) {
1069                    return sb.toString();
1070                }
1071                sb.append((char)ch);
1072            }
1073        }
1074
1075        private AtomicFile getFile() {
1076            File dataDir = Environment.getDataDirectory();
1077            File systemDir = new File(dataDir, "system");
1078            File fname = new File(systemDir, "package-usage.list");
1079            return new AtomicFile(fname);
1080        }
1081    }
1082
1083    class PackageHandler extends Handler {
1084        private boolean mBound = false;
1085        final ArrayList<HandlerParams> mPendingInstalls =
1086            new ArrayList<HandlerParams>();
1087
1088        private boolean connectToService() {
1089            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1090                    " DefaultContainerService");
1091            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1092            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1093            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1094                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1095                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1096                mBound = true;
1097                return true;
1098            }
1099            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1100            return false;
1101        }
1102
1103        private void disconnectService() {
1104            mContainerService = null;
1105            mBound = false;
1106            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1107            mContext.unbindService(mDefContainerConn);
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1109        }
1110
1111        PackageHandler(Looper looper) {
1112            super(looper);
1113        }
1114
1115        public void handleMessage(Message msg) {
1116            try {
1117                doHandleMessage(msg);
1118            } finally {
1119                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1120            }
1121        }
1122
1123        void doHandleMessage(Message msg) {
1124            switch (msg.what) {
1125                case INIT_COPY: {
1126                    HandlerParams params = (HandlerParams) msg.obj;
1127                    int idx = mPendingInstalls.size();
1128                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1129                    // If a bind was already initiated we dont really
1130                    // need to do anything. The pending install
1131                    // will be processed later on.
1132                    if (!mBound) {
1133                        // If this is the only one pending we might
1134                        // have to bind to the service again.
1135                        if (!connectToService()) {
1136                            Slog.e(TAG, "Failed to bind to media container service");
1137                            params.serviceError();
1138                            return;
1139                        } else {
1140                            // Once we bind to the service, the first
1141                            // pending request will be processed.
1142                            mPendingInstalls.add(idx, params);
1143                        }
1144                    } else {
1145                        mPendingInstalls.add(idx, params);
1146                        // Already bound to the service. Just make
1147                        // sure we trigger off processing the first request.
1148                        if (idx == 0) {
1149                            mHandler.sendEmptyMessage(MCS_BOUND);
1150                        }
1151                    }
1152                    break;
1153                }
1154                case MCS_BOUND: {
1155                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1156                    if (msg.obj != null) {
1157                        mContainerService = (IMediaContainerService) msg.obj;
1158                    }
1159                    if (mContainerService == null) {
1160                        if (!mBound) {
1161                            // Something seriously wrong since we are not bound and we are not
1162                            // waiting for connection. Bail out.
1163                            Slog.e(TAG, "Cannot bind to media container service");
1164                            for (HandlerParams params : mPendingInstalls) {
1165                                // Indicate service bind error
1166                                params.serviceError();
1167                            }
1168                            mPendingInstalls.clear();
1169                        } else {
1170                            Slog.w(TAG, "Waiting to connect to media container service");
1171                        }
1172                    } else if (mPendingInstalls.size() > 0) {
1173                        HandlerParams params = mPendingInstalls.get(0);
1174                        if (params != null) {
1175                            if (params.startCopy()) {
1176                                // We are done...  look for more work or to
1177                                // go idle.
1178                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1179                                        "Checking for more work or unbind...");
1180                                // Delete pending install
1181                                if (mPendingInstalls.size() > 0) {
1182                                    mPendingInstalls.remove(0);
1183                                }
1184                                if (mPendingInstalls.size() == 0) {
1185                                    if (mBound) {
1186                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1187                                                "Posting delayed MCS_UNBIND");
1188                                        removeMessages(MCS_UNBIND);
1189                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1190                                        // Unbind after a little delay, to avoid
1191                                        // continual thrashing.
1192                                        sendMessageDelayed(ubmsg, 10000);
1193                                    }
1194                                } else {
1195                                    // There are more pending requests in queue.
1196                                    // Just post MCS_BOUND message to trigger processing
1197                                    // of next pending install.
1198                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1199                                            "Posting MCS_BOUND for next work");
1200                                    mHandler.sendEmptyMessage(MCS_BOUND);
1201                                }
1202                            }
1203                        }
1204                    } else {
1205                        // Should never happen ideally.
1206                        Slog.w(TAG, "Empty queue");
1207                    }
1208                    break;
1209                }
1210                case MCS_RECONNECT: {
1211                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1212                    if (mPendingInstalls.size() > 0) {
1213                        if (mBound) {
1214                            disconnectService();
1215                        }
1216                        if (!connectToService()) {
1217                            Slog.e(TAG, "Failed to bind to media container service");
1218                            for (HandlerParams params : mPendingInstalls) {
1219                                // Indicate service bind error
1220                                params.serviceError();
1221                            }
1222                            mPendingInstalls.clear();
1223                        }
1224                    }
1225                    break;
1226                }
1227                case MCS_UNBIND: {
1228                    // If there is no actual work left, then time to unbind.
1229                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1230
1231                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1232                        if (mBound) {
1233                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1234
1235                            disconnectService();
1236                        }
1237                    } else if (mPendingInstalls.size() > 0) {
1238                        // There are more pending requests in queue.
1239                        // Just post MCS_BOUND message to trigger processing
1240                        // of next pending install.
1241                        mHandler.sendEmptyMessage(MCS_BOUND);
1242                    }
1243
1244                    break;
1245                }
1246                case MCS_GIVE_UP: {
1247                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1248                    mPendingInstalls.remove(0);
1249                    break;
1250                }
1251                case SEND_PENDING_BROADCAST: {
1252                    String packages[];
1253                    ArrayList<String> components[];
1254                    int size = 0;
1255                    int uids[];
1256                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1257                    synchronized (mPackages) {
1258                        if (mPendingBroadcasts == null) {
1259                            return;
1260                        }
1261                        size = mPendingBroadcasts.size();
1262                        if (size <= 0) {
1263                            // Nothing to be done. Just return
1264                            return;
1265                        }
1266                        packages = new String[size];
1267                        components = new ArrayList[size];
1268                        uids = new int[size];
1269                        int i = 0;  // filling out the above arrays
1270
1271                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1272                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1273                            Iterator<Map.Entry<String, ArrayList<String>>> it
1274                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1275                                            .entrySet().iterator();
1276                            while (it.hasNext() && i < size) {
1277                                Map.Entry<String, ArrayList<String>> ent = it.next();
1278                                packages[i] = ent.getKey();
1279                                components[i] = ent.getValue();
1280                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1281                                uids[i] = (ps != null)
1282                                        ? UserHandle.getUid(packageUserId, ps.appId)
1283                                        : -1;
1284                                i++;
1285                            }
1286                        }
1287                        size = i;
1288                        mPendingBroadcasts.clear();
1289                    }
1290                    // Send broadcasts
1291                    for (int i = 0; i < size; i++) {
1292                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1293                    }
1294                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1295                    break;
1296                }
1297                case START_CLEANING_PACKAGE: {
1298                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1299                    final String packageName = (String)msg.obj;
1300                    final int userId = msg.arg1;
1301                    final boolean andCode = msg.arg2 != 0;
1302                    synchronized (mPackages) {
1303                        if (userId == UserHandle.USER_ALL) {
1304                            int[] users = sUserManager.getUserIds();
1305                            for (int user : users) {
1306                                mSettings.addPackageToCleanLPw(
1307                                        new PackageCleanItem(user, packageName, andCode));
1308                            }
1309                        } else {
1310                            mSettings.addPackageToCleanLPw(
1311                                    new PackageCleanItem(userId, packageName, andCode));
1312                        }
1313                    }
1314                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1315                    startCleaningPackages();
1316                } break;
1317                case POST_INSTALL: {
1318                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1319                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1320                    mRunningInstalls.delete(msg.arg1);
1321                    boolean deleteOld = false;
1322
1323                    if (data != null) {
1324                        InstallArgs args = data.args;
1325                        PackageInstalledInfo res = data.res;
1326
1327                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1328                            final String packageName = res.pkg.applicationInfo.packageName;
1329                            res.removedInfo.sendBroadcast(false, true, false);
1330                            Bundle extras = new Bundle(1);
1331                            extras.putInt(Intent.EXTRA_UID, res.uid);
1332
1333                            // Now that we successfully installed the package, grant runtime
1334                            // permissions if requested before broadcasting the install.
1335                            if ((args.installFlags
1336                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1337                                grantRequestedRuntimePermissions(res.pkg,
1338                                        args.user.getIdentifier());
1339                            }
1340
1341                            // Determine the set of users who are adding this
1342                            // package for the first time vs. those who are seeing
1343                            // an update.
1344                            int[] firstUsers;
1345                            int[] updateUsers = new int[0];
1346                            if (res.origUsers == null || res.origUsers.length == 0) {
1347                                firstUsers = res.newUsers;
1348                            } else {
1349                                firstUsers = new int[0];
1350                                for (int i=0; i<res.newUsers.length; i++) {
1351                                    int user = res.newUsers[i];
1352                                    boolean isNew = true;
1353                                    for (int j=0; j<res.origUsers.length; j++) {
1354                                        if (res.origUsers[j] == user) {
1355                                            isNew = false;
1356                                            break;
1357                                        }
1358                                    }
1359                                    if (isNew) {
1360                                        int[] newFirst = new int[firstUsers.length+1];
1361                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1362                                                firstUsers.length);
1363                                        newFirst[firstUsers.length] = user;
1364                                        firstUsers = newFirst;
1365                                    } else {
1366                                        int[] newUpdate = new int[updateUsers.length+1];
1367                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1368                                                updateUsers.length);
1369                                        newUpdate[updateUsers.length] = user;
1370                                        updateUsers = newUpdate;
1371                                    }
1372                                }
1373                            }
1374                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1375                                    packageName, extras, null, null, firstUsers);
1376                            final boolean update = res.removedInfo.removedPackage != null;
1377                            if (update) {
1378                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1379                            }
1380                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1381                                    packageName, extras, null, null, updateUsers);
1382                            if (update) {
1383                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1384                                        packageName, extras, null, null, updateUsers);
1385                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1386                                        null, null, packageName, null, updateUsers);
1387
1388                                // treat asec-hosted packages like removable media on upgrade
1389                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1390                                    if (DEBUG_INSTALL) {
1391                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1392                                                + " is ASEC-hosted -> AVAILABLE");
1393                                    }
1394                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1395                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1396                                    pkgList.add(packageName);
1397                                    sendResourcesChangedBroadcast(true, true,
1398                                            pkgList,uidArray, null);
1399                                }
1400                            }
1401                            if (res.removedInfo.args != null) {
1402                                // Remove the replaced package's older resources safely now
1403                                deleteOld = true;
1404                            }
1405
1406                            // If this app is a browser and it's newly-installed for some
1407                            // users, clear any default-browser state in those users
1408                            if (firstUsers.length > 0) {
1409                                // the app's nature doesn't depend on the user, so we can just
1410                                // check its browser nature in any user and generalize.
1411                                if (packageIsBrowser(packageName, firstUsers[0])) {
1412                                    synchronized (mPackages) {
1413                                        for (int userId : firstUsers) {
1414                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1415                                        }
1416                                    }
1417                                }
1418                            }
1419                            // Log current value of "unknown sources" setting
1420                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1421                                getUnknownSourcesSettings());
1422                        }
1423                        // Force a gc to clear up things
1424                        Runtime.getRuntime().gc();
1425                        // We delete after a gc for applications  on sdcard.
1426                        if (deleteOld) {
1427                            synchronized (mInstallLock) {
1428                                res.removedInfo.args.doPostDeleteLI(true);
1429                            }
1430                        }
1431                        if (args.observer != null) {
1432                            try {
1433                                Bundle extras = extrasForInstallResult(res);
1434                                args.observer.onPackageInstalled(res.name, res.returnCode,
1435                                        res.returnMsg, extras);
1436                            } catch (RemoteException e) {
1437                                Slog.i(TAG, "Observer no longer exists.");
1438                            }
1439                        }
1440                    } else {
1441                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1442                    }
1443                } break;
1444                case UPDATED_MEDIA_STATUS: {
1445                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1446                    boolean reportStatus = msg.arg1 == 1;
1447                    boolean doGc = msg.arg2 == 1;
1448                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1449                    if (doGc) {
1450                        // Force a gc to clear up stale containers.
1451                        Runtime.getRuntime().gc();
1452                    }
1453                    if (msg.obj != null) {
1454                        @SuppressWarnings("unchecked")
1455                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1456                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1457                        // Unload containers
1458                        unloadAllContainers(args);
1459                    }
1460                    if (reportStatus) {
1461                        try {
1462                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1463                            PackageHelper.getMountService().finishMediaUpdate();
1464                        } catch (RemoteException e) {
1465                            Log.e(TAG, "MountService not running?");
1466                        }
1467                    }
1468                } break;
1469                case WRITE_SETTINGS: {
1470                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1471                    synchronized (mPackages) {
1472                        removeMessages(WRITE_SETTINGS);
1473                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1474                        mSettings.writeLPr();
1475                        mDirtyUsers.clear();
1476                    }
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478                } break;
1479                case WRITE_PACKAGE_RESTRICTIONS: {
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1481                    synchronized (mPackages) {
1482                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1483                        for (int userId : mDirtyUsers) {
1484                            mSettings.writePackageRestrictionsLPr(userId);
1485                        }
1486                        mDirtyUsers.clear();
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                } break;
1490                case CHECK_PENDING_VERIFICATION: {
1491                    final int verificationId = msg.arg1;
1492                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1493
1494                    if ((state != null) && !state.timeoutExtended()) {
1495                        final InstallArgs args = state.getInstallArgs();
1496                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1497
1498                        Slog.i(TAG, "Verification timed out for " + originUri);
1499                        mPendingVerification.remove(verificationId);
1500
1501                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1502
1503                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1504                            Slog.i(TAG, "Continuing with installation of " + originUri);
1505                            state.setVerifierResponse(Binder.getCallingUid(),
1506                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1507                            broadcastPackageVerified(verificationId, originUri,
1508                                    PackageManager.VERIFICATION_ALLOW,
1509                                    state.getInstallArgs().getUser());
1510                            try {
1511                                ret = args.copyApk(mContainerService, true);
1512                            } catch (RemoteException e) {
1513                                Slog.e(TAG, "Could not contact the ContainerService");
1514                            }
1515                        } else {
1516                            broadcastPackageVerified(verificationId, originUri,
1517                                    PackageManager.VERIFICATION_REJECT,
1518                                    state.getInstallArgs().getUser());
1519                        }
1520
1521                        processPendingInstall(args, ret);
1522                        mHandler.sendEmptyMessage(MCS_UNBIND);
1523                    }
1524                    break;
1525                }
1526                case PACKAGE_VERIFIED: {
1527                    final int verificationId = msg.arg1;
1528
1529                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1530                    if (state == null) {
1531                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1532                        break;
1533                    }
1534
1535                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1536
1537                    state.setVerifierResponse(response.callerUid, response.code);
1538
1539                    if (state.isVerificationComplete()) {
1540                        mPendingVerification.remove(verificationId);
1541
1542                        final InstallArgs args = state.getInstallArgs();
1543                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1544
1545                        int ret;
1546                        if (state.isInstallAllowed()) {
1547                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1548                            broadcastPackageVerified(verificationId, originUri,
1549                                    response.code, state.getInstallArgs().getUser());
1550                            try {
1551                                ret = args.copyApk(mContainerService, true);
1552                            } catch (RemoteException e) {
1553                                Slog.e(TAG, "Could not contact the ContainerService");
1554                            }
1555                        } else {
1556                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1557                        }
1558
1559                        processPendingInstall(args, ret);
1560
1561                        mHandler.sendEmptyMessage(MCS_UNBIND);
1562                    }
1563
1564                    break;
1565                }
1566                case START_INTENT_FILTER_VERIFICATIONS: {
1567                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1568                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1569                            params.replacing, params.pkg);
1570                    break;
1571                }
1572                case INTENT_FILTER_VERIFIED: {
1573                    final int verificationId = msg.arg1;
1574
1575                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1576                            verificationId);
1577                    if (state == null) {
1578                        Slog.w(TAG, "Invalid IntentFilter verification token "
1579                                + verificationId + " received");
1580                        break;
1581                    }
1582
1583                    final int userId = state.getUserId();
1584
1585                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1586                            "Processing IntentFilter verification with token:"
1587                            + verificationId + " and userId:" + userId);
1588
1589                    final IntentFilterVerificationResponse response =
1590                            (IntentFilterVerificationResponse) msg.obj;
1591
1592                    state.setVerifierResponse(response.callerUid, response.code);
1593
1594                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1595                            "IntentFilter verification with token:" + verificationId
1596                            + " and userId:" + userId
1597                            + " is settings verifier response with response code:"
1598                            + response.code);
1599
1600                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1601                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1602                                + response.getFailedDomainsString());
1603                    }
1604
1605                    if (state.isVerificationComplete()) {
1606                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1607                    } else {
1608                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1609                                "IntentFilter verification with token:" + verificationId
1610                                + " was not said to be complete");
1611                    }
1612
1613                    break;
1614                }
1615            }
1616        }
1617    }
1618
1619    private StorageEventListener mStorageListener = new StorageEventListener() {
1620        @Override
1621        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1622            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1623                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1624                    final String volumeUuid = vol.getFsUuid();
1625
1626                    // Clean up any users or apps that were removed or recreated
1627                    // while this volume was missing
1628                    reconcileUsers(volumeUuid);
1629                    reconcileApps(volumeUuid);
1630
1631                    // Clean up any install sessions that expired or were
1632                    // cancelled while this volume was missing
1633                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1634
1635                    loadPrivatePackages(vol);
1636
1637                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1638                    unloadPrivatePackages(vol);
1639                }
1640            }
1641
1642            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1643                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1644                    updateExternalMediaStatus(true, false);
1645                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1646                    updateExternalMediaStatus(false, false);
1647                }
1648            }
1649        }
1650
1651        @Override
1652        public void onVolumeForgotten(String fsUuid) {
1653            // Remove any apps installed on the forgotten volume
1654            synchronized (mPackages) {
1655                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1656                for (PackageSetting ps : packages) {
1657                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1658                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1659                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1660                }
1661
1662                mSettings.writeLPr();
1663            }
1664        }
1665    };
1666
1667    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1668        if (userId >= UserHandle.USER_OWNER) {
1669            grantRequestedRuntimePermissionsForUser(pkg, userId);
1670        } else if (userId == UserHandle.USER_ALL) {
1671            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1672                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1673            }
1674        }
1675
1676        // We could have touched GID membership, so flush out packages.list
1677        synchronized (mPackages) {
1678            mSettings.writePackageListLPr();
1679        }
1680    }
1681
1682    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1683        SettingBase sb = (SettingBase) pkg.mExtras;
1684        if (sb == null) {
1685            return;
1686        }
1687
1688        PermissionsState permissionsState = sb.getPermissionsState();
1689
1690        for (String permission : pkg.requestedPermissions) {
1691            BasePermission bp = mSettings.mPermissions.get(permission);
1692            if (bp != null && bp.isRuntime()) {
1693                permissionsState.grantRuntimePermission(bp, userId);
1694            }
1695        }
1696    }
1697
1698    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1699        Bundle extras = null;
1700        switch (res.returnCode) {
1701            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1702                extras = new Bundle();
1703                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1704                        res.origPermission);
1705                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1706                        res.origPackage);
1707                break;
1708            }
1709            case PackageManager.INSTALL_SUCCEEDED: {
1710                extras = new Bundle();
1711                extras.putBoolean(Intent.EXTRA_REPLACING,
1712                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1713                break;
1714            }
1715        }
1716        return extras;
1717    }
1718
1719    void scheduleWriteSettingsLocked() {
1720        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1721            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1722        }
1723    }
1724
1725    void scheduleWritePackageRestrictionsLocked(int userId) {
1726        if (!sUserManager.exists(userId)) return;
1727        mDirtyUsers.add(userId);
1728        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1729            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1730        }
1731    }
1732
1733    public static PackageManagerService main(Context context, Installer installer,
1734            boolean factoryTest, boolean onlyCore) {
1735        PackageManagerService m = new PackageManagerService(context, installer,
1736                factoryTest, onlyCore);
1737        ServiceManager.addService("package", m);
1738        return m;
1739    }
1740
1741    static String[] splitString(String str, char sep) {
1742        int count = 1;
1743        int i = 0;
1744        while ((i=str.indexOf(sep, i)) >= 0) {
1745            count++;
1746            i++;
1747        }
1748
1749        String[] res = new String[count];
1750        i=0;
1751        count = 0;
1752        int lastI=0;
1753        while ((i=str.indexOf(sep, i)) >= 0) {
1754            res[count] = str.substring(lastI, i);
1755            count++;
1756            i++;
1757            lastI = i;
1758        }
1759        res[count] = str.substring(lastI, str.length());
1760        return res;
1761    }
1762
1763    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1764        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1765                Context.DISPLAY_SERVICE);
1766        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1767    }
1768
1769    public PackageManagerService(Context context, Installer installer,
1770            boolean factoryTest, boolean onlyCore) {
1771        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1772                SystemClock.uptimeMillis());
1773
1774        if (mSdkVersion <= 0) {
1775            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1776        }
1777
1778        mContext = context;
1779        mFactoryTest = factoryTest;
1780        mOnlyCore = onlyCore;
1781        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1782        mMetrics = new DisplayMetrics();
1783        mSettings = new Settings(mPackages);
1784        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1785                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1786        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1787                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1788        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1789                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1790        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1791                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1792        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1793                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1794        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1795                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1796
1797        // TODO: add a property to control this?
1798        long dexOptLRUThresholdInMinutes;
1799        if (mLazyDexOpt) {
1800            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1801        } else {
1802            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1803        }
1804        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1805
1806        String separateProcesses = SystemProperties.get("debug.separate_processes");
1807        if (separateProcesses != null && separateProcesses.length() > 0) {
1808            if ("*".equals(separateProcesses)) {
1809                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1810                mSeparateProcesses = null;
1811                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1812            } else {
1813                mDefParseFlags = 0;
1814                mSeparateProcesses = separateProcesses.split(",");
1815                Slog.w(TAG, "Running with debug.separate_processes: "
1816                        + separateProcesses);
1817            }
1818        } else {
1819            mDefParseFlags = 0;
1820            mSeparateProcesses = null;
1821        }
1822
1823        mInstaller = installer;
1824        mPackageDexOptimizer = new PackageDexOptimizer(this);
1825        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1826
1827        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1828                FgThread.get().getLooper());
1829
1830        getDefaultDisplayMetrics(context, mMetrics);
1831
1832        SystemConfig systemConfig = SystemConfig.getInstance();
1833        mGlobalGids = systemConfig.getGlobalGids();
1834        mSystemPermissions = systemConfig.getSystemPermissions();
1835        mAvailableFeatures = systemConfig.getAvailableFeatures();
1836
1837        synchronized (mInstallLock) {
1838        // writer
1839        synchronized (mPackages) {
1840            mHandlerThread = new ServiceThread(TAG,
1841                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1842            mHandlerThread.start();
1843            mHandler = new PackageHandler(mHandlerThread.getLooper());
1844            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1845
1846            File dataDir = Environment.getDataDirectory();
1847            mAppDataDir = new File(dataDir, "data");
1848            mAppInstallDir = new File(dataDir, "app");
1849            mAppLib32InstallDir = new File(dataDir, "app-lib");
1850            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1851            mUserAppDataDir = new File(dataDir, "user");
1852            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1853
1854            sUserManager = new UserManagerService(context, this,
1855                    mInstallLock, mPackages);
1856
1857            // Propagate permission configuration in to package manager.
1858            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1859                    = systemConfig.getPermissions();
1860            for (int i=0; i<permConfig.size(); i++) {
1861                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1862                BasePermission bp = mSettings.mPermissions.get(perm.name);
1863                if (bp == null) {
1864                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1865                    mSettings.mPermissions.put(perm.name, bp);
1866                }
1867                if (perm.gids != null) {
1868                    bp.setGids(perm.gids, perm.perUser);
1869                }
1870            }
1871
1872            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1873            for (int i=0; i<libConfig.size(); i++) {
1874                mSharedLibraries.put(libConfig.keyAt(i),
1875                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1876            }
1877
1878            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1879
1880            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1881                    mSdkVersion, mOnlyCore);
1882
1883            String customResolverActivity = Resources.getSystem().getString(
1884                    R.string.config_customResolverActivity);
1885            if (TextUtils.isEmpty(customResolverActivity)) {
1886                customResolverActivity = null;
1887            } else {
1888                mCustomResolverComponentName = ComponentName.unflattenFromString(
1889                        customResolverActivity);
1890            }
1891
1892            long startTime = SystemClock.uptimeMillis();
1893
1894            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1895                    startTime);
1896
1897            // Set flag to monitor and not change apk file paths when
1898            // scanning install directories.
1899            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1900
1901            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1902
1903            /**
1904             * Add everything in the in the boot class path to the
1905             * list of process files because dexopt will have been run
1906             * if necessary during zygote startup.
1907             */
1908            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1909            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1910
1911            if (bootClassPath != null) {
1912                String[] bootClassPathElements = splitString(bootClassPath, ':');
1913                for (String element : bootClassPathElements) {
1914                    alreadyDexOpted.add(element);
1915                }
1916            } else {
1917                Slog.w(TAG, "No BOOTCLASSPATH found!");
1918            }
1919
1920            if (systemServerClassPath != null) {
1921                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1922                for (String element : systemServerClassPathElements) {
1923                    alreadyDexOpted.add(element);
1924                }
1925            } else {
1926                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1927            }
1928
1929            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1930            final String[] dexCodeInstructionSets =
1931                    getDexCodeInstructionSets(
1932                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1933
1934            /**
1935             * Ensure all external libraries have had dexopt run on them.
1936             */
1937            if (mSharedLibraries.size() > 0) {
1938                // NOTE: For now, we're compiling these system "shared libraries"
1939                // (and framework jars) into all available architectures. It's possible
1940                // to compile them only when we come across an app that uses them (there's
1941                // already logic for that in scanPackageLI) but that adds some complexity.
1942                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1943                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1944                        final String lib = libEntry.path;
1945                        if (lib == null) {
1946                            continue;
1947                        }
1948
1949                        try {
1950                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1951                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1952                                alreadyDexOpted.add(lib);
1953                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1954                            }
1955                        } catch (FileNotFoundException e) {
1956                            Slog.w(TAG, "Library not found: " + lib);
1957                        } catch (IOException e) {
1958                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1959                                    + e.getMessage());
1960                        }
1961                    }
1962                }
1963            }
1964
1965            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1966
1967            // Gross hack for now: we know this file doesn't contain any
1968            // code, so don't dexopt it to avoid the resulting log spew.
1969            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1970
1971            // Gross hack for now: we know this file is only part of
1972            // the boot class path for art, so don't dexopt it to
1973            // avoid the resulting log spew.
1974            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1975
1976            /**
1977             * There are a number of commands implemented in Java, which
1978             * we currently need to do the dexopt on so that they can be
1979             * run from a non-root shell.
1980             */
1981            String[] frameworkFiles = frameworkDir.list();
1982            if (frameworkFiles != null) {
1983                // TODO: We could compile these only for the most preferred ABI. We should
1984                // first double check that the dex files for these commands are not referenced
1985                // by other system apps.
1986                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1987                    for (int i=0; i<frameworkFiles.length; i++) {
1988                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1989                        String path = libPath.getPath();
1990                        // Skip the file if we already did it.
1991                        if (alreadyDexOpted.contains(path)) {
1992                            continue;
1993                        }
1994                        // Skip the file if it is not a type we want to dexopt.
1995                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1996                            continue;
1997                        }
1998                        try {
1999                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2000                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2001                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2002                            }
2003                        } catch (FileNotFoundException e) {
2004                            Slog.w(TAG, "Jar not found: " + path);
2005                        } catch (IOException e) {
2006                            Slog.w(TAG, "Exception reading jar: " + path, e);
2007                        }
2008                    }
2009                }
2010            }
2011
2012            // Collect vendor overlay packages.
2013            // (Do this before scanning any apps.)
2014            // For security and version matching reason, only consider
2015            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2016            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2017            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2018                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2019
2020            // Find base frameworks (resource packages without code).
2021            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2022                    | PackageParser.PARSE_IS_SYSTEM_DIR
2023                    | PackageParser.PARSE_IS_PRIVILEGED,
2024                    scanFlags | SCAN_NO_DEX, 0);
2025
2026            // Collected privileged system packages.
2027            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2028            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2029                    | PackageParser.PARSE_IS_SYSTEM_DIR
2030                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2031
2032            // Collect ordinary system packages.
2033            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2034            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2035                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2036
2037            // Collect all vendor packages.
2038            File vendorAppDir = new File("/vendor/app");
2039            try {
2040                vendorAppDir = vendorAppDir.getCanonicalFile();
2041            } catch (IOException e) {
2042                // failed to look up canonical path, continue with original one
2043            }
2044            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2045                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2046
2047            // Collect all OEM packages.
2048            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2049            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2050                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2051
2052            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2053            mInstaller.moveFiles();
2054
2055            // Prune any system packages that no longer exist.
2056            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2057            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2058            if (!mOnlyCore) {
2059                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2060                while (psit.hasNext()) {
2061                    PackageSetting ps = psit.next();
2062
2063                    /*
2064                     * If this is not a system app, it can't be a
2065                     * disable system app.
2066                     */
2067                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2068                        continue;
2069                    }
2070
2071                    /*
2072                     * If the package is scanned, it's not erased.
2073                     */
2074                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2075                    if (scannedPkg != null) {
2076                        /*
2077                         * If the system app is both scanned and in the
2078                         * disabled packages list, then it must have been
2079                         * added via OTA. Remove it from the currently
2080                         * scanned package so the previously user-installed
2081                         * application can be scanned.
2082                         */
2083                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2084                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2085                                    + ps.name + "; removing system app.  Last known codePath="
2086                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2087                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2088                                    + scannedPkg.mVersionCode);
2089                            removePackageLI(ps, true);
2090                            expectingBetter.put(ps.name, ps.codePath);
2091                        }
2092
2093                        continue;
2094                    }
2095
2096                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2097                        psit.remove();
2098                        logCriticalInfo(Log.WARN, "System package " + ps.name
2099                                + " no longer exists; wiping its data");
2100                        removeDataDirsLI(null, ps.name);
2101                    } else {
2102                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2103                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2104                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2105                        }
2106                    }
2107                }
2108            }
2109
2110            //look for any incomplete package installations
2111            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2112            //clean up list
2113            for(int i = 0; i < deletePkgsList.size(); i++) {
2114                //clean up here
2115                cleanupInstallFailedPackage(deletePkgsList.get(i));
2116            }
2117            //delete tmp files
2118            deleteTempPackageFiles();
2119
2120            // Remove any shared userIDs that have no associated packages
2121            mSettings.pruneSharedUsersLPw();
2122
2123            if (!mOnlyCore) {
2124                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2125                        SystemClock.uptimeMillis());
2126                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2127
2128                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2129                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2130
2131                /**
2132                 * Remove disable package settings for any updated system
2133                 * apps that were removed via an OTA. If they're not a
2134                 * previously-updated app, remove them completely.
2135                 * Otherwise, just revoke their system-level permissions.
2136                 */
2137                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2138                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2139                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2140
2141                    String msg;
2142                    if (deletedPkg == null) {
2143                        msg = "Updated system package " + deletedAppName
2144                                + " no longer exists; wiping its data";
2145                        removeDataDirsLI(null, deletedAppName);
2146                    } else {
2147                        msg = "Updated system app + " + deletedAppName
2148                                + " no longer present; removing system privileges for "
2149                                + deletedAppName;
2150
2151                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2152
2153                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2154                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2155                    }
2156                    logCriticalInfo(Log.WARN, msg);
2157                }
2158
2159                /**
2160                 * Make sure all system apps that we expected to appear on
2161                 * the userdata partition actually showed up. If they never
2162                 * appeared, crawl back and revive the system version.
2163                 */
2164                for (int i = 0; i < expectingBetter.size(); i++) {
2165                    final String packageName = expectingBetter.keyAt(i);
2166                    if (!mPackages.containsKey(packageName)) {
2167                        final File scanFile = expectingBetter.valueAt(i);
2168
2169                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2170                                + " but never showed up; reverting to system");
2171
2172                        final int reparseFlags;
2173                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2174                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2175                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2176                                    | PackageParser.PARSE_IS_PRIVILEGED;
2177                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2178                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2179                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2180                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2181                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2182                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2183                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2184                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2185                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2186                        } else {
2187                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2188                            continue;
2189                        }
2190
2191                        mSettings.enableSystemPackageLPw(packageName);
2192
2193                        try {
2194                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2195                        } catch (PackageManagerException e) {
2196                            Slog.e(TAG, "Failed to parse original system package: "
2197                                    + e.getMessage());
2198                        }
2199                    }
2200                }
2201            }
2202
2203            // Now that we know all of the shared libraries, update all clients to have
2204            // the correct library paths.
2205            updateAllSharedLibrariesLPw();
2206
2207            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2208                // NOTE: We ignore potential failures here during a system scan (like
2209                // the rest of the commands above) because there's precious little we
2210                // can do about it. A settings error is reported, though.
2211                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2212                        false /* force dexopt */, false /* defer dexopt */);
2213            }
2214
2215            // Now that we know all the packages we are keeping,
2216            // read and update their last usage times.
2217            mPackageUsage.readLP();
2218
2219            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2220                    SystemClock.uptimeMillis());
2221            Slog.i(TAG, "Time to scan packages: "
2222                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2223                    + " seconds");
2224
2225            // If the platform SDK has changed since the last time we booted,
2226            // we need to re-grant app permission to catch any new ones that
2227            // appear.  This is really a hack, and means that apps can in some
2228            // cases get permissions that the user didn't initially explicitly
2229            // allow...  it would be nice to have some better way to handle
2230            // this situation.
2231            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2232                    != mSdkVersion;
2233            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2234                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2235                    + "; regranting permissions for internal storage");
2236            mSettings.mInternalSdkPlatform = mSdkVersion;
2237
2238            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2239                    | (regrantPermissions
2240                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2241                            : 0));
2242
2243            // If this is the first boot, and it is a normal boot, then
2244            // we need to initialize the default preferred apps.
2245            if (!mRestoredSettings && !onlyCore) {
2246                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2247                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2248            }
2249
2250            // If this is first boot after an OTA, and a normal boot, then
2251            // we need to clear code cache directories.
2252            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2253            if (mIsUpgrade && !onlyCore) {
2254                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2255                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2256                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2257                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2258                }
2259                mSettings.mFingerprint = Build.FINGERPRINT;
2260            }
2261
2262            primeDomainVerificationsLPw();
2263            checkDefaultBrowser();
2264
2265            // All the changes are done during package scanning.
2266            mSettings.updateInternalDatabaseVersion();
2267
2268            // can downgrade to reader
2269            mSettings.writeLPr();
2270
2271            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2272                    SystemClock.uptimeMillis());
2273
2274            mRequiredVerifierPackage = getRequiredVerifierLPr();
2275            mRequiredInstallerPackage = getRequiredInstallerLPr();
2276
2277            mInstallerService = new PackageInstallerService(context, this);
2278
2279            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2280            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2281                    mIntentFilterVerifierComponent);
2282
2283        } // synchronized (mPackages)
2284        } // synchronized (mInstallLock)
2285
2286        // Now after opening every single application zip, make sure they
2287        // are all flushed.  Not really needed, but keeps things nice and
2288        // tidy.
2289        Runtime.getRuntime().gc();
2290
2291        // Expose private service for system components to use.
2292        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2293    }
2294
2295    @Override
2296    public boolean isFirstBoot() {
2297        return !mRestoredSettings;
2298    }
2299
2300    @Override
2301    public boolean isOnlyCoreApps() {
2302        return mOnlyCore;
2303    }
2304
2305    @Override
2306    public boolean isUpgrade() {
2307        return mIsUpgrade;
2308    }
2309
2310    private String getRequiredVerifierLPr() {
2311        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2312        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2313                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2314
2315        String requiredVerifier = null;
2316
2317        final int N = receivers.size();
2318        for (int i = 0; i < N; i++) {
2319            final ResolveInfo info = receivers.get(i);
2320
2321            if (info.activityInfo == null) {
2322                continue;
2323            }
2324
2325            final String packageName = info.activityInfo.packageName;
2326
2327            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2328                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2329                continue;
2330            }
2331
2332            if (requiredVerifier != null) {
2333                throw new RuntimeException("There can be only one required verifier");
2334            }
2335
2336            requiredVerifier = packageName;
2337        }
2338
2339        return requiredVerifier;
2340    }
2341
2342    private String getRequiredInstallerLPr() {
2343        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2344        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2345        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2346
2347        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2348                PACKAGE_MIME_TYPE, 0, 0);
2349
2350        String requiredInstaller = null;
2351
2352        final int N = installers.size();
2353        for (int i = 0; i < N; i++) {
2354            final ResolveInfo info = installers.get(i);
2355            final String packageName = info.activityInfo.packageName;
2356
2357            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2358                continue;
2359            }
2360
2361            if (requiredInstaller != null) {
2362                throw new RuntimeException("There must be one required installer");
2363            }
2364
2365            requiredInstaller = packageName;
2366        }
2367
2368        if (requiredInstaller == null) {
2369            throw new RuntimeException("There must be one required installer");
2370        }
2371
2372        return requiredInstaller;
2373    }
2374
2375    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2376        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2377        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2378                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2379
2380        ComponentName verifierComponentName = null;
2381
2382        int priority = -1000;
2383        final int N = receivers.size();
2384        for (int i = 0; i < N; i++) {
2385            final ResolveInfo info = receivers.get(i);
2386
2387            if (info.activityInfo == null) {
2388                continue;
2389            }
2390
2391            final String packageName = info.activityInfo.packageName;
2392
2393            final PackageSetting ps = mSettings.mPackages.get(packageName);
2394            if (ps == null) {
2395                continue;
2396            }
2397
2398            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2399                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2400                continue;
2401            }
2402
2403            // Select the IntentFilterVerifier with the highest priority
2404            if (priority < info.priority) {
2405                priority = info.priority;
2406                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2407                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2408                        + verifierComponentName + " with priority: " + info.priority);
2409            }
2410        }
2411
2412        return verifierComponentName;
2413    }
2414
2415    private void primeDomainVerificationsLPw() {
2416        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2417        boolean updated = false;
2418        ArraySet<String> allHostsSet = new ArraySet<>();
2419        for (PackageParser.Package pkg : mPackages.values()) {
2420            final String packageName = pkg.packageName;
2421            if (!hasDomainURLs(pkg)) {
2422                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2423                            "package with no domain URLs: " + packageName);
2424                continue;
2425            }
2426            if (!pkg.isSystemApp()) {
2427                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2428                        "No priming domain verifications for a non system package : " +
2429                                packageName);
2430                continue;
2431            }
2432            for (PackageParser.Activity a : pkg.activities) {
2433                for (ActivityIntentInfo filter : a.intents) {
2434                    if (hasValidDomains(filter)) {
2435                        allHostsSet.addAll(filter.getHostsList());
2436                    }
2437                }
2438            }
2439            if (allHostsSet.size() == 0) {
2440                allHostsSet.add("*");
2441            }
2442            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2443            IntentFilterVerificationInfo ivi =
2444                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2445            if (ivi != null) {
2446                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2447                        "Priming domain verifications for package: " + packageName +
2448                        " with hosts:" + ivi.getDomainsString());
2449                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2450                updated = true;
2451            }
2452            else {
2453                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2454                        "No priming domain verifications for package: " + packageName);
2455            }
2456            allHostsSet.clear();
2457        }
2458        if (updated) {
2459            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2460                    "Will need to write primed domain verifications");
2461        }
2462        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2463    }
2464
2465    private void applyFactoryDefaultBrowserLPw(int userId) {
2466        // The default browser app's package name is stored in a string resource,
2467        // with a product-specific overlay used for vendor customization.
2468        String browserPkg = mContext.getResources().getString(
2469                com.android.internal.R.string.default_browser);
2470        if (browserPkg != null) {
2471            // non-empty string => required to be a known package
2472            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2473            if (ps == null) {
2474                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2475                browserPkg = null;
2476            } else {
2477                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2478            }
2479        }
2480
2481        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2482        // default.  If there's more than one, just leave everything alone.
2483        if (browserPkg == null) {
2484            calculateDefaultBrowserLPw(userId);
2485        }
2486    }
2487
2488    private void calculateDefaultBrowserLPw(int userId) {
2489        List<String> allBrowsers = resolveAllBrowserApps(userId);
2490        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2491        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2492    }
2493
2494    private List<String> resolveAllBrowserApps(int userId) {
2495        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2496        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2497                PackageManager.MATCH_ALL, userId);
2498
2499        final int count = list.size();
2500        List<String> result = new ArrayList<String>(count);
2501        for (int i=0; i<count; i++) {
2502            ResolveInfo info = list.get(i);
2503            if (info.activityInfo == null
2504                    || !info.handleAllWebDataURI
2505                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2506                    || result.contains(info.activityInfo.packageName)) {
2507                continue;
2508            }
2509            result.add(info.activityInfo.packageName);
2510        }
2511
2512        return result;
2513    }
2514
2515    private boolean packageIsBrowser(String packageName, int userId) {
2516        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2517                PackageManager.MATCH_ALL, userId);
2518        final int N = list.size();
2519        for (int i = 0; i < N; i++) {
2520            ResolveInfo info = list.get(i);
2521            if (packageName.equals(info.activityInfo.packageName)) {
2522                return true;
2523            }
2524        }
2525        return false;
2526    }
2527
2528    private void checkDefaultBrowser() {
2529        final int myUserId = UserHandle.myUserId();
2530        final String packageName = getDefaultBrowserPackageName(myUserId);
2531        if (packageName != null) {
2532            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2533            if (info == null) {
2534                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2535                synchronized (mPackages) {
2536                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2537                }
2538            }
2539        }
2540    }
2541
2542    @Override
2543    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2544            throws RemoteException {
2545        try {
2546            return super.onTransact(code, data, reply, flags);
2547        } catch (RuntimeException e) {
2548            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2549                Slog.wtf(TAG, "Package Manager Crash", e);
2550            }
2551            throw e;
2552        }
2553    }
2554
2555    void cleanupInstallFailedPackage(PackageSetting ps) {
2556        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2557
2558        removeDataDirsLI(ps.volumeUuid, ps.name);
2559        if (ps.codePath != null) {
2560            if (ps.codePath.isDirectory()) {
2561                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2562            } else {
2563                ps.codePath.delete();
2564            }
2565        }
2566        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2567            if (ps.resourcePath.isDirectory()) {
2568                FileUtils.deleteContents(ps.resourcePath);
2569            }
2570            ps.resourcePath.delete();
2571        }
2572        mSettings.removePackageLPw(ps.name);
2573    }
2574
2575    static int[] appendInts(int[] cur, int[] add) {
2576        if (add == null) return cur;
2577        if (cur == null) return add;
2578        final int N = add.length;
2579        for (int i=0; i<N; i++) {
2580            cur = appendInt(cur, add[i]);
2581        }
2582        return cur;
2583    }
2584
2585    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2586        if (!sUserManager.exists(userId)) return null;
2587        final PackageSetting ps = (PackageSetting) p.mExtras;
2588        if (ps == null) {
2589            return null;
2590        }
2591
2592        final PermissionsState permissionsState = ps.getPermissionsState();
2593
2594        final int[] gids = permissionsState.computeGids(userId);
2595        final Set<String> permissions = permissionsState.getPermissions(userId);
2596        final PackageUserState state = ps.readUserState(userId);
2597
2598        return PackageParser.generatePackageInfo(p, gids, flags,
2599                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2600    }
2601
2602    @Override
2603    public boolean isPackageFrozen(String packageName) {
2604        synchronized (mPackages) {
2605            final PackageSetting ps = mSettings.mPackages.get(packageName);
2606            if (ps != null) {
2607                return ps.frozen;
2608            }
2609        }
2610        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2611        return true;
2612    }
2613
2614    @Override
2615    public boolean isPackageAvailable(String packageName, int userId) {
2616        if (!sUserManager.exists(userId)) return false;
2617        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2618        synchronized (mPackages) {
2619            PackageParser.Package p = mPackages.get(packageName);
2620            if (p != null) {
2621                final PackageSetting ps = (PackageSetting) p.mExtras;
2622                if (ps != null) {
2623                    final PackageUserState state = ps.readUserState(userId);
2624                    if (state != null) {
2625                        return PackageParser.isAvailable(state);
2626                    }
2627                }
2628            }
2629        }
2630        return false;
2631    }
2632
2633    @Override
2634    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2635        if (!sUserManager.exists(userId)) return null;
2636        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2637        // reader
2638        synchronized (mPackages) {
2639            PackageParser.Package p = mPackages.get(packageName);
2640            if (DEBUG_PACKAGE_INFO)
2641                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2642            if (p != null) {
2643                return generatePackageInfo(p, flags, userId);
2644            }
2645            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2646                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2647            }
2648        }
2649        return null;
2650    }
2651
2652    @Override
2653    public String[] currentToCanonicalPackageNames(String[] names) {
2654        String[] out = new String[names.length];
2655        // reader
2656        synchronized (mPackages) {
2657            for (int i=names.length-1; i>=0; i--) {
2658                PackageSetting ps = mSettings.mPackages.get(names[i]);
2659                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2660            }
2661        }
2662        return out;
2663    }
2664
2665    @Override
2666    public String[] canonicalToCurrentPackageNames(String[] names) {
2667        String[] out = new String[names.length];
2668        // reader
2669        synchronized (mPackages) {
2670            for (int i=names.length-1; i>=0; i--) {
2671                String cur = mSettings.mRenamedPackages.get(names[i]);
2672                out[i] = cur != null ? cur : names[i];
2673            }
2674        }
2675        return out;
2676    }
2677
2678    @Override
2679    public int getPackageUid(String packageName, int userId) {
2680        if (!sUserManager.exists(userId)) return -1;
2681        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2682
2683        // reader
2684        synchronized (mPackages) {
2685            PackageParser.Package p = mPackages.get(packageName);
2686            if(p != null) {
2687                return UserHandle.getUid(userId, p.applicationInfo.uid);
2688            }
2689            PackageSetting ps = mSettings.mPackages.get(packageName);
2690            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2691                return -1;
2692            }
2693            p = ps.pkg;
2694            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2695        }
2696    }
2697
2698    @Override
2699    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2700        if (!sUserManager.exists(userId)) {
2701            return null;
2702        }
2703
2704        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2705                "getPackageGids");
2706
2707        // reader
2708        synchronized (mPackages) {
2709            PackageParser.Package p = mPackages.get(packageName);
2710            if (DEBUG_PACKAGE_INFO) {
2711                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2712            }
2713            if (p != null) {
2714                PackageSetting ps = (PackageSetting) p.mExtras;
2715                return ps.getPermissionsState().computeGids(userId);
2716            }
2717        }
2718
2719        return null;
2720    }
2721
2722    @Override
2723    public int getMountExternalMode(int uid) {
2724        if (Process.isIsolated(uid)) {
2725            return Zygote.MOUNT_EXTERNAL_NONE;
2726        } else {
2727            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2728                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2729            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2730                return Zygote.MOUNT_EXTERNAL_WRITE;
2731            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2732                return Zygote.MOUNT_EXTERNAL_READ;
2733            } else {
2734                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2735            }
2736        }
2737    }
2738
2739    static PermissionInfo generatePermissionInfo(
2740            BasePermission bp, int flags) {
2741        if (bp.perm != null) {
2742            return PackageParser.generatePermissionInfo(bp.perm, flags);
2743        }
2744        PermissionInfo pi = new PermissionInfo();
2745        pi.name = bp.name;
2746        pi.packageName = bp.sourcePackage;
2747        pi.nonLocalizedLabel = bp.name;
2748        pi.protectionLevel = bp.protectionLevel;
2749        return pi;
2750    }
2751
2752    @Override
2753    public PermissionInfo getPermissionInfo(String name, int flags) {
2754        // reader
2755        synchronized (mPackages) {
2756            final BasePermission p = mSettings.mPermissions.get(name);
2757            if (p != null) {
2758                return generatePermissionInfo(p, flags);
2759            }
2760            return null;
2761        }
2762    }
2763
2764    @Override
2765    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2766        // reader
2767        synchronized (mPackages) {
2768            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2769            for (BasePermission p : mSettings.mPermissions.values()) {
2770                if (group == null) {
2771                    if (p.perm == null || p.perm.info.group == null) {
2772                        out.add(generatePermissionInfo(p, flags));
2773                    }
2774                } else {
2775                    if (p.perm != null && group.equals(p.perm.info.group)) {
2776                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2777                    }
2778                }
2779            }
2780
2781            if (out.size() > 0) {
2782                return out;
2783            }
2784            return mPermissionGroups.containsKey(group) ? out : null;
2785        }
2786    }
2787
2788    @Override
2789    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2790        // reader
2791        synchronized (mPackages) {
2792            return PackageParser.generatePermissionGroupInfo(
2793                    mPermissionGroups.get(name), flags);
2794        }
2795    }
2796
2797    @Override
2798    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2799        // reader
2800        synchronized (mPackages) {
2801            final int N = mPermissionGroups.size();
2802            ArrayList<PermissionGroupInfo> out
2803                    = new ArrayList<PermissionGroupInfo>(N);
2804            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2805                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2806            }
2807            return out;
2808        }
2809    }
2810
2811    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2812            int userId) {
2813        if (!sUserManager.exists(userId)) return null;
2814        PackageSetting ps = mSettings.mPackages.get(packageName);
2815        if (ps != null) {
2816            if (ps.pkg == null) {
2817                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2818                        flags, userId);
2819                if (pInfo != null) {
2820                    return pInfo.applicationInfo;
2821                }
2822                return null;
2823            }
2824            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2825                    ps.readUserState(userId), userId);
2826        }
2827        return null;
2828    }
2829
2830    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2831            int userId) {
2832        if (!sUserManager.exists(userId)) return null;
2833        PackageSetting ps = mSettings.mPackages.get(packageName);
2834        if (ps != null) {
2835            PackageParser.Package pkg = ps.pkg;
2836            if (pkg == null) {
2837                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2838                    return null;
2839                }
2840                // Only data remains, so we aren't worried about code paths
2841                pkg = new PackageParser.Package(packageName);
2842                pkg.applicationInfo.packageName = packageName;
2843                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2844                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2845                pkg.applicationInfo.dataDir = Environment
2846                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2847                        .getAbsolutePath();
2848                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2849                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2850            }
2851            return generatePackageInfo(pkg, flags, userId);
2852        }
2853        return null;
2854    }
2855
2856    @Override
2857    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2858        if (!sUserManager.exists(userId)) return null;
2859        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2860        // writer
2861        synchronized (mPackages) {
2862            PackageParser.Package p = mPackages.get(packageName);
2863            if (DEBUG_PACKAGE_INFO) Log.v(
2864                    TAG, "getApplicationInfo " + packageName
2865                    + ": " + p);
2866            if (p != null) {
2867                PackageSetting ps = mSettings.mPackages.get(packageName);
2868                if (ps == null) return null;
2869                // Note: isEnabledLP() does not apply here - always return info
2870                return PackageParser.generateApplicationInfo(
2871                        p, flags, ps.readUserState(userId), userId);
2872            }
2873            if ("android".equals(packageName)||"system".equals(packageName)) {
2874                return mAndroidApplication;
2875            }
2876            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2877                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2878            }
2879        }
2880        return null;
2881    }
2882
2883    @Override
2884    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2885            final IPackageDataObserver observer) {
2886        mContext.enforceCallingOrSelfPermission(
2887                android.Manifest.permission.CLEAR_APP_CACHE, null);
2888        // Queue up an async operation since clearing cache may take a little while.
2889        mHandler.post(new Runnable() {
2890            public void run() {
2891                mHandler.removeCallbacks(this);
2892                int retCode = -1;
2893                synchronized (mInstallLock) {
2894                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2895                    if (retCode < 0) {
2896                        Slog.w(TAG, "Couldn't clear application caches");
2897                    }
2898                }
2899                if (observer != null) {
2900                    try {
2901                        observer.onRemoveCompleted(null, (retCode >= 0));
2902                    } catch (RemoteException e) {
2903                        Slog.w(TAG, "RemoveException when invoking call back");
2904                    }
2905                }
2906            }
2907        });
2908    }
2909
2910    @Override
2911    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2912            final IntentSender pi) {
2913        mContext.enforceCallingOrSelfPermission(
2914                android.Manifest.permission.CLEAR_APP_CACHE, null);
2915        // Queue up an async operation since clearing cache may take a little while.
2916        mHandler.post(new Runnable() {
2917            public void run() {
2918                mHandler.removeCallbacks(this);
2919                int retCode = -1;
2920                synchronized (mInstallLock) {
2921                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2922                    if (retCode < 0) {
2923                        Slog.w(TAG, "Couldn't clear application caches");
2924                    }
2925                }
2926                if(pi != null) {
2927                    try {
2928                        // Callback via pending intent
2929                        int code = (retCode >= 0) ? 1 : 0;
2930                        pi.sendIntent(null, code, null,
2931                                null, null);
2932                    } catch (SendIntentException e1) {
2933                        Slog.i(TAG, "Failed to send pending intent");
2934                    }
2935                }
2936            }
2937        });
2938    }
2939
2940    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2941        synchronized (mInstallLock) {
2942            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2943                throw new IOException("Failed to free enough space");
2944            }
2945        }
2946    }
2947
2948    @Override
2949    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2950        if (!sUserManager.exists(userId)) return null;
2951        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2952        synchronized (mPackages) {
2953            PackageParser.Activity a = mActivities.mActivities.get(component);
2954
2955            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2956            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2957                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2958                if (ps == null) return null;
2959                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2960                        userId);
2961            }
2962            if (mResolveComponentName.equals(component)) {
2963                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2964                        new PackageUserState(), userId);
2965            }
2966        }
2967        return null;
2968    }
2969
2970    @Override
2971    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2972            String resolvedType) {
2973        synchronized (mPackages) {
2974            PackageParser.Activity a = mActivities.mActivities.get(component);
2975            if (a == null) {
2976                return false;
2977            }
2978            for (int i=0; i<a.intents.size(); i++) {
2979                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2980                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2981                    return true;
2982                }
2983            }
2984            return false;
2985        }
2986    }
2987
2988    @Override
2989    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2990        if (!sUserManager.exists(userId)) return null;
2991        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2992        synchronized (mPackages) {
2993            PackageParser.Activity a = mReceivers.mActivities.get(component);
2994            if (DEBUG_PACKAGE_INFO) Log.v(
2995                TAG, "getReceiverInfo " + component + ": " + a);
2996            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2997                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2998                if (ps == null) return null;
2999                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3000                        userId);
3001            }
3002        }
3003        return null;
3004    }
3005
3006    @Override
3007    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3010        synchronized (mPackages) {
3011            PackageParser.Service s = mServices.mServices.get(component);
3012            if (DEBUG_PACKAGE_INFO) Log.v(
3013                TAG, "getServiceInfo " + component + ": " + s);
3014            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3015                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3016                if (ps == null) return null;
3017                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3018                        userId);
3019            }
3020        }
3021        return null;
3022    }
3023
3024    @Override
3025    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3026        if (!sUserManager.exists(userId)) return null;
3027        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3028        synchronized (mPackages) {
3029            PackageParser.Provider p = mProviders.mProviders.get(component);
3030            if (DEBUG_PACKAGE_INFO) Log.v(
3031                TAG, "getProviderInfo " + component + ": " + p);
3032            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3033                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3034                if (ps == null) return null;
3035                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3036                        userId);
3037            }
3038        }
3039        return null;
3040    }
3041
3042    @Override
3043    public String[] getSystemSharedLibraryNames() {
3044        Set<String> libSet;
3045        synchronized (mPackages) {
3046            libSet = mSharedLibraries.keySet();
3047            int size = libSet.size();
3048            if (size > 0) {
3049                String[] libs = new String[size];
3050                libSet.toArray(libs);
3051                return libs;
3052            }
3053        }
3054        return null;
3055    }
3056
3057    /**
3058     * @hide
3059     */
3060    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3061        synchronized (mPackages) {
3062            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3063            if (lib != null && lib.apk != null) {
3064                return mPackages.get(lib.apk);
3065            }
3066        }
3067        return null;
3068    }
3069
3070    @Override
3071    public FeatureInfo[] getSystemAvailableFeatures() {
3072        Collection<FeatureInfo> featSet;
3073        synchronized (mPackages) {
3074            featSet = mAvailableFeatures.values();
3075            int size = featSet.size();
3076            if (size > 0) {
3077                FeatureInfo[] features = new FeatureInfo[size+1];
3078                featSet.toArray(features);
3079                FeatureInfo fi = new FeatureInfo();
3080                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3081                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3082                features[size] = fi;
3083                return features;
3084            }
3085        }
3086        return null;
3087    }
3088
3089    @Override
3090    public boolean hasSystemFeature(String name) {
3091        synchronized (mPackages) {
3092            return mAvailableFeatures.containsKey(name);
3093        }
3094    }
3095
3096    private void checkValidCaller(int uid, int userId) {
3097        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3098            return;
3099
3100        throw new SecurityException("Caller uid=" + uid
3101                + " is not privileged to communicate with user=" + userId);
3102    }
3103
3104    @Override
3105    public int checkPermission(String permName, String pkgName, int userId) {
3106        if (!sUserManager.exists(userId)) {
3107            return PackageManager.PERMISSION_DENIED;
3108        }
3109
3110        synchronized (mPackages) {
3111            final PackageParser.Package p = mPackages.get(pkgName);
3112            if (p != null && p.mExtras != null) {
3113                final PackageSetting ps = (PackageSetting) p.mExtras;
3114                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3115                    return PackageManager.PERMISSION_GRANTED;
3116                }
3117            }
3118        }
3119
3120        return PackageManager.PERMISSION_DENIED;
3121    }
3122
3123    @Override
3124    public int checkUidPermission(String permName, int uid) {
3125        final int userId = UserHandle.getUserId(uid);
3126
3127        if (!sUserManager.exists(userId)) {
3128            return PackageManager.PERMISSION_DENIED;
3129        }
3130
3131        synchronized (mPackages) {
3132            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3133            if (obj != null) {
3134                final SettingBase ps = (SettingBase) obj;
3135                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3136                    return PackageManager.PERMISSION_GRANTED;
3137                }
3138            } else {
3139                ArraySet<String> perms = mSystemPermissions.get(uid);
3140                if (perms != null && perms.contains(permName)) {
3141                    return PackageManager.PERMISSION_GRANTED;
3142                }
3143            }
3144        }
3145
3146        return PackageManager.PERMISSION_DENIED;
3147    }
3148
3149    /**
3150     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3151     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3152     * @param checkShell TODO(yamasani):
3153     * @param message the message to log on security exception
3154     */
3155    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3156            boolean checkShell, String message) {
3157        if (userId < 0) {
3158            throw new IllegalArgumentException("Invalid userId " + userId);
3159        }
3160        if (checkShell) {
3161            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3162        }
3163        if (userId == UserHandle.getUserId(callingUid)) return;
3164        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3165            if (requireFullPermission) {
3166                mContext.enforceCallingOrSelfPermission(
3167                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3168            } else {
3169                try {
3170                    mContext.enforceCallingOrSelfPermission(
3171                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3172                } catch (SecurityException se) {
3173                    mContext.enforceCallingOrSelfPermission(
3174                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3175                }
3176            }
3177        }
3178    }
3179
3180    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3181        if (callingUid == Process.SHELL_UID) {
3182            if (userHandle >= 0
3183                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3184                throw new SecurityException("Shell does not have permission to access user "
3185                        + userHandle);
3186            } else if (userHandle < 0) {
3187                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3188                        + Debug.getCallers(3));
3189            }
3190        }
3191    }
3192
3193    private BasePermission findPermissionTreeLP(String permName) {
3194        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3195            if (permName.startsWith(bp.name) &&
3196                    permName.length() > bp.name.length() &&
3197                    permName.charAt(bp.name.length()) == '.') {
3198                return bp;
3199            }
3200        }
3201        return null;
3202    }
3203
3204    private BasePermission checkPermissionTreeLP(String permName) {
3205        if (permName != null) {
3206            BasePermission bp = findPermissionTreeLP(permName);
3207            if (bp != null) {
3208                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3209                    return bp;
3210                }
3211                throw new SecurityException("Calling uid "
3212                        + Binder.getCallingUid()
3213                        + " is not allowed to add to permission tree "
3214                        + bp.name + " owned by uid " + bp.uid);
3215            }
3216        }
3217        throw new SecurityException("No permission tree found for " + permName);
3218    }
3219
3220    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3221        if (s1 == null) {
3222            return s2 == null;
3223        }
3224        if (s2 == null) {
3225            return false;
3226        }
3227        if (s1.getClass() != s2.getClass()) {
3228            return false;
3229        }
3230        return s1.equals(s2);
3231    }
3232
3233    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3234        if (pi1.icon != pi2.icon) return false;
3235        if (pi1.logo != pi2.logo) return false;
3236        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3237        if (!compareStrings(pi1.name, pi2.name)) return false;
3238        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3239        // We'll take care of setting this one.
3240        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3241        // These are not currently stored in settings.
3242        //if (!compareStrings(pi1.group, pi2.group)) return false;
3243        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3244        //if (pi1.labelRes != pi2.labelRes) return false;
3245        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3246        return true;
3247    }
3248
3249    int permissionInfoFootprint(PermissionInfo info) {
3250        int size = info.name.length();
3251        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3252        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3253        return size;
3254    }
3255
3256    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3257        int size = 0;
3258        for (BasePermission perm : mSettings.mPermissions.values()) {
3259            if (perm.uid == tree.uid) {
3260                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3261            }
3262        }
3263        return size;
3264    }
3265
3266    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3267        // We calculate the max size of permissions defined by this uid and throw
3268        // if that plus the size of 'info' would exceed our stated maximum.
3269        if (tree.uid != Process.SYSTEM_UID) {
3270            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3271            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3272                throw new SecurityException("Permission tree size cap exceeded");
3273            }
3274        }
3275    }
3276
3277    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3278        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3279            throw new SecurityException("Label must be specified in permission");
3280        }
3281        BasePermission tree = checkPermissionTreeLP(info.name);
3282        BasePermission bp = mSettings.mPermissions.get(info.name);
3283        boolean added = bp == null;
3284        boolean changed = true;
3285        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3286        if (added) {
3287            enforcePermissionCapLocked(info, tree);
3288            bp = new BasePermission(info.name, tree.sourcePackage,
3289                    BasePermission.TYPE_DYNAMIC);
3290        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3291            throw new SecurityException(
3292                    "Not allowed to modify non-dynamic permission "
3293                    + info.name);
3294        } else {
3295            if (bp.protectionLevel == fixedLevel
3296                    && bp.perm.owner.equals(tree.perm.owner)
3297                    && bp.uid == tree.uid
3298                    && comparePermissionInfos(bp.perm.info, info)) {
3299                changed = false;
3300            }
3301        }
3302        bp.protectionLevel = fixedLevel;
3303        info = new PermissionInfo(info);
3304        info.protectionLevel = fixedLevel;
3305        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3306        bp.perm.info.packageName = tree.perm.info.packageName;
3307        bp.uid = tree.uid;
3308        if (added) {
3309            mSettings.mPermissions.put(info.name, bp);
3310        }
3311        if (changed) {
3312            if (!async) {
3313                mSettings.writeLPr();
3314            } else {
3315                scheduleWriteSettingsLocked();
3316            }
3317        }
3318        return added;
3319    }
3320
3321    @Override
3322    public boolean addPermission(PermissionInfo info) {
3323        synchronized (mPackages) {
3324            return addPermissionLocked(info, false);
3325        }
3326    }
3327
3328    @Override
3329    public boolean addPermissionAsync(PermissionInfo info) {
3330        synchronized (mPackages) {
3331            return addPermissionLocked(info, true);
3332        }
3333    }
3334
3335    @Override
3336    public void removePermission(String name) {
3337        synchronized (mPackages) {
3338            checkPermissionTreeLP(name);
3339            BasePermission bp = mSettings.mPermissions.get(name);
3340            if (bp != null) {
3341                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3342                    throw new SecurityException(
3343                            "Not allowed to modify non-dynamic permission "
3344                            + name);
3345                }
3346                mSettings.mPermissions.remove(name);
3347                mSettings.writeLPr();
3348            }
3349        }
3350    }
3351
3352    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3353            BasePermission bp) {
3354        int index = pkg.requestedPermissions.indexOf(bp.name);
3355        if (index == -1) {
3356            throw new SecurityException("Package " + pkg.packageName
3357                    + " has not requested permission " + bp.name);
3358        }
3359        if (!bp.isRuntime()) {
3360            throw new SecurityException("Permission " + bp.name
3361                    + " is not a changeable permission type");
3362        }
3363    }
3364
3365    @Override
3366    public void grantRuntimePermission(String packageName, String name, final int userId) {
3367        if (!sUserManager.exists(userId)) {
3368            Log.e(TAG, "No such user:" + userId);
3369            return;
3370        }
3371
3372        mContext.enforceCallingOrSelfPermission(
3373                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3374                "grantRuntimePermission");
3375
3376        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3377                "grantRuntimePermission");
3378
3379        final int uid;
3380        final SettingBase sb;
3381
3382        synchronized (mPackages) {
3383            final PackageParser.Package pkg = mPackages.get(packageName);
3384            if (pkg == null) {
3385                throw new IllegalArgumentException("Unknown package: " + packageName);
3386            }
3387
3388            final BasePermission bp = mSettings.mPermissions.get(name);
3389            if (bp == null) {
3390                throw new IllegalArgumentException("Unknown permission: " + name);
3391            }
3392
3393            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3394
3395            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3396            sb = (SettingBase) pkg.mExtras;
3397            if (sb == null) {
3398                throw new IllegalArgumentException("Unknown package: " + packageName);
3399            }
3400
3401            final PermissionsState permissionsState = sb.getPermissionsState();
3402
3403            final int flags = permissionsState.getPermissionFlags(name, userId);
3404            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3405                throw new SecurityException("Cannot grant system fixed permission: "
3406                        + name + " for package: " + packageName);
3407            }
3408
3409            final int result = permissionsState.grantRuntimePermission(bp, userId);
3410            switch (result) {
3411                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3412                    return;
3413                }
3414
3415                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3416                    mHandler.post(new Runnable() {
3417                        @Override
3418                        public void run() {
3419                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3420                        }
3421                    });
3422                } break;
3423            }
3424
3425            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3426
3427            // Not critical if that is lost - app has to request again.
3428            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3429        }
3430
3431        if (READ_EXTERNAL_STORAGE.equals(name)
3432                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3433            final long token = Binder.clearCallingIdentity();
3434            try {
3435                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3436                storage.remountUid(uid);
3437            } finally {
3438                Binder.restoreCallingIdentity(token);
3439            }
3440        }
3441    }
3442
3443    @Override
3444    public void revokeRuntimePermission(String packageName, String name, int userId) {
3445        if (!sUserManager.exists(userId)) {
3446            Log.e(TAG, "No such user:" + userId);
3447            return;
3448        }
3449
3450        mContext.enforceCallingOrSelfPermission(
3451                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3452                "revokeRuntimePermission");
3453
3454        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3455                "revokeRuntimePermission");
3456
3457        final SettingBase sb;
3458
3459        synchronized (mPackages) {
3460            final PackageParser.Package pkg = mPackages.get(packageName);
3461            if (pkg == null) {
3462                throw new IllegalArgumentException("Unknown package: " + packageName);
3463            }
3464
3465            final BasePermission bp = mSettings.mPermissions.get(name);
3466            if (bp == null) {
3467                throw new IllegalArgumentException("Unknown permission: " + name);
3468            }
3469
3470            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3471
3472            sb = (SettingBase) pkg.mExtras;
3473            if (sb == null) {
3474                throw new IllegalArgumentException("Unknown package: " + packageName);
3475            }
3476
3477            final PermissionsState permissionsState = sb.getPermissionsState();
3478
3479            final int flags = permissionsState.getPermissionFlags(name, userId);
3480            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3481                throw new SecurityException("Cannot revoke system fixed permission: "
3482                        + name + " for package: " + packageName);
3483            }
3484
3485            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3486                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3487                return;
3488            }
3489
3490            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3491
3492            // Critical, after this call app should never have the permission.
3493            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3494        }
3495
3496        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3497    }
3498
3499    @Override
3500    public void resetRuntimePermissions() {
3501        mContext.enforceCallingOrSelfPermission(
3502                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3503                "revokeRuntimePermission");
3504
3505        int callingUid = Binder.getCallingUid();
3506        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3507            mContext.enforceCallingOrSelfPermission(
3508                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3509                    "resetRuntimePermissions");
3510        }
3511
3512        final int[] userIds;
3513
3514        synchronized (mPackages) {
3515            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3516            final int userCount = UserManagerService.getInstance().getUserIds().length;
3517            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3518        }
3519
3520        for (int userId : userIds) {
3521            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3522        }
3523    }
3524
3525    @Override
3526    public int getPermissionFlags(String name, String packageName, int userId) {
3527        if (!sUserManager.exists(userId)) {
3528            return 0;
3529        }
3530
3531        mContext.enforceCallingOrSelfPermission(
3532                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3533                "getPermissionFlags");
3534
3535        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3536                "getPermissionFlags");
3537
3538        synchronized (mPackages) {
3539            final PackageParser.Package pkg = mPackages.get(packageName);
3540            if (pkg == null) {
3541                throw new IllegalArgumentException("Unknown package: " + packageName);
3542            }
3543
3544            final BasePermission bp = mSettings.mPermissions.get(name);
3545            if (bp == null) {
3546                throw new IllegalArgumentException("Unknown permission: " + name);
3547            }
3548
3549            SettingBase sb = (SettingBase) pkg.mExtras;
3550            if (sb == null) {
3551                throw new IllegalArgumentException("Unknown package: " + packageName);
3552            }
3553
3554            PermissionsState permissionsState = sb.getPermissionsState();
3555            return permissionsState.getPermissionFlags(name, userId);
3556        }
3557    }
3558
3559    @Override
3560    public void updatePermissionFlags(String name, String packageName, int flagMask,
3561            int flagValues, int userId) {
3562        if (!sUserManager.exists(userId)) {
3563            return;
3564        }
3565
3566        mContext.enforceCallingOrSelfPermission(
3567                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3568                "updatePermissionFlags");
3569
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3571                "updatePermissionFlags");
3572
3573        // Only the system can change system fixed flags.
3574        if (getCallingUid() != Process.SYSTEM_UID) {
3575            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3576            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3577        }
3578
3579        synchronized (mPackages) {
3580            final PackageParser.Package pkg = mPackages.get(packageName);
3581            if (pkg == null) {
3582                throw new IllegalArgumentException("Unknown package: " + packageName);
3583            }
3584
3585            final BasePermission bp = mSettings.mPermissions.get(name);
3586            if (bp == null) {
3587                throw new IllegalArgumentException("Unknown permission: " + name);
3588            }
3589
3590            SettingBase sb = (SettingBase) pkg.mExtras;
3591            if (sb == null) {
3592                throw new IllegalArgumentException("Unknown package: " + packageName);
3593            }
3594
3595            PermissionsState permissionsState = sb.getPermissionsState();
3596
3597            // Only the package manager can change flags for system component permissions.
3598            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3599            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3600                return;
3601            }
3602
3603            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3604
3605            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3606                // Install and runtime permissions are stored in different places,
3607                // so figure out what permission changed and persist the change.
3608                if (permissionsState.getInstallPermissionState(name) != null) {
3609                    scheduleWriteSettingsLocked();
3610                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3611                        || hadState) {
3612                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3613                }
3614            }
3615        }
3616    }
3617
3618    /**
3619     * Update the permission flags for all packages and runtime permissions of a user in order
3620     * to allow device or profile owner to remove POLICY_FIXED.
3621     */
3622    @Override
3623    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3624        if (!sUserManager.exists(userId)) {
3625            return;
3626        }
3627
3628        mContext.enforceCallingOrSelfPermission(
3629                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3630                "updatePermissionFlagsForAllApps");
3631
3632        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3633                "updatePermissionFlagsForAllApps");
3634
3635        // Only the system can change system fixed flags.
3636        if (getCallingUid() != Process.SYSTEM_UID) {
3637            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3638            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3639        }
3640
3641        synchronized (mPackages) {
3642            boolean changed = false;
3643            final int packageCount = mPackages.size();
3644            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3645                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3646                SettingBase sb = (SettingBase) pkg.mExtras;
3647                if (sb == null) {
3648                    continue;
3649                }
3650                PermissionsState permissionsState = sb.getPermissionsState();
3651                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3652                        userId, flagMask, flagValues);
3653            }
3654            if (changed) {
3655                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3656            }
3657        }
3658    }
3659
3660    @Override
3661    public boolean shouldShowRequestPermissionRationale(String permissionName,
3662            String packageName, int userId) {
3663        if (UserHandle.getCallingUserId() != userId) {
3664            mContext.enforceCallingPermission(
3665                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3666                    "canShowRequestPermissionRationale for user " + userId);
3667        }
3668
3669        final int uid = getPackageUid(packageName, userId);
3670        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3671            return false;
3672        }
3673
3674        if (checkPermission(permissionName, packageName, userId)
3675                == PackageManager.PERMISSION_GRANTED) {
3676            return false;
3677        }
3678
3679        final int flags;
3680
3681        final long identity = Binder.clearCallingIdentity();
3682        try {
3683            flags = getPermissionFlags(permissionName,
3684                    packageName, userId);
3685        } finally {
3686            Binder.restoreCallingIdentity(identity);
3687        }
3688
3689        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3690                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3691                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3692
3693        if ((flags & fixedFlags) != 0) {
3694            return false;
3695        }
3696
3697        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3698    }
3699
3700    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3701        BasePermission bp = mSettings.mPermissions.get(permission);
3702        if (bp == null) {
3703            throw new SecurityException("Missing " + permission + " permission");
3704        }
3705
3706        SettingBase sb = (SettingBase) pkg.mExtras;
3707        PermissionsState permissionsState = sb.getPermissionsState();
3708
3709        if (permissionsState.grantInstallPermission(bp) !=
3710                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3711            scheduleWriteSettingsLocked();
3712        }
3713    }
3714
3715    @Override
3716    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3717        mContext.enforceCallingOrSelfPermission(
3718                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3719                "addOnPermissionsChangeListener");
3720
3721        synchronized (mPackages) {
3722            mOnPermissionChangeListeners.addListenerLocked(listener);
3723        }
3724    }
3725
3726    @Override
3727    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3728        synchronized (mPackages) {
3729            mOnPermissionChangeListeners.removeListenerLocked(listener);
3730        }
3731    }
3732
3733    @Override
3734    public boolean isProtectedBroadcast(String actionName) {
3735        synchronized (mPackages) {
3736            return mProtectedBroadcasts.contains(actionName);
3737        }
3738    }
3739
3740    @Override
3741    public int checkSignatures(String pkg1, String pkg2) {
3742        synchronized (mPackages) {
3743            final PackageParser.Package p1 = mPackages.get(pkg1);
3744            final PackageParser.Package p2 = mPackages.get(pkg2);
3745            if (p1 == null || p1.mExtras == null
3746                    || p2 == null || p2.mExtras == null) {
3747                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3748            }
3749            return compareSignatures(p1.mSignatures, p2.mSignatures);
3750        }
3751    }
3752
3753    @Override
3754    public int checkUidSignatures(int uid1, int uid2) {
3755        // Map to base uids.
3756        uid1 = UserHandle.getAppId(uid1);
3757        uid2 = UserHandle.getAppId(uid2);
3758        // reader
3759        synchronized (mPackages) {
3760            Signature[] s1;
3761            Signature[] s2;
3762            Object obj = mSettings.getUserIdLPr(uid1);
3763            if (obj != null) {
3764                if (obj instanceof SharedUserSetting) {
3765                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3766                } else if (obj instanceof PackageSetting) {
3767                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3768                } else {
3769                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3770                }
3771            } else {
3772                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3773            }
3774            obj = mSettings.getUserIdLPr(uid2);
3775            if (obj != null) {
3776                if (obj instanceof SharedUserSetting) {
3777                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3778                } else if (obj instanceof PackageSetting) {
3779                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3780                } else {
3781                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3782                }
3783            } else {
3784                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3785            }
3786            return compareSignatures(s1, s2);
3787        }
3788    }
3789
3790    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3791        final long identity = Binder.clearCallingIdentity();
3792        try {
3793            if (sb instanceof SharedUserSetting) {
3794                SharedUserSetting sus = (SharedUserSetting) sb;
3795                final int packageCount = sus.packages.size();
3796                for (int i = 0; i < packageCount; i++) {
3797                    PackageSetting susPs = sus.packages.valueAt(i);
3798                    if (userId == UserHandle.USER_ALL) {
3799                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3800                    } else {
3801                        final int uid = UserHandle.getUid(userId, susPs.appId);
3802                        killUid(uid, reason);
3803                    }
3804                }
3805            } else if (sb instanceof PackageSetting) {
3806                PackageSetting ps = (PackageSetting) sb;
3807                if (userId == UserHandle.USER_ALL) {
3808                    killApplication(ps.pkg.packageName, ps.appId, reason);
3809                } else {
3810                    final int uid = UserHandle.getUid(userId, ps.appId);
3811                    killUid(uid, reason);
3812                }
3813            }
3814        } finally {
3815            Binder.restoreCallingIdentity(identity);
3816        }
3817    }
3818
3819    private static void killUid(int uid, String reason) {
3820        IActivityManager am = ActivityManagerNative.getDefault();
3821        if (am != null) {
3822            try {
3823                am.killUid(uid, reason);
3824            } catch (RemoteException e) {
3825                /* ignore - same process */
3826            }
3827        }
3828    }
3829
3830    /**
3831     * Compares two sets of signatures. Returns:
3832     * <br />
3833     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3834     * <br />
3835     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3836     * <br />
3837     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3838     * <br />
3839     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3840     * <br />
3841     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3842     */
3843    static int compareSignatures(Signature[] s1, Signature[] s2) {
3844        if (s1 == null) {
3845            return s2 == null
3846                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3847                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3848        }
3849
3850        if (s2 == null) {
3851            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3852        }
3853
3854        if (s1.length != s2.length) {
3855            return PackageManager.SIGNATURE_NO_MATCH;
3856        }
3857
3858        // Since both signature sets are of size 1, we can compare without HashSets.
3859        if (s1.length == 1) {
3860            return s1[0].equals(s2[0]) ?
3861                    PackageManager.SIGNATURE_MATCH :
3862                    PackageManager.SIGNATURE_NO_MATCH;
3863        }
3864
3865        ArraySet<Signature> set1 = new ArraySet<Signature>();
3866        for (Signature sig : s1) {
3867            set1.add(sig);
3868        }
3869        ArraySet<Signature> set2 = new ArraySet<Signature>();
3870        for (Signature sig : s2) {
3871            set2.add(sig);
3872        }
3873        // Make sure s2 contains all signatures in s1.
3874        if (set1.equals(set2)) {
3875            return PackageManager.SIGNATURE_MATCH;
3876        }
3877        return PackageManager.SIGNATURE_NO_MATCH;
3878    }
3879
3880    /**
3881     * If the database version for this type of package (internal storage or
3882     * external storage) is less than the version where package signatures
3883     * were updated, return true.
3884     */
3885    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3886        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3887                DatabaseVersion.SIGNATURE_END_ENTITY))
3888                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3889                        DatabaseVersion.SIGNATURE_END_ENTITY));
3890    }
3891
3892    /**
3893     * Used for backward compatibility to make sure any packages with
3894     * certificate chains get upgraded to the new style. {@code existingSigs}
3895     * will be in the old format (since they were stored on disk from before the
3896     * system upgrade) and {@code scannedSigs} will be in the newer format.
3897     */
3898    private int compareSignaturesCompat(PackageSignatures existingSigs,
3899            PackageParser.Package scannedPkg) {
3900        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3901            return PackageManager.SIGNATURE_NO_MATCH;
3902        }
3903
3904        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3905        for (Signature sig : existingSigs.mSignatures) {
3906            existingSet.add(sig);
3907        }
3908        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3909        for (Signature sig : scannedPkg.mSignatures) {
3910            try {
3911                Signature[] chainSignatures = sig.getChainSignatures();
3912                for (Signature chainSig : chainSignatures) {
3913                    scannedCompatSet.add(chainSig);
3914                }
3915            } catch (CertificateEncodingException e) {
3916                scannedCompatSet.add(sig);
3917            }
3918        }
3919        /*
3920         * Make sure the expanded scanned set contains all signatures in the
3921         * existing one.
3922         */
3923        if (scannedCompatSet.equals(existingSet)) {
3924            // Migrate the old signatures to the new scheme.
3925            existingSigs.assignSignatures(scannedPkg.mSignatures);
3926            // The new KeySets will be re-added later in the scanning process.
3927            synchronized (mPackages) {
3928                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3929            }
3930            return PackageManager.SIGNATURE_MATCH;
3931        }
3932        return PackageManager.SIGNATURE_NO_MATCH;
3933    }
3934
3935    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3936        if (isExternal(scannedPkg)) {
3937            return mSettings.isExternalDatabaseVersionOlderThan(
3938                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3939        } else {
3940            return mSettings.isInternalDatabaseVersionOlderThan(
3941                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3942        }
3943    }
3944
3945    private int compareSignaturesRecover(PackageSignatures existingSigs,
3946            PackageParser.Package scannedPkg) {
3947        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3948            return PackageManager.SIGNATURE_NO_MATCH;
3949        }
3950
3951        String msg = null;
3952        try {
3953            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3954                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3955                        + scannedPkg.packageName);
3956                return PackageManager.SIGNATURE_MATCH;
3957            }
3958        } catch (CertificateException e) {
3959            msg = e.getMessage();
3960        }
3961
3962        logCriticalInfo(Log.INFO,
3963                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3964        return PackageManager.SIGNATURE_NO_MATCH;
3965    }
3966
3967    @Override
3968    public String[] getPackagesForUid(int uid) {
3969        uid = UserHandle.getAppId(uid);
3970        // reader
3971        synchronized (mPackages) {
3972            Object obj = mSettings.getUserIdLPr(uid);
3973            if (obj instanceof SharedUserSetting) {
3974                final SharedUserSetting sus = (SharedUserSetting) obj;
3975                final int N = sus.packages.size();
3976                final String[] res = new String[N];
3977                final Iterator<PackageSetting> it = sus.packages.iterator();
3978                int i = 0;
3979                while (it.hasNext()) {
3980                    res[i++] = it.next().name;
3981                }
3982                return res;
3983            } else if (obj instanceof PackageSetting) {
3984                final PackageSetting ps = (PackageSetting) obj;
3985                return new String[] { ps.name };
3986            }
3987        }
3988        return null;
3989    }
3990
3991    @Override
3992    public String getNameForUid(int uid) {
3993        // reader
3994        synchronized (mPackages) {
3995            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3996            if (obj instanceof SharedUserSetting) {
3997                final SharedUserSetting sus = (SharedUserSetting) obj;
3998                return sus.name + ":" + sus.userId;
3999            } else if (obj instanceof PackageSetting) {
4000                final PackageSetting ps = (PackageSetting) obj;
4001                return ps.name;
4002            }
4003        }
4004        return null;
4005    }
4006
4007    @Override
4008    public int getUidForSharedUser(String sharedUserName) {
4009        if(sharedUserName == null) {
4010            return -1;
4011        }
4012        // reader
4013        synchronized (mPackages) {
4014            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4015            if (suid == null) {
4016                return -1;
4017            }
4018            return suid.userId;
4019        }
4020    }
4021
4022    @Override
4023    public int getFlagsForUid(int uid) {
4024        synchronized (mPackages) {
4025            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4026            if (obj instanceof SharedUserSetting) {
4027                final SharedUserSetting sus = (SharedUserSetting) obj;
4028                return sus.pkgFlags;
4029            } else if (obj instanceof PackageSetting) {
4030                final PackageSetting ps = (PackageSetting) obj;
4031                return ps.pkgFlags;
4032            }
4033        }
4034        return 0;
4035    }
4036
4037    @Override
4038    public int getPrivateFlagsForUid(int uid) {
4039        synchronized (mPackages) {
4040            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4041            if (obj instanceof SharedUserSetting) {
4042                final SharedUserSetting sus = (SharedUserSetting) obj;
4043                return sus.pkgPrivateFlags;
4044            } else if (obj instanceof PackageSetting) {
4045                final PackageSetting ps = (PackageSetting) obj;
4046                return ps.pkgPrivateFlags;
4047            }
4048        }
4049        return 0;
4050    }
4051
4052    @Override
4053    public boolean isUidPrivileged(int uid) {
4054        uid = UserHandle.getAppId(uid);
4055        // reader
4056        synchronized (mPackages) {
4057            Object obj = mSettings.getUserIdLPr(uid);
4058            if (obj instanceof SharedUserSetting) {
4059                final SharedUserSetting sus = (SharedUserSetting) obj;
4060                final Iterator<PackageSetting> it = sus.packages.iterator();
4061                while (it.hasNext()) {
4062                    if (it.next().isPrivileged()) {
4063                        return true;
4064                    }
4065                }
4066            } else if (obj instanceof PackageSetting) {
4067                final PackageSetting ps = (PackageSetting) obj;
4068                return ps.isPrivileged();
4069            }
4070        }
4071        return false;
4072    }
4073
4074    @Override
4075    public String[] getAppOpPermissionPackages(String permissionName) {
4076        synchronized (mPackages) {
4077            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4078            if (pkgs == null) {
4079                return null;
4080            }
4081            return pkgs.toArray(new String[pkgs.size()]);
4082        }
4083    }
4084
4085    @Override
4086    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4087            int flags, int userId) {
4088        if (!sUserManager.exists(userId)) return null;
4089        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4090        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4091        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4092    }
4093
4094    @Override
4095    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4096            IntentFilter filter, int match, ComponentName activity) {
4097        final int userId = UserHandle.getCallingUserId();
4098        if (DEBUG_PREFERRED) {
4099            Log.v(TAG, "setLastChosenActivity intent=" + intent
4100                + " resolvedType=" + resolvedType
4101                + " flags=" + flags
4102                + " filter=" + filter
4103                + " match=" + match
4104                + " activity=" + activity);
4105            filter.dump(new PrintStreamPrinter(System.out), "    ");
4106        }
4107        intent.setComponent(null);
4108        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4109        // Find any earlier preferred or last chosen entries and nuke them
4110        findPreferredActivity(intent, resolvedType,
4111                flags, query, 0, false, true, false, userId);
4112        // Add the new activity as the last chosen for this filter
4113        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4114                "Setting last chosen");
4115    }
4116
4117    @Override
4118    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4119        final int userId = UserHandle.getCallingUserId();
4120        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4121        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4122        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4123                false, false, false, userId);
4124    }
4125
4126    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4127            int flags, List<ResolveInfo> query, int userId) {
4128        if (query != null) {
4129            final int N = query.size();
4130            if (N == 1) {
4131                return query.get(0);
4132            } else if (N > 1) {
4133                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4134                // If there is more than one activity with the same priority,
4135                // then let the user decide between them.
4136                ResolveInfo r0 = query.get(0);
4137                ResolveInfo r1 = query.get(1);
4138                if (DEBUG_INTENT_MATCHING || debug) {
4139                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4140                            + r1.activityInfo.name + "=" + r1.priority);
4141                }
4142                // If the first activity has a higher priority, or a different
4143                // default, then it is always desireable to pick it.
4144                if (r0.priority != r1.priority
4145                        || r0.preferredOrder != r1.preferredOrder
4146                        || r0.isDefault != r1.isDefault) {
4147                    return query.get(0);
4148                }
4149                // If we have saved a preference for a preferred activity for
4150                // this Intent, use that.
4151                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4152                        flags, query, r0.priority, true, false, debug, userId);
4153                if (ri != null) {
4154                    return ri;
4155                }
4156                if (userId != 0) {
4157                    ri = new ResolveInfo(mResolveInfo);
4158                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4159                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4160                            ri.activityInfo.applicationInfo);
4161                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4162                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4163                    return ri;
4164                }
4165                return mResolveInfo;
4166            }
4167        }
4168        return null;
4169    }
4170
4171    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4172            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4173        final int N = query.size();
4174        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4175                .get(userId);
4176        // Get the list of persistent preferred activities that handle the intent
4177        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4178        List<PersistentPreferredActivity> pprefs = ppir != null
4179                ? ppir.queryIntent(intent, resolvedType,
4180                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4181                : null;
4182        if (pprefs != null && pprefs.size() > 0) {
4183            final int M = pprefs.size();
4184            for (int i=0; i<M; i++) {
4185                final PersistentPreferredActivity ppa = pprefs.get(i);
4186                if (DEBUG_PREFERRED || debug) {
4187                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4188                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4189                            + "\n  component=" + ppa.mComponent);
4190                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4191                }
4192                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4193                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4194                if (DEBUG_PREFERRED || debug) {
4195                    Slog.v(TAG, "Found persistent preferred activity:");
4196                    if (ai != null) {
4197                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4198                    } else {
4199                        Slog.v(TAG, "  null");
4200                    }
4201                }
4202                if (ai == null) {
4203                    // This previously registered persistent preferred activity
4204                    // component is no longer known. Ignore it and do NOT remove it.
4205                    continue;
4206                }
4207                for (int j=0; j<N; j++) {
4208                    final ResolveInfo ri = query.get(j);
4209                    if (!ri.activityInfo.applicationInfo.packageName
4210                            .equals(ai.applicationInfo.packageName)) {
4211                        continue;
4212                    }
4213                    if (!ri.activityInfo.name.equals(ai.name)) {
4214                        continue;
4215                    }
4216                    //  Found a persistent preference that can handle the intent.
4217                    if (DEBUG_PREFERRED || debug) {
4218                        Slog.v(TAG, "Returning persistent preferred activity: " +
4219                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4220                    }
4221                    return ri;
4222                }
4223            }
4224        }
4225        return null;
4226    }
4227
4228    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4229            List<ResolveInfo> query, int priority, boolean always,
4230            boolean removeMatches, boolean debug, int userId) {
4231        if (!sUserManager.exists(userId)) return null;
4232        // writer
4233        synchronized (mPackages) {
4234            if (intent.getSelector() != null) {
4235                intent = intent.getSelector();
4236            }
4237            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4238
4239            // Try to find a matching persistent preferred activity.
4240            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4241                    debug, userId);
4242
4243            // If a persistent preferred activity matched, use it.
4244            if (pri != null) {
4245                return pri;
4246            }
4247
4248            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4249            // Get the list of preferred activities that handle the intent
4250            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4251            List<PreferredActivity> prefs = pir != null
4252                    ? pir.queryIntent(intent, resolvedType,
4253                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4254                    : null;
4255            if (prefs != null && prefs.size() > 0) {
4256                boolean changed = false;
4257                try {
4258                    // First figure out how good the original match set is.
4259                    // We will only allow preferred activities that came
4260                    // from the same match quality.
4261                    int match = 0;
4262
4263                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4264
4265                    final int N = query.size();
4266                    for (int j=0; j<N; j++) {
4267                        final ResolveInfo ri = query.get(j);
4268                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4269                                + ": 0x" + Integer.toHexString(match));
4270                        if (ri.match > match) {
4271                            match = ri.match;
4272                        }
4273                    }
4274
4275                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4276                            + Integer.toHexString(match));
4277
4278                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4279                    final int M = prefs.size();
4280                    for (int i=0; i<M; i++) {
4281                        final PreferredActivity pa = prefs.get(i);
4282                        if (DEBUG_PREFERRED || debug) {
4283                            Slog.v(TAG, "Checking PreferredActivity ds="
4284                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4285                                    + "\n  component=" + pa.mPref.mComponent);
4286                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4287                        }
4288                        if (pa.mPref.mMatch != match) {
4289                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4290                                    + Integer.toHexString(pa.mPref.mMatch));
4291                            continue;
4292                        }
4293                        // If it's not an "always" type preferred activity and that's what we're
4294                        // looking for, skip it.
4295                        if (always && !pa.mPref.mAlways) {
4296                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4297                            continue;
4298                        }
4299                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4300                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4301                        if (DEBUG_PREFERRED || debug) {
4302                            Slog.v(TAG, "Found preferred activity:");
4303                            if (ai != null) {
4304                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4305                            } else {
4306                                Slog.v(TAG, "  null");
4307                            }
4308                        }
4309                        if (ai == null) {
4310                            // This previously registered preferred activity
4311                            // component is no longer known.  Most likely an update
4312                            // to the app was installed and in the new version this
4313                            // component no longer exists.  Clean it up by removing
4314                            // it from the preferred activities list, and skip it.
4315                            Slog.w(TAG, "Removing dangling preferred activity: "
4316                                    + pa.mPref.mComponent);
4317                            pir.removeFilter(pa);
4318                            changed = true;
4319                            continue;
4320                        }
4321                        for (int j=0; j<N; j++) {
4322                            final ResolveInfo ri = query.get(j);
4323                            if (!ri.activityInfo.applicationInfo.packageName
4324                                    .equals(ai.applicationInfo.packageName)) {
4325                                continue;
4326                            }
4327                            if (!ri.activityInfo.name.equals(ai.name)) {
4328                                continue;
4329                            }
4330
4331                            if (removeMatches) {
4332                                pir.removeFilter(pa);
4333                                changed = true;
4334                                if (DEBUG_PREFERRED) {
4335                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4336                                }
4337                                break;
4338                            }
4339
4340                            // Okay we found a previously set preferred or last chosen app.
4341                            // If the result set is different from when this
4342                            // was created, we need to clear it and re-ask the
4343                            // user their preference, if we're looking for an "always" type entry.
4344                            if (always && !pa.mPref.sameSet(query)) {
4345                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4346                                        + intent + " type " + resolvedType);
4347                                if (DEBUG_PREFERRED) {
4348                                    Slog.v(TAG, "Removing preferred activity since set changed "
4349                                            + pa.mPref.mComponent);
4350                                }
4351                                pir.removeFilter(pa);
4352                                // Re-add the filter as a "last chosen" entry (!always)
4353                                PreferredActivity lastChosen = new PreferredActivity(
4354                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4355                                pir.addFilter(lastChosen);
4356                                changed = true;
4357                                return null;
4358                            }
4359
4360                            // Yay! Either the set matched or we're looking for the last chosen
4361                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4362                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4363                            return ri;
4364                        }
4365                    }
4366                } finally {
4367                    if (changed) {
4368                        if (DEBUG_PREFERRED) {
4369                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4370                        }
4371                        scheduleWritePackageRestrictionsLocked(userId);
4372                    }
4373                }
4374            }
4375        }
4376        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4377        return null;
4378    }
4379
4380    /*
4381     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4382     */
4383    @Override
4384    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4385            int targetUserId) {
4386        mContext.enforceCallingOrSelfPermission(
4387                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4388        List<CrossProfileIntentFilter> matches =
4389                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4390        if (matches != null) {
4391            int size = matches.size();
4392            for (int i = 0; i < size; i++) {
4393                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4394            }
4395        }
4396        if (hasWebURI(intent)) {
4397            // cross-profile app linking works only towards the parent.
4398            final UserInfo parent = getProfileParent(sourceUserId);
4399            synchronized(mPackages) {
4400                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4401                        intent, resolvedType, 0, sourceUserId, parent.id);
4402                return xpDomainInfo != null
4403                        && xpDomainInfo.bestDomainVerificationStatus !=
4404                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4405            }
4406        }
4407        return false;
4408    }
4409
4410    private UserInfo getProfileParent(int userId) {
4411        final long identity = Binder.clearCallingIdentity();
4412        try {
4413            return sUserManager.getProfileParent(userId);
4414        } finally {
4415            Binder.restoreCallingIdentity(identity);
4416        }
4417    }
4418
4419    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4420            String resolvedType, int userId) {
4421        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4422        if (resolver != null) {
4423            return resolver.queryIntent(intent, resolvedType, false, userId);
4424        }
4425        return null;
4426    }
4427
4428    @Override
4429    public List<ResolveInfo> queryIntentActivities(Intent intent,
4430            String resolvedType, int flags, int userId) {
4431        if (!sUserManager.exists(userId)) return Collections.emptyList();
4432        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4433        ComponentName comp = intent.getComponent();
4434        if (comp == null) {
4435            if (intent.getSelector() != null) {
4436                intent = intent.getSelector();
4437                comp = intent.getComponent();
4438            }
4439        }
4440
4441        if (comp != null) {
4442            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4443            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4444            if (ai != null) {
4445                final ResolveInfo ri = new ResolveInfo();
4446                ri.activityInfo = ai;
4447                list.add(ri);
4448            }
4449            return list;
4450        }
4451
4452        // reader
4453        synchronized (mPackages) {
4454            final String pkgName = intent.getPackage();
4455            if (pkgName == null) {
4456                List<CrossProfileIntentFilter> matchingFilters =
4457                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4458                // Check for results that need to skip the current profile.
4459                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4460                        resolvedType, flags, userId);
4461                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4462                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4463                    result.add(xpResolveInfo);
4464                    return filterIfNotPrimaryUser(result, userId);
4465                }
4466
4467                // Check for results in the current profile.
4468                List<ResolveInfo> result = mActivities.queryIntent(
4469                        intent, resolvedType, flags, userId);
4470
4471                // Check for cross profile results.
4472                xpResolveInfo = queryCrossProfileIntents(
4473                        matchingFilters, intent, resolvedType, flags, userId);
4474                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4475                    result.add(xpResolveInfo);
4476                    Collections.sort(result, mResolvePrioritySorter);
4477                }
4478                result = filterIfNotPrimaryUser(result, userId);
4479                if (hasWebURI(intent)) {
4480                    CrossProfileDomainInfo xpDomainInfo = null;
4481                    final UserInfo parent = getProfileParent(userId);
4482                    if (parent != null) {
4483                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4484                                flags, userId, parent.id);
4485                    }
4486                    if (xpDomainInfo != null) {
4487                        if (xpResolveInfo != null) {
4488                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4489                            // in the result.
4490                            result.remove(xpResolveInfo);
4491                        }
4492                        if (result.size() == 0) {
4493                            result.add(xpDomainInfo.resolveInfo);
4494                            return result;
4495                        }
4496                    } else if (result.size() <= 1) {
4497                        return result;
4498                    }
4499                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4500                            xpDomainInfo);
4501                    Collections.sort(result, mResolvePrioritySorter);
4502                }
4503                return result;
4504            }
4505            final PackageParser.Package pkg = mPackages.get(pkgName);
4506            if (pkg != null) {
4507                return filterIfNotPrimaryUser(
4508                        mActivities.queryIntentForPackage(
4509                                intent, resolvedType, flags, pkg.activities, userId),
4510                        userId);
4511            }
4512            return new ArrayList<ResolveInfo>();
4513        }
4514    }
4515
4516    private static class CrossProfileDomainInfo {
4517        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4518        ResolveInfo resolveInfo;
4519        /* Best domain verification status of the activities found in the other profile */
4520        int bestDomainVerificationStatus;
4521    }
4522
4523    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4524            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4525        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4526                sourceUserId)) {
4527            return null;
4528        }
4529        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4530                resolvedType, flags, parentUserId);
4531
4532        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4533            return null;
4534        }
4535        CrossProfileDomainInfo result = null;
4536        int size = resultTargetUser.size();
4537        for (int i = 0; i < size; i++) {
4538            ResolveInfo riTargetUser = resultTargetUser.get(i);
4539            // Intent filter verification is only for filters that specify a host. So don't return
4540            // those that handle all web uris.
4541            if (riTargetUser.handleAllWebDataURI) {
4542                continue;
4543            }
4544            String packageName = riTargetUser.activityInfo.packageName;
4545            PackageSetting ps = mSettings.mPackages.get(packageName);
4546            if (ps == null) {
4547                continue;
4548            }
4549            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4550            if (result == null) {
4551                result = new CrossProfileDomainInfo();
4552                result.resolveInfo =
4553                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4554                result.bestDomainVerificationStatus = status;
4555            } else {
4556                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4557                        result.bestDomainVerificationStatus);
4558            }
4559        }
4560        return result;
4561    }
4562
4563    /**
4564     * Verification statuses are ordered from the worse to the best, except for
4565     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4566     */
4567    private int bestDomainVerificationStatus(int status1, int status2) {
4568        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4569            return status2;
4570        }
4571        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4572            return status1;
4573        }
4574        return (int) MathUtils.max(status1, status2);
4575    }
4576
4577    private boolean isUserEnabled(int userId) {
4578        long callingId = Binder.clearCallingIdentity();
4579        try {
4580            UserInfo userInfo = sUserManager.getUserInfo(userId);
4581            return userInfo != null && userInfo.isEnabled();
4582        } finally {
4583            Binder.restoreCallingIdentity(callingId);
4584        }
4585    }
4586
4587    /**
4588     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4589     *
4590     * @return filtered list
4591     */
4592    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4593        if (userId == UserHandle.USER_OWNER) {
4594            return resolveInfos;
4595        }
4596        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4597            ResolveInfo info = resolveInfos.get(i);
4598            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4599                resolveInfos.remove(i);
4600            }
4601        }
4602        return resolveInfos;
4603    }
4604
4605    private static boolean hasWebURI(Intent intent) {
4606        if (intent.getData() == null) {
4607            return false;
4608        }
4609        final String scheme = intent.getScheme();
4610        if (TextUtils.isEmpty(scheme)) {
4611            return false;
4612        }
4613        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4614    }
4615
4616    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4617            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4618        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4619            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4620                    candidates.size());
4621        }
4622
4623        final int userId = UserHandle.getCallingUserId();
4624        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4625        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4626        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4627        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4628        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4629
4630        synchronized (mPackages) {
4631            final int count = candidates.size();
4632            // First, try to use linked apps. Partition the candidates into four lists:
4633            // one for the final results, one for the "do not use ever", one for "undefined status"
4634            // and finally one for "browser app type".
4635            for (int n=0; n<count; n++) {
4636                ResolveInfo info = candidates.get(n);
4637                String packageName = info.activityInfo.packageName;
4638                PackageSetting ps = mSettings.mPackages.get(packageName);
4639                if (ps != null) {
4640                    // Add to the special match all list (Browser use case)
4641                    if (info.handleAllWebDataURI) {
4642                        matchAllList.add(info);
4643                        continue;
4644                    }
4645                    // Try to get the status from User settings first
4646                    int status = getDomainVerificationStatusLPr(ps, userId);
4647                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4648                        if (DEBUG_DOMAIN_VERIFICATION) {
4649                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4650                        }
4651                        alwaysList.add(info);
4652                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4653                        if (DEBUG_DOMAIN_VERIFICATION) {
4654                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4655                        }
4656                        neverList.add(info);
4657                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4658                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4659                        if (DEBUG_DOMAIN_VERIFICATION) {
4660                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4661                        }
4662                        undefinedList.add(info);
4663                    }
4664                }
4665            }
4666            // First try to add the "always" resolution for the current user if there is any
4667            if (alwaysList.size() > 0) {
4668                result.addAll(alwaysList);
4669            // if there is an "always" for the parent user, add it.
4670            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4671                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4672                result.add(xpDomainInfo.resolveInfo);
4673            } else {
4674                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4675                result.addAll(undefinedList);
4676                if (xpDomainInfo != null && (
4677                        xpDomainInfo.bestDomainVerificationStatus
4678                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4679                        || xpDomainInfo.bestDomainVerificationStatus
4680                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4681                    result.add(xpDomainInfo.resolveInfo);
4682                }
4683                // Also add Browsers (all of them or only the default one)
4684                if ((flags & MATCH_ALL) != 0) {
4685                    result.addAll(matchAllList);
4686                } else {
4687                    // Try to add the Default Browser if we can
4688                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4689                            UserHandle.myUserId());
4690                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4691                        boolean defaultBrowserFound = false;
4692                        final int browserCount = matchAllList.size();
4693                        for (int n=0; n<browserCount; n++) {
4694                            ResolveInfo browser = matchAllList.get(n);
4695                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4696                                result.add(browser);
4697                                defaultBrowserFound = true;
4698                                break;
4699                            }
4700                        }
4701                        if (!defaultBrowserFound) {
4702                            result.addAll(matchAllList);
4703                        }
4704                    } else {
4705                        result.addAll(matchAllList);
4706                    }
4707                }
4708
4709                // If there is nothing selected, add all candidates and remove the ones that the user
4710                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4711                if (result.size() == 0) {
4712                    result.addAll(candidates);
4713                    result.removeAll(neverList);
4714                }
4715            }
4716        }
4717        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4718            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4719                    result.size());
4720            for (ResolveInfo info : result) {
4721                Slog.v(TAG, "  + " + info.activityInfo);
4722            }
4723        }
4724        return result;
4725    }
4726
4727    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4728        int status = ps.getDomainVerificationStatusForUser(userId);
4729        // if none available, get the master status
4730        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4731            if (ps.getIntentFilterVerificationInfo() != null) {
4732                status = ps.getIntentFilterVerificationInfo().getStatus();
4733            }
4734        }
4735        return status;
4736    }
4737
4738    private ResolveInfo querySkipCurrentProfileIntents(
4739            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4740            int flags, int sourceUserId) {
4741        if (matchingFilters != null) {
4742            int size = matchingFilters.size();
4743            for (int i = 0; i < size; i ++) {
4744                CrossProfileIntentFilter filter = matchingFilters.get(i);
4745                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4746                    // Checking if there are activities in the target user that can handle the
4747                    // intent.
4748                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4749                            flags, sourceUserId);
4750                    if (resolveInfo != null) {
4751                        return resolveInfo;
4752                    }
4753                }
4754            }
4755        }
4756        return null;
4757    }
4758
4759    // Return matching ResolveInfo if any for skip current profile intent filters.
4760    private ResolveInfo queryCrossProfileIntents(
4761            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4762            int flags, int sourceUserId) {
4763        if (matchingFilters != null) {
4764            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4765            // match the same intent. For performance reasons, it is better not to
4766            // run queryIntent twice for the same userId
4767            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4768            int size = matchingFilters.size();
4769            for (int i = 0; i < size; i++) {
4770                CrossProfileIntentFilter filter = matchingFilters.get(i);
4771                int targetUserId = filter.getTargetUserId();
4772                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4773                        && !alreadyTriedUserIds.get(targetUserId)) {
4774                    // Checking if there are activities in the target user that can handle the
4775                    // intent.
4776                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4777                            flags, sourceUserId);
4778                    if (resolveInfo != null) return resolveInfo;
4779                    alreadyTriedUserIds.put(targetUserId, true);
4780                }
4781            }
4782        }
4783        return null;
4784    }
4785
4786    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4787            String resolvedType, int flags, int sourceUserId) {
4788        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4789                resolvedType, flags, filter.getTargetUserId());
4790        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4791            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4792        }
4793        return null;
4794    }
4795
4796    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4797            int sourceUserId, int targetUserId) {
4798        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4799        String className;
4800        if (targetUserId == UserHandle.USER_OWNER) {
4801            className = FORWARD_INTENT_TO_USER_OWNER;
4802        } else {
4803            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4804        }
4805        ComponentName forwardingActivityComponentName = new ComponentName(
4806                mAndroidApplication.packageName, className);
4807        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4808                sourceUserId);
4809        if (targetUserId == UserHandle.USER_OWNER) {
4810            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4811            forwardingResolveInfo.noResourceId = true;
4812        }
4813        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4814        forwardingResolveInfo.priority = 0;
4815        forwardingResolveInfo.preferredOrder = 0;
4816        forwardingResolveInfo.match = 0;
4817        forwardingResolveInfo.isDefault = true;
4818        forwardingResolveInfo.filter = filter;
4819        forwardingResolveInfo.targetUserId = targetUserId;
4820        return forwardingResolveInfo;
4821    }
4822
4823    @Override
4824    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4825            Intent[] specifics, String[] specificTypes, Intent intent,
4826            String resolvedType, int flags, int userId) {
4827        if (!sUserManager.exists(userId)) return Collections.emptyList();
4828        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4829                false, "query intent activity options");
4830        final String resultsAction = intent.getAction();
4831
4832        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4833                | PackageManager.GET_RESOLVED_FILTER, userId);
4834
4835        if (DEBUG_INTENT_MATCHING) {
4836            Log.v(TAG, "Query " + intent + ": " + results);
4837        }
4838
4839        int specificsPos = 0;
4840        int N;
4841
4842        // todo: note that the algorithm used here is O(N^2).  This
4843        // isn't a problem in our current environment, but if we start running
4844        // into situations where we have more than 5 or 10 matches then this
4845        // should probably be changed to something smarter...
4846
4847        // First we go through and resolve each of the specific items
4848        // that were supplied, taking care of removing any corresponding
4849        // duplicate items in the generic resolve list.
4850        if (specifics != null) {
4851            for (int i=0; i<specifics.length; i++) {
4852                final Intent sintent = specifics[i];
4853                if (sintent == null) {
4854                    continue;
4855                }
4856
4857                if (DEBUG_INTENT_MATCHING) {
4858                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4859                }
4860
4861                String action = sintent.getAction();
4862                if (resultsAction != null && resultsAction.equals(action)) {
4863                    // If this action was explicitly requested, then don't
4864                    // remove things that have it.
4865                    action = null;
4866                }
4867
4868                ResolveInfo ri = null;
4869                ActivityInfo ai = null;
4870
4871                ComponentName comp = sintent.getComponent();
4872                if (comp == null) {
4873                    ri = resolveIntent(
4874                        sintent,
4875                        specificTypes != null ? specificTypes[i] : null,
4876                            flags, userId);
4877                    if (ri == null) {
4878                        continue;
4879                    }
4880                    if (ri == mResolveInfo) {
4881                        // ACK!  Must do something better with this.
4882                    }
4883                    ai = ri.activityInfo;
4884                    comp = new ComponentName(ai.applicationInfo.packageName,
4885                            ai.name);
4886                } else {
4887                    ai = getActivityInfo(comp, flags, userId);
4888                    if (ai == null) {
4889                        continue;
4890                    }
4891                }
4892
4893                // Look for any generic query activities that are duplicates
4894                // of this specific one, and remove them from the results.
4895                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4896                N = results.size();
4897                int j;
4898                for (j=specificsPos; j<N; j++) {
4899                    ResolveInfo sri = results.get(j);
4900                    if ((sri.activityInfo.name.equals(comp.getClassName())
4901                            && sri.activityInfo.applicationInfo.packageName.equals(
4902                                    comp.getPackageName()))
4903                        || (action != null && sri.filter.matchAction(action))) {
4904                        results.remove(j);
4905                        if (DEBUG_INTENT_MATCHING) Log.v(
4906                            TAG, "Removing duplicate item from " + j
4907                            + " due to specific " + specificsPos);
4908                        if (ri == null) {
4909                            ri = sri;
4910                        }
4911                        j--;
4912                        N--;
4913                    }
4914                }
4915
4916                // Add this specific item to its proper place.
4917                if (ri == null) {
4918                    ri = new ResolveInfo();
4919                    ri.activityInfo = ai;
4920                }
4921                results.add(specificsPos, ri);
4922                ri.specificIndex = i;
4923                specificsPos++;
4924            }
4925        }
4926
4927        // Now we go through the remaining generic results and remove any
4928        // duplicate actions that are found here.
4929        N = results.size();
4930        for (int i=specificsPos; i<N-1; i++) {
4931            final ResolveInfo rii = results.get(i);
4932            if (rii.filter == null) {
4933                continue;
4934            }
4935
4936            // Iterate over all of the actions of this result's intent
4937            // filter...  typically this should be just one.
4938            final Iterator<String> it = rii.filter.actionsIterator();
4939            if (it == null) {
4940                continue;
4941            }
4942            while (it.hasNext()) {
4943                final String action = it.next();
4944                if (resultsAction != null && resultsAction.equals(action)) {
4945                    // If this action was explicitly requested, then don't
4946                    // remove things that have it.
4947                    continue;
4948                }
4949                for (int j=i+1; j<N; j++) {
4950                    final ResolveInfo rij = results.get(j);
4951                    if (rij.filter != null && rij.filter.hasAction(action)) {
4952                        results.remove(j);
4953                        if (DEBUG_INTENT_MATCHING) Log.v(
4954                            TAG, "Removing duplicate item from " + j
4955                            + " due to action " + action + " at " + i);
4956                        j--;
4957                        N--;
4958                    }
4959                }
4960            }
4961
4962            // If the caller didn't request filter information, drop it now
4963            // so we don't have to marshall/unmarshall it.
4964            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4965                rii.filter = null;
4966            }
4967        }
4968
4969        // Filter out the caller activity if so requested.
4970        if (caller != null) {
4971            N = results.size();
4972            for (int i=0; i<N; i++) {
4973                ActivityInfo ainfo = results.get(i).activityInfo;
4974                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4975                        && caller.getClassName().equals(ainfo.name)) {
4976                    results.remove(i);
4977                    break;
4978                }
4979            }
4980        }
4981
4982        // If the caller didn't request filter information,
4983        // drop them now so we don't have to
4984        // marshall/unmarshall it.
4985        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4986            N = results.size();
4987            for (int i=0; i<N; i++) {
4988                results.get(i).filter = null;
4989            }
4990        }
4991
4992        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4993        return results;
4994    }
4995
4996    @Override
4997    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4998            int userId) {
4999        if (!sUserManager.exists(userId)) return Collections.emptyList();
5000        ComponentName comp = intent.getComponent();
5001        if (comp == null) {
5002            if (intent.getSelector() != null) {
5003                intent = intent.getSelector();
5004                comp = intent.getComponent();
5005            }
5006        }
5007        if (comp != null) {
5008            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5009            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5010            if (ai != null) {
5011                ResolveInfo ri = new ResolveInfo();
5012                ri.activityInfo = ai;
5013                list.add(ri);
5014            }
5015            return list;
5016        }
5017
5018        // reader
5019        synchronized (mPackages) {
5020            String pkgName = intent.getPackage();
5021            if (pkgName == null) {
5022                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5023            }
5024            final PackageParser.Package pkg = mPackages.get(pkgName);
5025            if (pkg != null) {
5026                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5027                        userId);
5028            }
5029            return null;
5030        }
5031    }
5032
5033    @Override
5034    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5035        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5036        if (!sUserManager.exists(userId)) return null;
5037        if (query != null) {
5038            if (query.size() >= 1) {
5039                // If there is more than one service with the same priority,
5040                // just arbitrarily pick the first one.
5041                return query.get(0);
5042            }
5043        }
5044        return null;
5045    }
5046
5047    @Override
5048    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5049            int userId) {
5050        if (!sUserManager.exists(userId)) return Collections.emptyList();
5051        ComponentName comp = intent.getComponent();
5052        if (comp == null) {
5053            if (intent.getSelector() != null) {
5054                intent = intent.getSelector();
5055                comp = intent.getComponent();
5056            }
5057        }
5058        if (comp != null) {
5059            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5060            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5061            if (si != null) {
5062                final ResolveInfo ri = new ResolveInfo();
5063                ri.serviceInfo = si;
5064                list.add(ri);
5065            }
5066            return list;
5067        }
5068
5069        // reader
5070        synchronized (mPackages) {
5071            String pkgName = intent.getPackage();
5072            if (pkgName == null) {
5073                return mServices.queryIntent(intent, resolvedType, flags, userId);
5074            }
5075            final PackageParser.Package pkg = mPackages.get(pkgName);
5076            if (pkg != null) {
5077                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5078                        userId);
5079            }
5080            return null;
5081        }
5082    }
5083
5084    @Override
5085    public List<ResolveInfo> queryIntentContentProviders(
5086            Intent intent, String resolvedType, int flags, int userId) {
5087        if (!sUserManager.exists(userId)) return Collections.emptyList();
5088        ComponentName comp = intent.getComponent();
5089        if (comp == null) {
5090            if (intent.getSelector() != null) {
5091                intent = intent.getSelector();
5092                comp = intent.getComponent();
5093            }
5094        }
5095        if (comp != null) {
5096            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5097            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5098            if (pi != null) {
5099                final ResolveInfo ri = new ResolveInfo();
5100                ri.providerInfo = pi;
5101                list.add(ri);
5102            }
5103            return list;
5104        }
5105
5106        // reader
5107        synchronized (mPackages) {
5108            String pkgName = intent.getPackage();
5109            if (pkgName == null) {
5110                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5111            }
5112            final PackageParser.Package pkg = mPackages.get(pkgName);
5113            if (pkg != null) {
5114                return mProviders.queryIntentForPackage(
5115                        intent, resolvedType, flags, pkg.providers, userId);
5116            }
5117            return null;
5118        }
5119    }
5120
5121    @Override
5122    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5123        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5124
5125        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5126
5127        // writer
5128        synchronized (mPackages) {
5129            ArrayList<PackageInfo> list;
5130            if (listUninstalled) {
5131                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5132                for (PackageSetting ps : mSettings.mPackages.values()) {
5133                    PackageInfo pi;
5134                    if (ps.pkg != null) {
5135                        pi = generatePackageInfo(ps.pkg, flags, userId);
5136                    } else {
5137                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5138                    }
5139                    if (pi != null) {
5140                        list.add(pi);
5141                    }
5142                }
5143            } else {
5144                list = new ArrayList<PackageInfo>(mPackages.size());
5145                for (PackageParser.Package p : mPackages.values()) {
5146                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5147                    if (pi != null) {
5148                        list.add(pi);
5149                    }
5150                }
5151            }
5152
5153            return new ParceledListSlice<PackageInfo>(list);
5154        }
5155    }
5156
5157    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5158            String[] permissions, boolean[] tmp, int flags, int userId) {
5159        int numMatch = 0;
5160        final PermissionsState permissionsState = ps.getPermissionsState();
5161        for (int i=0; i<permissions.length; i++) {
5162            final String permission = permissions[i];
5163            if (permissionsState.hasPermission(permission, userId)) {
5164                tmp[i] = true;
5165                numMatch++;
5166            } else {
5167                tmp[i] = false;
5168            }
5169        }
5170        if (numMatch == 0) {
5171            return;
5172        }
5173        PackageInfo pi;
5174        if (ps.pkg != null) {
5175            pi = generatePackageInfo(ps.pkg, flags, userId);
5176        } else {
5177            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5178        }
5179        // The above might return null in cases of uninstalled apps or install-state
5180        // skew across users/profiles.
5181        if (pi != null) {
5182            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5183                if (numMatch == permissions.length) {
5184                    pi.requestedPermissions = permissions;
5185                } else {
5186                    pi.requestedPermissions = new String[numMatch];
5187                    numMatch = 0;
5188                    for (int i=0; i<permissions.length; i++) {
5189                        if (tmp[i]) {
5190                            pi.requestedPermissions[numMatch] = permissions[i];
5191                            numMatch++;
5192                        }
5193                    }
5194                }
5195            }
5196            list.add(pi);
5197        }
5198    }
5199
5200    @Override
5201    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5202            String[] permissions, int flags, int userId) {
5203        if (!sUserManager.exists(userId)) return null;
5204        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5205
5206        // writer
5207        synchronized (mPackages) {
5208            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5209            boolean[] tmpBools = new boolean[permissions.length];
5210            if (listUninstalled) {
5211                for (PackageSetting ps : mSettings.mPackages.values()) {
5212                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5213                }
5214            } else {
5215                for (PackageParser.Package pkg : mPackages.values()) {
5216                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5217                    if (ps != null) {
5218                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5219                                userId);
5220                    }
5221                }
5222            }
5223
5224            return new ParceledListSlice<PackageInfo>(list);
5225        }
5226    }
5227
5228    @Override
5229    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5230        if (!sUserManager.exists(userId)) return null;
5231        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5232
5233        // writer
5234        synchronized (mPackages) {
5235            ArrayList<ApplicationInfo> list;
5236            if (listUninstalled) {
5237                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5238                for (PackageSetting ps : mSettings.mPackages.values()) {
5239                    ApplicationInfo ai;
5240                    if (ps.pkg != null) {
5241                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5242                                ps.readUserState(userId), userId);
5243                    } else {
5244                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5245                    }
5246                    if (ai != null) {
5247                        list.add(ai);
5248                    }
5249                }
5250            } else {
5251                list = new ArrayList<ApplicationInfo>(mPackages.size());
5252                for (PackageParser.Package p : mPackages.values()) {
5253                    if (p.mExtras != null) {
5254                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5255                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5256                        if (ai != null) {
5257                            list.add(ai);
5258                        }
5259                    }
5260                }
5261            }
5262
5263            return new ParceledListSlice<ApplicationInfo>(list);
5264        }
5265    }
5266
5267    public List<ApplicationInfo> getPersistentApplications(int flags) {
5268        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5269
5270        // reader
5271        synchronized (mPackages) {
5272            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5273            final int userId = UserHandle.getCallingUserId();
5274            while (i.hasNext()) {
5275                final PackageParser.Package p = i.next();
5276                if (p.applicationInfo != null
5277                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5278                        && (!mSafeMode || isSystemApp(p))) {
5279                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5280                    if (ps != null) {
5281                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5282                                ps.readUserState(userId), userId);
5283                        if (ai != null) {
5284                            finalList.add(ai);
5285                        }
5286                    }
5287                }
5288            }
5289        }
5290
5291        return finalList;
5292    }
5293
5294    @Override
5295    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5296        if (!sUserManager.exists(userId)) return null;
5297        // reader
5298        synchronized (mPackages) {
5299            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5300            PackageSetting ps = provider != null
5301                    ? mSettings.mPackages.get(provider.owner.packageName)
5302                    : null;
5303            return ps != null
5304                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5305                    && (!mSafeMode || (provider.info.applicationInfo.flags
5306                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5307                    ? PackageParser.generateProviderInfo(provider, flags,
5308                            ps.readUserState(userId), userId)
5309                    : null;
5310        }
5311    }
5312
5313    /**
5314     * @deprecated
5315     */
5316    @Deprecated
5317    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5318        // reader
5319        synchronized (mPackages) {
5320            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5321                    .entrySet().iterator();
5322            final int userId = UserHandle.getCallingUserId();
5323            while (i.hasNext()) {
5324                Map.Entry<String, PackageParser.Provider> entry = i.next();
5325                PackageParser.Provider p = entry.getValue();
5326                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5327
5328                if (ps != null && p.syncable
5329                        && (!mSafeMode || (p.info.applicationInfo.flags
5330                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5331                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5332                            ps.readUserState(userId), userId);
5333                    if (info != null) {
5334                        outNames.add(entry.getKey());
5335                        outInfo.add(info);
5336                    }
5337                }
5338            }
5339        }
5340    }
5341
5342    @Override
5343    public List<ProviderInfo> queryContentProviders(String processName,
5344            int uid, int flags) {
5345        ArrayList<ProviderInfo> finalList = null;
5346        // reader
5347        synchronized (mPackages) {
5348            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5349            final int userId = processName != null ?
5350                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5351            while (i.hasNext()) {
5352                final PackageParser.Provider p = i.next();
5353                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5354                if (ps != null && p.info.authority != null
5355                        && (processName == null
5356                                || (p.info.processName.equals(processName)
5357                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5358                        && mSettings.isEnabledLPr(p.info, flags, userId)
5359                        && (!mSafeMode
5360                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5361                    if (finalList == null) {
5362                        finalList = new ArrayList<ProviderInfo>(3);
5363                    }
5364                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5365                            ps.readUserState(userId), userId);
5366                    if (info != null) {
5367                        finalList.add(info);
5368                    }
5369                }
5370            }
5371        }
5372
5373        if (finalList != null) {
5374            Collections.sort(finalList, mProviderInitOrderSorter);
5375        }
5376
5377        return finalList;
5378    }
5379
5380    @Override
5381    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5382            int flags) {
5383        // reader
5384        synchronized (mPackages) {
5385            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5386            return PackageParser.generateInstrumentationInfo(i, flags);
5387        }
5388    }
5389
5390    @Override
5391    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5392            int flags) {
5393        ArrayList<InstrumentationInfo> finalList =
5394            new ArrayList<InstrumentationInfo>();
5395
5396        // reader
5397        synchronized (mPackages) {
5398            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5399            while (i.hasNext()) {
5400                final PackageParser.Instrumentation p = i.next();
5401                if (targetPackage == null
5402                        || targetPackage.equals(p.info.targetPackage)) {
5403                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5404                            flags);
5405                    if (ii != null) {
5406                        finalList.add(ii);
5407                    }
5408                }
5409            }
5410        }
5411
5412        return finalList;
5413    }
5414
5415    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5416        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5417        if (overlays == null) {
5418            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5419            return;
5420        }
5421        for (PackageParser.Package opkg : overlays.values()) {
5422            // Not much to do if idmap fails: we already logged the error
5423            // and we certainly don't want to abort installation of pkg simply
5424            // because an overlay didn't fit properly. For these reasons,
5425            // ignore the return value of createIdmapForPackagePairLI.
5426            createIdmapForPackagePairLI(pkg, opkg);
5427        }
5428    }
5429
5430    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5431            PackageParser.Package opkg) {
5432        if (!opkg.mTrustedOverlay) {
5433            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5434                    opkg.baseCodePath + ": overlay not trusted");
5435            return false;
5436        }
5437        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5438        if (overlaySet == null) {
5439            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5440                    opkg.baseCodePath + " but target package has no known overlays");
5441            return false;
5442        }
5443        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5444        // TODO: generate idmap for split APKs
5445        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5446            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5447                    + opkg.baseCodePath);
5448            return false;
5449        }
5450        PackageParser.Package[] overlayArray =
5451            overlaySet.values().toArray(new PackageParser.Package[0]);
5452        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5453            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5454                return p1.mOverlayPriority - p2.mOverlayPriority;
5455            }
5456        };
5457        Arrays.sort(overlayArray, cmp);
5458
5459        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5460        int i = 0;
5461        for (PackageParser.Package p : overlayArray) {
5462            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5463        }
5464        return true;
5465    }
5466
5467    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5468        final File[] files = dir.listFiles();
5469        if (ArrayUtils.isEmpty(files)) {
5470            Log.d(TAG, "No files in app dir " + dir);
5471            return;
5472        }
5473
5474        if (DEBUG_PACKAGE_SCANNING) {
5475            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5476                    + " flags=0x" + Integer.toHexString(parseFlags));
5477        }
5478
5479        for (File file : files) {
5480            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5481                    && !PackageInstallerService.isStageName(file.getName());
5482            if (!isPackage) {
5483                // Ignore entries which are not packages
5484                continue;
5485            }
5486            try {
5487                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5488                        scanFlags, currentTime, null);
5489            } catch (PackageManagerException e) {
5490                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5491
5492                // Delete invalid userdata apps
5493                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5494                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5495                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5496                    if (file.isDirectory()) {
5497                        mInstaller.rmPackageDir(file.getAbsolutePath());
5498                    } else {
5499                        file.delete();
5500                    }
5501                }
5502            }
5503        }
5504    }
5505
5506    private static File getSettingsProblemFile() {
5507        File dataDir = Environment.getDataDirectory();
5508        File systemDir = new File(dataDir, "system");
5509        File fname = new File(systemDir, "uiderrors.txt");
5510        return fname;
5511    }
5512
5513    static void reportSettingsProblem(int priority, String msg) {
5514        logCriticalInfo(priority, msg);
5515    }
5516
5517    static void logCriticalInfo(int priority, String msg) {
5518        Slog.println(priority, TAG, msg);
5519        EventLogTags.writePmCriticalInfo(msg);
5520        try {
5521            File fname = getSettingsProblemFile();
5522            FileOutputStream out = new FileOutputStream(fname, true);
5523            PrintWriter pw = new FastPrintWriter(out);
5524            SimpleDateFormat formatter = new SimpleDateFormat();
5525            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5526            pw.println(dateString + ": " + msg);
5527            pw.close();
5528            FileUtils.setPermissions(
5529                    fname.toString(),
5530                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5531                    -1, -1);
5532        } catch (java.io.IOException e) {
5533        }
5534    }
5535
5536    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5537            PackageParser.Package pkg, File srcFile, int parseFlags)
5538            throws PackageManagerException {
5539        if (ps != null
5540                && ps.codePath.equals(srcFile)
5541                && ps.timeStamp == srcFile.lastModified()
5542                && !isCompatSignatureUpdateNeeded(pkg)
5543                && !isRecoverSignatureUpdateNeeded(pkg)) {
5544            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5545            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5546            ArraySet<PublicKey> signingKs;
5547            synchronized (mPackages) {
5548                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5549            }
5550            if (ps.signatures.mSignatures != null
5551                    && ps.signatures.mSignatures.length != 0
5552                    && signingKs != null) {
5553                // Optimization: reuse the existing cached certificates
5554                // if the package appears to be unchanged.
5555                pkg.mSignatures = ps.signatures.mSignatures;
5556                pkg.mSigningKeys = signingKs;
5557                return;
5558            }
5559
5560            Slog.w(TAG, "PackageSetting for " + ps.name
5561                    + " is missing signatures.  Collecting certs again to recover them.");
5562        } else {
5563            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5564        }
5565
5566        try {
5567            pp.collectCertificates(pkg, parseFlags);
5568            pp.collectManifestDigest(pkg);
5569        } catch (PackageParserException e) {
5570            throw PackageManagerException.from(e);
5571        }
5572    }
5573
5574    /*
5575     *  Scan a package and return the newly parsed package.
5576     *  Returns null in case of errors and the error code is stored in mLastScanError
5577     */
5578    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5579            long currentTime, UserHandle user) throws PackageManagerException {
5580        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5581        parseFlags |= mDefParseFlags;
5582        PackageParser pp = new PackageParser();
5583        pp.setSeparateProcesses(mSeparateProcesses);
5584        pp.setOnlyCoreApps(mOnlyCore);
5585        pp.setDisplayMetrics(mMetrics);
5586
5587        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5588            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5589        }
5590
5591        final PackageParser.Package pkg;
5592        try {
5593            pkg = pp.parsePackage(scanFile, parseFlags);
5594        } catch (PackageParserException e) {
5595            throw PackageManagerException.from(e);
5596        }
5597
5598        PackageSetting ps = null;
5599        PackageSetting updatedPkg;
5600        // reader
5601        synchronized (mPackages) {
5602            // Look to see if we already know about this package.
5603            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5604            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5605                // This package has been renamed to its original name.  Let's
5606                // use that.
5607                ps = mSettings.peekPackageLPr(oldName);
5608            }
5609            // If there was no original package, see one for the real package name.
5610            if (ps == null) {
5611                ps = mSettings.peekPackageLPr(pkg.packageName);
5612            }
5613            // Check to see if this package could be hiding/updating a system
5614            // package.  Must look for it either under the original or real
5615            // package name depending on our state.
5616            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5617            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5618        }
5619        boolean updatedPkgBetter = false;
5620        // First check if this is a system package that may involve an update
5621        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5622            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5623            // it needs to drop FLAG_PRIVILEGED.
5624            if (locationIsPrivileged(scanFile)) {
5625                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5626            } else {
5627                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5628            }
5629
5630            if (ps != null && !ps.codePath.equals(scanFile)) {
5631                // The path has changed from what was last scanned...  check the
5632                // version of the new path against what we have stored to determine
5633                // what to do.
5634                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5635                if (pkg.mVersionCode <= ps.versionCode) {
5636                    // The system package has been updated and the code path does not match
5637                    // Ignore entry. Skip it.
5638                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5639                            + " ignored: updated version " + ps.versionCode
5640                            + " better than this " + pkg.mVersionCode);
5641                    if (!updatedPkg.codePath.equals(scanFile)) {
5642                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5643                                + ps.name + " changing from " + updatedPkg.codePathString
5644                                + " to " + scanFile);
5645                        updatedPkg.codePath = scanFile;
5646                        updatedPkg.codePathString = scanFile.toString();
5647                        updatedPkg.resourcePath = scanFile;
5648                        updatedPkg.resourcePathString = scanFile.toString();
5649                    }
5650                    updatedPkg.pkg = pkg;
5651                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5652                } else {
5653                    // The current app on the system partition is better than
5654                    // what we have updated to on the data partition; switch
5655                    // back to the system partition version.
5656                    // At this point, its safely assumed that package installation for
5657                    // apps in system partition will go through. If not there won't be a working
5658                    // version of the app
5659                    // writer
5660                    synchronized (mPackages) {
5661                        // Just remove the loaded entries from package lists.
5662                        mPackages.remove(ps.name);
5663                    }
5664
5665                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5666                            + " reverting from " + ps.codePathString
5667                            + ": new version " + pkg.mVersionCode
5668                            + " better than installed " + ps.versionCode);
5669
5670                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5671                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5672                    synchronized (mInstallLock) {
5673                        args.cleanUpResourcesLI();
5674                    }
5675                    synchronized (mPackages) {
5676                        mSettings.enableSystemPackageLPw(ps.name);
5677                    }
5678                    updatedPkgBetter = true;
5679                }
5680            }
5681        }
5682
5683        if (updatedPkg != null) {
5684            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5685            // initially
5686            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5687
5688            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5689            // flag set initially
5690            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5691                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5692            }
5693        }
5694
5695        // Verify certificates against what was last scanned
5696        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5697
5698        /*
5699         * A new system app appeared, but we already had a non-system one of the
5700         * same name installed earlier.
5701         */
5702        boolean shouldHideSystemApp = false;
5703        if (updatedPkg == null && ps != null
5704                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5705            /*
5706             * Check to make sure the signatures match first. If they don't,
5707             * wipe the installed application and its data.
5708             */
5709            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5710                    != PackageManager.SIGNATURE_MATCH) {
5711                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5712                        + " signatures don't match existing userdata copy; removing");
5713                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5714                ps = null;
5715            } else {
5716                /*
5717                 * If the newly-added system app is an older version than the
5718                 * already installed version, hide it. It will be scanned later
5719                 * and re-added like an update.
5720                 */
5721                if (pkg.mVersionCode <= ps.versionCode) {
5722                    shouldHideSystemApp = true;
5723                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5724                            + " but new version " + pkg.mVersionCode + " better than installed "
5725                            + ps.versionCode + "; hiding system");
5726                } else {
5727                    /*
5728                     * The newly found system app is a newer version that the
5729                     * one previously installed. Simply remove the
5730                     * already-installed application and replace it with our own
5731                     * while keeping the application data.
5732                     */
5733                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5734                            + " reverting from " + ps.codePathString + ": new version "
5735                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5736                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5737                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5738                    synchronized (mInstallLock) {
5739                        args.cleanUpResourcesLI();
5740                    }
5741                }
5742            }
5743        }
5744
5745        // The apk is forward locked (not public) if its code and resources
5746        // are kept in different files. (except for app in either system or
5747        // vendor path).
5748        // TODO grab this value from PackageSettings
5749        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5750            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5751                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5752            }
5753        }
5754
5755        // TODO: extend to support forward-locked splits
5756        String resourcePath = null;
5757        String baseResourcePath = null;
5758        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5759            if (ps != null && ps.resourcePathString != null) {
5760                resourcePath = ps.resourcePathString;
5761                baseResourcePath = ps.resourcePathString;
5762            } else {
5763                // Should not happen at all. Just log an error.
5764                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5765            }
5766        } else {
5767            resourcePath = pkg.codePath;
5768            baseResourcePath = pkg.baseCodePath;
5769        }
5770
5771        // Set application objects path explicitly.
5772        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5773        pkg.applicationInfo.setCodePath(pkg.codePath);
5774        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5775        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5776        pkg.applicationInfo.setResourcePath(resourcePath);
5777        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5778        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5779
5780        // Note that we invoke the following method only if we are about to unpack an application
5781        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5782                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5783
5784        /*
5785         * If the system app should be overridden by a previously installed
5786         * data, hide the system app now and let the /data/app scan pick it up
5787         * again.
5788         */
5789        if (shouldHideSystemApp) {
5790            synchronized (mPackages) {
5791                /*
5792                 * We have to grant systems permissions before we hide, because
5793                 * grantPermissions will assume the package update is trying to
5794                 * expand its permissions.
5795                 */
5796                grantPermissionsLPw(pkg, true, pkg.packageName);
5797                mSettings.disableSystemPackageLPw(pkg.packageName);
5798            }
5799        }
5800
5801        return scannedPkg;
5802    }
5803
5804    private static String fixProcessName(String defProcessName,
5805            String processName, int uid) {
5806        if (processName == null) {
5807            return defProcessName;
5808        }
5809        return processName;
5810    }
5811
5812    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5813            throws PackageManagerException {
5814        if (pkgSetting.signatures.mSignatures != null) {
5815            // Already existing package. Make sure signatures match
5816            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5817                    == PackageManager.SIGNATURE_MATCH;
5818            if (!match) {
5819                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5820                        == PackageManager.SIGNATURE_MATCH;
5821            }
5822            if (!match) {
5823                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5824                        == PackageManager.SIGNATURE_MATCH;
5825            }
5826            if (!match) {
5827                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5828                        + pkg.packageName + " signatures do not match the "
5829                        + "previously installed version; ignoring!");
5830            }
5831        }
5832
5833        // Check for shared user signatures
5834        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5835            // Already existing package. Make sure signatures match
5836            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5837                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5838            if (!match) {
5839                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5840                        == PackageManager.SIGNATURE_MATCH;
5841            }
5842            if (!match) {
5843                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5844                        == PackageManager.SIGNATURE_MATCH;
5845            }
5846            if (!match) {
5847                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5848                        "Package " + pkg.packageName
5849                        + " has no signatures that match those in shared user "
5850                        + pkgSetting.sharedUser.name + "; ignoring!");
5851            }
5852        }
5853    }
5854
5855    /**
5856     * Enforces that only the system UID or root's UID can call a method exposed
5857     * via Binder.
5858     *
5859     * @param message used as message if SecurityException is thrown
5860     * @throws SecurityException if the caller is not system or root
5861     */
5862    private static final void enforceSystemOrRoot(String message) {
5863        final int uid = Binder.getCallingUid();
5864        if (uid != Process.SYSTEM_UID && uid != 0) {
5865            throw new SecurityException(message);
5866        }
5867    }
5868
5869    @Override
5870    public void performBootDexOpt() {
5871        enforceSystemOrRoot("Only the system can request dexopt be performed");
5872
5873        // Before everything else, see whether we need to fstrim.
5874        try {
5875            IMountService ms = PackageHelper.getMountService();
5876            if (ms != null) {
5877                final boolean isUpgrade = isUpgrade();
5878                boolean doTrim = isUpgrade;
5879                if (doTrim) {
5880                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5881                } else {
5882                    final long interval = android.provider.Settings.Global.getLong(
5883                            mContext.getContentResolver(),
5884                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5885                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5886                    if (interval > 0) {
5887                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5888                        if (timeSinceLast > interval) {
5889                            doTrim = true;
5890                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5891                                    + "; running immediately");
5892                        }
5893                    }
5894                }
5895                if (doTrim) {
5896                    if (!isFirstBoot()) {
5897                        try {
5898                            ActivityManagerNative.getDefault().showBootMessage(
5899                                    mContext.getResources().getString(
5900                                            R.string.android_upgrading_fstrim), true);
5901                        } catch (RemoteException e) {
5902                        }
5903                    }
5904                    ms.runMaintenance();
5905                }
5906            } else {
5907                Slog.e(TAG, "Mount service unavailable!");
5908            }
5909        } catch (RemoteException e) {
5910            // Can't happen; MountService is local
5911        }
5912
5913        final ArraySet<PackageParser.Package> pkgs;
5914        synchronized (mPackages) {
5915            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5916        }
5917
5918        if (pkgs != null) {
5919            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5920            // in case the device runs out of space.
5921            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5922            // Give priority to core apps.
5923            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5924                PackageParser.Package pkg = it.next();
5925                if (pkg.coreApp) {
5926                    if (DEBUG_DEXOPT) {
5927                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5928                    }
5929                    sortedPkgs.add(pkg);
5930                    it.remove();
5931                }
5932            }
5933            // Give priority to system apps that listen for pre boot complete.
5934            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5935            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5936            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5937                PackageParser.Package pkg = it.next();
5938                if (pkgNames.contains(pkg.packageName)) {
5939                    if (DEBUG_DEXOPT) {
5940                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5941                    }
5942                    sortedPkgs.add(pkg);
5943                    it.remove();
5944                }
5945            }
5946            // Give priority to system apps.
5947            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5948                PackageParser.Package pkg = it.next();
5949                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5950                    if (DEBUG_DEXOPT) {
5951                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5952                    }
5953                    sortedPkgs.add(pkg);
5954                    it.remove();
5955                }
5956            }
5957            // Give priority to updated system apps.
5958            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5959                PackageParser.Package pkg = it.next();
5960                if (pkg.isUpdatedSystemApp()) {
5961                    if (DEBUG_DEXOPT) {
5962                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5963                    }
5964                    sortedPkgs.add(pkg);
5965                    it.remove();
5966                }
5967            }
5968            // Give priority to apps that listen for boot complete.
5969            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5970            pkgNames = getPackageNamesForIntent(intent);
5971            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5972                PackageParser.Package pkg = it.next();
5973                if (pkgNames.contains(pkg.packageName)) {
5974                    if (DEBUG_DEXOPT) {
5975                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5976                    }
5977                    sortedPkgs.add(pkg);
5978                    it.remove();
5979                }
5980            }
5981            // Filter out packages that aren't recently used.
5982            filterRecentlyUsedApps(pkgs);
5983            // Add all remaining apps.
5984            for (PackageParser.Package pkg : pkgs) {
5985                if (DEBUG_DEXOPT) {
5986                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5987                }
5988                sortedPkgs.add(pkg);
5989            }
5990
5991            // If we want to be lazy, filter everything that wasn't recently used.
5992            if (mLazyDexOpt) {
5993                filterRecentlyUsedApps(sortedPkgs);
5994            }
5995
5996            int i = 0;
5997            int total = sortedPkgs.size();
5998            File dataDir = Environment.getDataDirectory();
5999            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6000            if (lowThreshold == 0) {
6001                throw new IllegalStateException("Invalid low memory threshold");
6002            }
6003            for (PackageParser.Package pkg : sortedPkgs) {
6004                long usableSpace = dataDir.getUsableSpace();
6005                if (usableSpace < lowThreshold) {
6006                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6007                    break;
6008                }
6009                performBootDexOpt(pkg, ++i, total);
6010            }
6011        }
6012    }
6013
6014    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6015        // Filter out packages that aren't recently used.
6016        //
6017        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6018        // should do a full dexopt.
6019        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6020            int total = pkgs.size();
6021            int skipped = 0;
6022            long now = System.currentTimeMillis();
6023            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6024                PackageParser.Package pkg = i.next();
6025                long then = pkg.mLastPackageUsageTimeInMills;
6026                if (then + mDexOptLRUThresholdInMills < now) {
6027                    if (DEBUG_DEXOPT) {
6028                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6029                              ((then == 0) ? "never" : new Date(then)));
6030                    }
6031                    i.remove();
6032                    skipped++;
6033                }
6034            }
6035            if (DEBUG_DEXOPT) {
6036                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6037            }
6038        }
6039    }
6040
6041    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6042        List<ResolveInfo> ris = null;
6043        try {
6044            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6045                    intent, null, 0, UserHandle.USER_OWNER);
6046        } catch (RemoteException e) {
6047        }
6048        ArraySet<String> pkgNames = new ArraySet<String>();
6049        if (ris != null) {
6050            for (ResolveInfo ri : ris) {
6051                pkgNames.add(ri.activityInfo.packageName);
6052            }
6053        }
6054        return pkgNames;
6055    }
6056
6057    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6058        if (DEBUG_DEXOPT) {
6059            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6060        }
6061        if (!isFirstBoot()) {
6062            try {
6063                ActivityManagerNative.getDefault().showBootMessage(
6064                        mContext.getResources().getString(R.string.android_upgrading_apk,
6065                                curr, total), true);
6066            } catch (RemoteException e) {
6067            }
6068        }
6069        PackageParser.Package p = pkg;
6070        synchronized (mInstallLock) {
6071            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6072                    false /* force dex */, false /* defer */, true /* include dependencies */);
6073        }
6074    }
6075
6076    @Override
6077    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6078        return performDexOpt(packageName, instructionSet, false);
6079    }
6080
6081    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6082        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6083        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6084        if (!dexopt && !updateUsage) {
6085            // We aren't going to dexopt or update usage, so bail early.
6086            return false;
6087        }
6088        PackageParser.Package p;
6089        final String targetInstructionSet;
6090        synchronized (mPackages) {
6091            p = mPackages.get(packageName);
6092            if (p == null) {
6093                return false;
6094            }
6095            if (updateUsage) {
6096                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6097            }
6098            mPackageUsage.write(false);
6099            if (!dexopt) {
6100                // We aren't going to dexopt, so bail early.
6101                return false;
6102            }
6103
6104            targetInstructionSet = instructionSet != null ? instructionSet :
6105                    getPrimaryInstructionSet(p.applicationInfo);
6106            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6107                return false;
6108            }
6109        }
6110
6111        synchronized (mInstallLock) {
6112            final String[] instructionSets = new String[] { targetInstructionSet };
6113            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6114                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6115            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6116        }
6117    }
6118
6119    public ArraySet<String> getPackagesThatNeedDexOpt() {
6120        ArraySet<String> pkgs = null;
6121        synchronized (mPackages) {
6122            for (PackageParser.Package p : mPackages.values()) {
6123                if (DEBUG_DEXOPT) {
6124                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6125                }
6126                if (!p.mDexOptPerformed.isEmpty()) {
6127                    continue;
6128                }
6129                if (pkgs == null) {
6130                    pkgs = new ArraySet<String>();
6131                }
6132                pkgs.add(p.packageName);
6133            }
6134        }
6135        return pkgs;
6136    }
6137
6138    public void shutdown() {
6139        mPackageUsage.write(true);
6140    }
6141
6142    @Override
6143    public void forceDexOpt(String packageName) {
6144        enforceSystemOrRoot("forceDexOpt");
6145
6146        PackageParser.Package pkg;
6147        synchronized (mPackages) {
6148            pkg = mPackages.get(packageName);
6149            if (pkg == null) {
6150                throw new IllegalArgumentException("Missing package: " + packageName);
6151            }
6152        }
6153
6154        synchronized (mInstallLock) {
6155            final String[] instructionSets = new String[] {
6156                    getPrimaryInstructionSet(pkg.applicationInfo) };
6157            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6158                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6159            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6160                throw new IllegalStateException("Failed to dexopt: " + res);
6161            }
6162        }
6163    }
6164
6165    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6166        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6167            Slog.w(TAG, "Unable to update from " + oldPkg.name
6168                    + " to " + newPkg.packageName
6169                    + ": old package not in system partition");
6170            return false;
6171        } else if (mPackages.get(oldPkg.name) != null) {
6172            Slog.w(TAG, "Unable to update from " + oldPkg.name
6173                    + " to " + newPkg.packageName
6174                    + ": old package still exists");
6175            return false;
6176        }
6177        return true;
6178    }
6179
6180    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6181        int[] users = sUserManager.getUserIds();
6182        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6183        if (res < 0) {
6184            return res;
6185        }
6186        for (int user : users) {
6187            if (user != 0) {
6188                res = mInstaller.createUserData(volumeUuid, packageName,
6189                        UserHandle.getUid(user, uid), user, seinfo);
6190                if (res < 0) {
6191                    return res;
6192                }
6193            }
6194        }
6195        return res;
6196    }
6197
6198    private int removeDataDirsLI(String volumeUuid, String packageName) {
6199        int[] users = sUserManager.getUserIds();
6200        int res = 0;
6201        for (int user : users) {
6202            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6203            if (resInner < 0) {
6204                res = resInner;
6205            }
6206        }
6207
6208        return res;
6209    }
6210
6211    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6212        int[] users = sUserManager.getUserIds();
6213        int res = 0;
6214        for (int user : users) {
6215            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6216            if (resInner < 0) {
6217                res = resInner;
6218            }
6219        }
6220        return res;
6221    }
6222
6223    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6224            PackageParser.Package changingLib) {
6225        if (file.path != null) {
6226            usesLibraryFiles.add(file.path);
6227            return;
6228        }
6229        PackageParser.Package p = mPackages.get(file.apk);
6230        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6231            // If we are doing this while in the middle of updating a library apk,
6232            // then we need to make sure to use that new apk for determining the
6233            // dependencies here.  (We haven't yet finished committing the new apk
6234            // to the package manager state.)
6235            if (p == null || p.packageName.equals(changingLib.packageName)) {
6236                p = changingLib;
6237            }
6238        }
6239        if (p != null) {
6240            usesLibraryFiles.addAll(p.getAllCodePaths());
6241        }
6242    }
6243
6244    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6245            PackageParser.Package changingLib) throws PackageManagerException {
6246        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6247            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6248            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6249            for (int i=0; i<N; i++) {
6250                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6251                if (file == null) {
6252                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6253                            "Package " + pkg.packageName + " requires unavailable shared library "
6254                            + pkg.usesLibraries.get(i) + "; failing!");
6255                }
6256                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6257            }
6258            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6259            for (int i=0; i<N; i++) {
6260                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6261                if (file == null) {
6262                    Slog.w(TAG, "Package " + pkg.packageName
6263                            + " desires unavailable shared library "
6264                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6265                } else {
6266                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6267                }
6268            }
6269            N = usesLibraryFiles.size();
6270            if (N > 0) {
6271                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6272            } else {
6273                pkg.usesLibraryFiles = null;
6274            }
6275        }
6276    }
6277
6278    private static boolean hasString(List<String> list, List<String> which) {
6279        if (list == null) {
6280            return false;
6281        }
6282        for (int i=list.size()-1; i>=0; i--) {
6283            for (int j=which.size()-1; j>=0; j--) {
6284                if (which.get(j).equals(list.get(i))) {
6285                    return true;
6286                }
6287            }
6288        }
6289        return false;
6290    }
6291
6292    private void updateAllSharedLibrariesLPw() {
6293        for (PackageParser.Package pkg : mPackages.values()) {
6294            try {
6295                updateSharedLibrariesLPw(pkg, null);
6296            } catch (PackageManagerException e) {
6297                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6298            }
6299        }
6300    }
6301
6302    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6303            PackageParser.Package changingPkg) {
6304        ArrayList<PackageParser.Package> res = null;
6305        for (PackageParser.Package pkg : mPackages.values()) {
6306            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6307                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6308                if (res == null) {
6309                    res = new ArrayList<PackageParser.Package>();
6310                }
6311                res.add(pkg);
6312                try {
6313                    updateSharedLibrariesLPw(pkg, changingPkg);
6314                } catch (PackageManagerException e) {
6315                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6316                }
6317            }
6318        }
6319        return res;
6320    }
6321
6322    /**
6323     * Derive the value of the {@code cpuAbiOverride} based on the provided
6324     * value and an optional stored value from the package settings.
6325     */
6326    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6327        String cpuAbiOverride = null;
6328
6329        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6330            cpuAbiOverride = null;
6331        } else if (abiOverride != null) {
6332            cpuAbiOverride = abiOverride;
6333        } else if (settings != null) {
6334            cpuAbiOverride = settings.cpuAbiOverrideString;
6335        }
6336
6337        return cpuAbiOverride;
6338    }
6339
6340    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6341            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6342        boolean success = false;
6343        try {
6344            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6345                    currentTime, user);
6346            success = true;
6347            return res;
6348        } finally {
6349            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6350                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6351            }
6352        }
6353    }
6354
6355    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6356            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6357        final File scanFile = new File(pkg.codePath);
6358        if (pkg.applicationInfo.getCodePath() == null ||
6359                pkg.applicationInfo.getResourcePath() == null) {
6360            // Bail out. The resource and code paths haven't been set.
6361            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6362                    "Code and resource paths haven't been set correctly");
6363        }
6364
6365        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6366            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6367        } else {
6368            // Only allow system apps to be flagged as core apps.
6369            pkg.coreApp = false;
6370        }
6371
6372        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6373            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6374        }
6375
6376        if (mCustomResolverComponentName != null &&
6377                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6378            setUpCustomResolverActivity(pkg);
6379        }
6380
6381        if (pkg.packageName.equals("android")) {
6382            synchronized (mPackages) {
6383                if (mAndroidApplication != null) {
6384                    Slog.w(TAG, "*************************************************");
6385                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6386                    Slog.w(TAG, " file=" + scanFile);
6387                    Slog.w(TAG, "*************************************************");
6388                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6389                            "Core android package being redefined.  Skipping.");
6390                }
6391
6392                // Set up information for our fall-back user intent resolution activity.
6393                mPlatformPackage = pkg;
6394                pkg.mVersionCode = mSdkVersion;
6395                mAndroidApplication = pkg.applicationInfo;
6396
6397                if (!mResolverReplaced) {
6398                    mResolveActivity.applicationInfo = mAndroidApplication;
6399                    mResolveActivity.name = ResolverActivity.class.getName();
6400                    mResolveActivity.packageName = mAndroidApplication.packageName;
6401                    mResolveActivity.processName = "system:ui";
6402                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6403                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6404                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6405                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6406                    mResolveActivity.exported = true;
6407                    mResolveActivity.enabled = true;
6408                    mResolveInfo.activityInfo = mResolveActivity;
6409                    mResolveInfo.priority = 0;
6410                    mResolveInfo.preferredOrder = 0;
6411                    mResolveInfo.match = 0;
6412                    mResolveComponentName = new ComponentName(
6413                            mAndroidApplication.packageName, mResolveActivity.name);
6414                }
6415            }
6416        }
6417
6418        if (DEBUG_PACKAGE_SCANNING) {
6419            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6420                Log.d(TAG, "Scanning package " + pkg.packageName);
6421        }
6422
6423        if (mPackages.containsKey(pkg.packageName)
6424                || mSharedLibraries.containsKey(pkg.packageName)) {
6425            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6426                    "Application package " + pkg.packageName
6427                    + " already installed.  Skipping duplicate.");
6428        }
6429
6430        // If we're only installing presumed-existing packages, require that the
6431        // scanned APK is both already known and at the path previously established
6432        // for it.  Previously unknown packages we pick up normally, but if we have an
6433        // a priori expectation about this package's install presence, enforce it.
6434        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6435            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6436            if (known != null) {
6437                if (DEBUG_PACKAGE_SCANNING) {
6438                    Log.d(TAG, "Examining " + pkg.codePath
6439                            + " and requiring known paths " + known.codePathString
6440                            + " & " + known.resourcePathString);
6441                }
6442                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6443                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6444                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6445                            "Application package " + pkg.packageName
6446                            + " found at " + pkg.applicationInfo.getCodePath()
6447                            + " but expected at " + known.codePathString + "; ignoring.");
6448                }
6449            }
6450        }
6451
6452        // Initialize package source and resource directories
6453        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6454        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6455
6456        SharedUserSetting suid = null;
6457        PackageSetting pkgSetting = null;
6458
6459        if (!isSystemApp(pkg)) {
6460            // Only system apps can use these features.
6461            pkg.mOriginalPackages = null;
6462            pkg.mRealPackage = null;
6463            pkg.mAdoptPermissions = null;
6464        }
6465
6466        // writer
6467        synchronized (mPackages) {
6468            if (pkg.mSharedUserId != null) {
6469                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6470                if (suid == null) {
6471                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6472                            "Creating application package " + pkg.packageName
6473                            + " for shared user failed");
6474                }
6475                if (DEBUG_PACKAGE_SCANNING) {
6476                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6477                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6478                                + "): packages=" + suid.packages);
6479                }
6480            }
6481
6482            // Check if we are renaming from an original package name.
6483            PackageSetting origPackage = null;
6484            String realName = null;
6485            if (pkg.mOriginalPackages != null) {
6486                // This package may need to be renamed to a previously
6487                // installed name.  Let's check on that...
6488                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6489                if (pkg.mOriginalPackages.contains(renamed)) {
6490                    // This package had originally been installed as the
6491                    // original name, and we have already taken care of
6492                    // transitioning to the new one.  Just update the new
6493                    // one to continue using the old name.
6494                    realName = pkg.mRealPackage;
6495                    if (!pkg.packageName.equals(renamed)) {
6496                        // Callers into this function may have already taken
6497                        // care of renaming the package; only do it here if
6498                        // it is not already done.
6499                        pkg.setPackageName(renamed);
6500                    }
6501
6502                } else {
6503                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6504                        if ((origPackage = mSettings.peekPackageLPr(
6505                                pkg.mOriginalPackages.get(i))) != null) {
6506                            // We do have the package already installed under its
6507                            // original name...  should we use it?
6508                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6509                                // New package is not compatible with original.
6510                                origPackage = null;
6511                                continue;
6512                            } else if (origPackage.sharedUser != null) {
6513                                // Make sure uid is compatible between packages.
6514                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6515                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6516                                            + " to " + pkg.packageName + ": old uid "
6517                                            + origPackage.sharedUser.name
6518                                            + " differs from " + pkg.mSharedUserId);
6519                                    origPackage = null;
6520                                    continue;
6521                                }
6522                            } else {
6523                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6524                                        + pkg.packageName + " to old name " + origPackage.name);
6525                            }
6526                            break;
6527                        }
6528                    }
6529                }
6530            }
6531
6532            if (mTransferedPackages.contains(pkg.packageName)) {
6533                Slog.w(TAG, "Package " + pkg.packageName
6534                        + " was transferred to another, but its .apk remains");
6535            }
6536
6537            // Just create the setting, don't add it yet. For already existing packages
6538            // the PkgSetting exists already and doesn't have to be created.
6539            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6540                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6541                    pkg.applicationInfo.primaryCpuAbi,
6542                    pkg.applicationInfo.secondaryCpuAbi,
6543                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6544                    user, false);
6545            if (pkgSetting == null) {
6546                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6547                        "Creating application package " + pkg.packageName + " failed");
6548            }
6549
6550            if (pkgSetting.origPackage != null) {
6551                // If we are first transitioning from an original package,
6552                // fix up the new package's name now.  We need to do this after
6553                // looking up the package under its new name, so getPackageLP
6554                // can take care of fiddling things correctly.
6555                pkg.setPackageName(origPackage.name);
6556
6557                // File a report about this.
6558                String msg = "New package " + pkgSetting.realName
6559                        + " renamed to replace old package " + pkgSetting.name;
6560                reportSettingsProblem(Log.WARN, msg);
6561
6562                // Make a note of it.
6563                mTransferedPackages.add(origPackage.name);
6564
6565                // No longer need to retain this.
6566                pkgSetting.origPackage = null;
6567            }
6568
6569            if (realName != null) {
6570                // Make a note of it.
6571                mTransferedPackages.add(pkg.packageName);
6572            }
6573
6574            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6575                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6576            }
6577
6578            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6579                // Check all shared libraries and map to their actual file path.
6580                // We only do this here for apps not on a system dir, because those
6581                // are the only ones that can fail an install due to this.  We
6582                // will take care of the system apps by updating all of their
6583                // library paths after the scan is done.
6584                updateSharedLibrariesLPw(pkg, null);
6585            }
6586
6587            if (mFoundPolicyFile) {
6588                SELinuxMMAC.assignSeinfoValue(pkg);
6589            }
6590
6591            pkg.applicationInfo.uid = pkgSetting.appId;
6592            pkg.mExtras = pkgSetting;
6593            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6594                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6595                    // We just determined the app is signed correctly, so bring
6596                    // over the latest parsed certs.
6597                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6598                } else {
6599                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6600                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6601                                "Package " + pkg.packageName + " upgrade keys do not match the "
6602                                + "previously installed version");
6603                    } else {
6604                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6605                        String msg = "System package " + pkg.packageName
6606                            + " signature changed; retaining data.";
6607                        reportSettingsProblem(Log.WARN, msg);
6608                    }
6609                }
6610            } else {
6611                try {
6612                    verifySignaturesLP(pkgSetting, pkg);
6613                    // We just determined the app is signed correctly, so bring
6614                    // over the latest parsed certs.
6615                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6616                } catch (PackageManagerException e) {
6617                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6618                        throw e;
6619                    }
6620                    // The signature has changed, but this package is in the system
6621                    // image...  let's recover!
6622                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6623                    // However...  if this package is part of a shared user, but it
6624                    // doesn't match the signature of the shared user, let's fail.
6625                    // What this means is that you can't change the signatures
6626                    // associated with an overall shared user, which doesn't seem all
6627                    // that unreasonable.
6628                    if (pkgSetting.sharedUser != null) {
6629                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6630                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6631                            throw new PackageManagerException(
6632                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6633                                            "Signature mismatch for shared user : "
6634                                            + pkgSetting.sharedUser);
6635                        }
6636                    }
6637                    // File a report about this.
6638                    String msg = "System package " + pkg.packageName
6639                        + " signature changed; retaining data.";
6640                    reportSettingsProblem(Log.WARN, msg);
6641                }
6642            }
6643            // Verify that this new package doesn't have any content providers
6644            // that conflict with existing packages.  Only do this if the
6645            // package isn't already installed, since we don't want to break
6646            // things that are installed.
6647            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6648                final int N = pkg.providers.size();
6649                int i;
6650                for (i=0; i<N; i++) {
6651                    PackageParser.Provider p = pkg.providers.get(i);
6652                    if (p.info.authority != null) {
6653                        String names[] = p.info.authority.split(";");
6654                        for (int j = 0; j < names.length; j++) {
6655                            if (mProvidersByAuthority.containsKey(names[j])) {
6656                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6657                                final String otherPackageName =
6658                                        ((other != null && other.getComponentName() != null) ?
6659                                                other.getComponentName().getPackageName() : "?");
6660                                throw new PackageManagerException(
6661                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6662                                                "Can't install because provider name " + names[j]
6663                                                + " (in package " + pkg.applicationInfo.packageName
6664                                                + ") is already used by " + otherPackageName);
6665                            }
6666                        }
6667                    }
6668                }
6669            }
6670
6671            if (pkg.mAdoptPermissions != null) {
6672                // This package wants to adopt ownership of permissions from
6673                // another package.
6674                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6675                    final String origName = pkg.mAdoptPermissions.get(i);
6676                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6677                    if (orig != null) {
6678                        if (verifyPackageUpdateLPr(orig, pkg)) {
6679                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6680                                    + pkg.packageName);
6681                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6682                        }
6683                    }
6684                }
6685            }
6686        }
6687
6688        final String pkgName = pkg.packageName;
6689
6690        final long scanFileTime = scanFile.lastModified();
6691        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6692        pkg.applicationInfo.processName = fixProcessName(
6693                pkg.applicationInfo.packageName,
6694                pkg.applicationInfo.processName,
6695                pkg.applicationInfo.uid);
6696
6697        File dataPath;
6698        if (mPlatformPackage == pkg) {
6699            // The system package is special.
6700            dataPath = new File(Environment.getDataDirectory(), "system");
6701
6702            pkg.applicationInfo.dataDir = dataPath.getPath();
6703
6704        } else {
6705            // This is a normal package, need to make its data directory.
6706            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6707                    UserHandle.USER_OWNER, pkg.packageName);
6708
6709            boolean uidError = false;
6710            if (dataPath.exists()) {
6711                int currentUid = 0;
6712                try {
6713                    StructStat stat = Os.stat(dataPath.getPath());
6714                    currentUid = stat.st_uid;
6715                } catch (ErrnoException e) {
6716                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6717                }
6718
6719                // If we have mismatched owners for the data path, we have a problem.
6720                if (currentUid != pkg.applicationInfo.uid) {
6721                    boolean recovered = false;
6722                    if (currentUid == 0) {
6723                        // The directory somehow became owned by root.  Wow.
6724                        // This is probably because the system was stopped while
6725                        // installd was in the middle of messing with its libs
6726                        // directory.  Ask installd to fix that.
6727                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6728                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6729                        if (ret >= 0) {
6730                            recovered = true;
6731                            String msg = "Package " + pkg.packageName
6732                                    + " unexpectedly changed to uid 0; recovered to " +
6733                                    + pkg.applicationInfo.uid;
6734                            reportSettingsProblem(Log.WARN, msg);
6735                        }
6736                    }
6737                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6738                            || (scanFlags&SCAN_BOOTING) != 0)) {
6739                        // If this is a system app, we can at least delete its
6740                        // current data so the application will still work.
6741                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6742                        if (ret >= 0) {
6743                            // TODO: Kill the processes first
6744                            // Old data gone!
6745                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6746                                    ? "System package " : "Third party package ";
6747                            String msg = prefix + pkg.packageName
6748                                    + " has changed from uid: "
6749                                    + currentUid + " to "
6750                                    + pkg.applicationInfo.uid + "; old data erased";
6751                            reportSettingsProblem(Log.WARN, msg);
6752                            recovered = true;
6753
6754                            // And now re-install the app.
6755                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6756                                    pkg.applicationInfo.seinfo);
6757                            if (ret == -1) {
6758                                // Ack should not happen!
6759                                msg = prefix + pkg.packageName
6760                                        + " could not have data directory re-created after delete.";
6761                                reportSettingsProblem(Log.WARN, msg);
6762                                throw new PackageManagerException(
6763                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6764                            }
6765                        }
6766                        if (!recovered) {
6767                            mHasSystemUidErrors = true;
6768                        }
6769                    } else if (!recovered) {
6770                        // If we allow this install to proceed, we will be broken.
6771                        // Abort, abort!
6772                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6773                                "scanPackageLI");
6774                    }
6775                    if (!recovered) {
6776                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6777                            + pkg.applicationInfo.uid + "/fs_"
6778                            + currentUid;
6779                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6780                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6781                        String msg = "Package " + pkg.packageName
6782                                + " has mismatched uid: "
6783                                + currentUid + " on disk, "
6784                                + pkg.applicationInfo.uid + " in settings";
6785                        // writer
6786                        synchronized (mPackages) {
6787                            mSettings.mReadMessages.append(msg);
6788                            mSettings.mReadMessages.append('\n');
6789                            uidError = true;
6790                            if (!pkgSetting.uidError) {
6791                                reportSettingsProblem(Log.ERROR, msg);
6792                            }
6793                        }
6794                    }
6795                }
6796                pkg.applicationInfo.dataDir = dataPath.getPath();
6797                if (mShouldRestoreconData) {
6798                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6799                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6800                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6801                }
6802            } else {
6803                if (DEBUG_PACKAGE_SCANNING) {
6804                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6805                        Log.v(TAG, "Want this data dir: " + dataPath);
6806                }
6807                //invoke installer to do the actual installation
6808                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6809                        pkg.applicationInfo.seinfo);
6810                if (ret < 0) {
6811                    // Error from installer
6812                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6813                            "Unable to create data dirs [errorCode=" + ret + "]");
6814                }
6815
6816                if (dataPath.exists()) {
6817                    pkg.applicationInfo.dataDir = dataPath.getPath();
6818                } else {
6819                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6820                    pkg.applicationInfo.dataDir = null;
6821                }
6822            }
6823
6824            pkgSetting.uidError = uidError;
6825        }
6826
6827        final String path = scanFile.getPath();
6828        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6829
6830        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6831            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6832
6833            // Some system apps still use directory structure for native libraries
6834            // in which case we might end up not detecting abi solely based on apk
6835            // structure. Try to detect abi based on directory structure.
6836            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6837                    pkg.applicationInfo.primaryCpuAbi == null) {
6838                setBundledAppAbisAndRoots(pkg, pkgSetting);
6839                setNativeLibraryPaths(pkg);
6840            }
6841
6842        } else {
6843            if ((scanFlags & SCAN_MOVE) != 0) {
6844                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6845                // but we already have this packages package info in the PackageSetting. We just
6846                // use that and derive the native library path based on the new codepath.
6847                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6848                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6849            }
6850
6851            // Set native library paths again. For moves, the path will be updated based on the
6852            // ABIs we've determined above. For non-moves, the path will be updated based on the
6853            // ABIs we determined during compilation, but the path will depend on the final
6854            // package path (after the rename away from the stage path).
6855            setNativeLibraryPaths(pkg);
6856        }
6857
6858        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6859        final int[] userIds = sUserManager.getUserIds();
6860        synchronized (mInstallLock) {
6861            // Make sure all user data directories are ready to roll; we're okay
6862            // if they already exist
6863            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6864                for (int userId : userIds) {
6865                    if (userId != 0) {
6866                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6867                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6868                                pkg.applicationInfo.seinfo);
6869                    }
6870                }
6871            }
6872
6873            // Create a native library symlink only if we have native libraries
6874            // and if the native libraries are 32 bit libraries. We do not provide
6875            // this symlink for 64 bit libraries.
6876            if (pkg.applicationInfo.primaryCpuAbi != null &&
6877                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6878                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6879                for (int userId : userIds) {
6880                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6881                            nativeLibPath, userId) < 0) {
6882                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6883                                "Failed linking native library dir (user=" + userId + ")");
6884                    }
6885                }
6886            }
6887        }
6888
6889        // This is a special case for the "system" package, where the ABI is
6890        // dictated by the zygote configuration (and init.rc). We should keep track
6891        // of this ABI so that we can deal with "normal" applications that run under
6892        // the same UID correctly.
6893        if (mPlatformPackage == pkg) {
6894            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6895                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6896        }
6897
6898        // If there's a mismatch between the abi-override in the package setting
6899        // and the abiOverride specified for the install. Warn about this because we
6900        // would've already compiled the app without taking the package setting into
6901        // account.
6902        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6903            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6904                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6905                        " for package: " + pkg.packageName);
6906            }
6907        }
6908
6909        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6910        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6911        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6912
6913        // Copy the derived override back to the parsed package, so that we can
6914        // update the package settings accordingly.
6915        pkg.cpuAbiOverride = cpuAbiOverride;
6916
6917        if (DEBUG_ABI_SELECTION) {
6918            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6919                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6920                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6921        }
6922
6923        // Push the derived path down into PackageSettings so we know what to
6924        // clean up at uninstall time.
6925        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6926
6927        if (DEBUG_ABI_SELECTION) {
6928            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6929                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6930                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6931        }
6932
6933        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6934            // We don't do this here during boot because we can do it all
6935            // at once after scanning all existing packages.
6936            //
6937            // We also do this *before* we perform dexopt on this package, so that
6938            // we can avoid redundant dexopts, and also to make sure we've got the
6939            // code and package path correct.
6940            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6941                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6942        }
6943
6944        if ((scanFlags & SCAN_NO_DEX) == 0) {
6945            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6946                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6947            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6948                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6949            }
6950        }
6951        if (mFactoryTest && pkg.requestedPermissions.contains(
6952                android.Manifest.permission.FACTORY_TEST)) {
6953            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6954        }
6955
6956        ArrayList<PackageParser.Package> clientLibPkgs = null;
6957
6958        // writer
6959        synchronized (mPackages) {
6960            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6961                // Only system apps can add new shared libraries.
6962                if (pkg.libraryNames != null) {
6963                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6964                        String name = pkg.libraryNames.get(i);
6965                        boolean allowed = false;
6966                        if (pkg.isUpdatedSystemApp()) {
6967                            // New library entries can only be added through the
6968                            // system image.  This is important to get rid of a lot
6969                            // of nasty edge cases: for example if we allowed a non-
6970                            // system update of the app to add a library, then uninstalling
6971                            // the update would make the library go away, and assumptions
6972                            // we made such as through app install filtering would now
6973                            // have allowed apps on the device which aren't compatible
6974                            // with it.  Better to just have the restriction here, be
6975                            // conservative, and create many fewer cases that can negatively
6976                            // impact the user experience.
6977                            final PackageSetting sysPs = mSettings
6978                                    .getDisabledSystemPkgLPr(pkg.packageName);
6979                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6980                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6981                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6982                                        allowed = true;
6983                                        allowed = true;
6984                                        break;
6985                                    }
6986                                }
6987                            }
6988                        } else {
6989                            allowed = true;
6990                        }
6991                        if (allowed) {
6992                            if (!mSharedLibraries.containsKey(name)) {
6993                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6994                            } else if (!name.equals(pkg.packageName)) {
6995                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6996                                        + name + " already exists; skipping");
6997                            }
6998                        } else {
6999                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7000                                    + name + " that is not declared on system image; skipping");
7001                        }
7002                    }
7003                    if ((scanFlags&SCAN_BOOTING) == 0) {
7004                        // If we are not booting, we need to update any applications
7005                        // that are clients of our shared library.  If we are booting,
7006                        // this will all be done once the scan is complete.
7007                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7008                    }
7009                }
7010            }
7011        }
7012
7013        // We also need to dexopt any apps that are dependent on this library.  Note that
7014        // if these fail, we should abort the install since installing the library will
7015        // result in some apps being broken.
7016        if (clientLibPkgs != null) {
7017            if ((scanFlags & SCAN_NO_DEX) == 0) {
7018                for (int i = 0; i < clientLibPkgs.size(); i++) {
7019                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7020                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7021                            null /* instruction sets */, forceDex,
7022                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7023                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7024                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7025                                "scanPackageLI failed to dexopt clientLibPkgs");
7026                    }
7027                }
7028            }
7029        }
7030
7031        // Also need to kill any apps that are dependent on the library.
7032        if (clientLibPkgs != null) {
7033            for (int i=0; i<clientLibPkgs.size(); i++) {
7034                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7035                killApplication(clientPkg.applicationInfo.packageName,
7036                        clientPkg.applicationInfo.uid, "update lib");
7037            }
7038        }
7039
7040        // Make sure we're not adding any bogus keyset info
7041        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7042        ksms.assertScannedPackageValid(pkg);
7043
7044        // writer
7045        synchronized (mPackages) {
7046            // We don't expect installation to fail beyond this point
7047
7048            // Add the new setting to mSettings
7049            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7050            // Add the new setting to mPackages
7051            mPackages.put(pkg.applicationInfo.packageName, pkg);
7052            // Make sure we don't accidentally delete its data.
7053            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7054            while (iter.hasNext()) {
7055                PackageCleanItem item = iter.next();
7056                if (pkgName.equals(item.packageName)) {
7057                    iter.remove();
7058                }
7059            }
7060
7061            // Take care of first install / last update times.
7062            if (currentTime != 0) {
7063                if (pkgSetting.firstInstallTime == 0) {
7064                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7065                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7066                    pkgSetting.lastUpdateTime = currentTime;
7067                }
7068            } else if (pkgSetting.firstInstallTime == 0) {
7069                // We need *something*.  Take time time stamp of the file.
7070                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7071            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7072                if (scanFileTime != pkgSetting.timeStamp) {
7073                    // A package on the system image has changed; consider this
7074                    // to be an update.
7075                    pkgSetting.lastUpdateTime = scanFileTime;
7076                }
7077            }
7078
7079            // Add the package's KeySets to the global KeySetManagerService
7080            ksms.addScannedPackageLPw(pkg);
7081
7082            int N = pkg.providers.size();
7083            StringBuilder r = null;
7084            int i;
7085            for (i=0; i<N; i++) {
7086                PackageParser.Provider p = pkg.providers.get(i);
7087                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7088                        p.info.processName, pkg.applicationInfo.uid);
7089                mProviders.addProvider(p);
7090                p.syncable = p.info.isSyncable;
7091                if (p.info.authority != null) {
7092                    String names[] = p.info.authority.split(";");
7093                    p.info.authority = null;
7094                    for (int j = 0; j < names.length; j++) {
7095                        if (j == 1 && p.syncable) {
7096                            // We only want the first authority for a provider to possibly be
7097                            // syncable, so if we already added this provider using a different
7098                            // authority clear the syncable flag. We copy the provider before
7099                            // changing it because the mProviders object contains a reference
7100                            // to a provider that we don't want to change.
7101                            // Only do this for the second authority since the resulting provider
7102                            // object can be the same for all future authorities for this provider.
7103                            p = new PackageParser.Provider(p);
7104                            p.syncable = false;
7105                        }
7106                        if (!mProvidersByAuthority.containsKey(names[j])) {
7107                            mProvidersByAuthority.put(names[j], p);
7108                            if (p.info.authority == null) {
7109                                p.info.authority = names[j];
7110                            } else {
7111                                p.info.authority = p.info.authority + ";" + names[j];
7112                            }
7113                            if (DEBUG_PACKAGE_SCANNING) {
7114                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7115                                    Log.d(TAG, "Registered content provider: " + names[j]
7116                                            + ", className = " + p.info.name + ", isSyncable = "
7117                                            + p.info.isSyncable);
7118                            }
7119                        } else {
7120                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7121                            Slog.w(TAG, "Skipping provider name " + names[j] +
7122                                    " (in package " + pkg.applicationInfo.packageName +
7123                                    "): name already used by "
7124                                    + ((other != null && other.getComponentName() != null)
7125                                            ? other.getComponentName().getPackageName() : "?"));
7126                        }
7127                    }
7128                }
7129                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7130                    if (r == null) {
7131                        r = new StringBuilder(256);
7132                    } else {
7133                        r.append(' ');
7134                    }
7135                    r.append(p.info.name);
7136                }
7137            }
7138            if (r != null) {
7139                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7140            }
7141
7142            N = pkg.services.size();
7143            r = null;
7144            for (i=0; i<N; i++) {
7145                PackageParser.Service s = pkg.services.get(i);
7146                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7147                        s.info.processName, pkg.applicationInfo.uid);
7148                mServices.addService(s);
7149                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7150                    if (r == null) {
7151                        r = new StringBuilder(256);
7152                    } else {
7153                        r.append(' ');
7154                    }
7155                    r.append(s.info.name);
7156                }
7157            }
7158            if (r != null) {
7159                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7160            }
7161
7162            N = pkg.receivers.size();
7163            r = null;
7164            for (i=0; i<N; i++) {
7165                PackageParser.Activity a = pkg.receivers.get(i);
7166                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7167                        a.info.processName, pkg.applicationInfo.uid);
7168                mReceivers.addActivity(a, "receiver");
7169                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7170                    if (r == null) {
7171                        r = new StringBuilder(256);
7172                    } else {
7173                        r.append(' ');
7174                    }
7175                    r.append(a.info.name);
7176                }
7177            }
7178            if (r != null) {
7179                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7180            }
7181
7182            N = pkg.activities.size();
7183            r = null;
7184            for (i=0; i<N; i++) {
7185                PackageParser.Activity a = pkg.activities.get(i);
7186                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7187                        a.info.processName, pkg.applicationInfo.uid);
7188                mActivities.addActivity(a, "activity");
7189                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7190                    if (r == null) {
7191                        r = new StringBuilder(256);
7192                    } else {
7193                        r.append(' ');
7194                    }
7195                    r.append(a.info.name);
7196                }
7197            }
7198            if (r != null) {
7199                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7200            }
7201
7202            N = pkg.permissionGroups.size();
7203            r = null;
7204            for (i=0; i<N; i++) {
7205                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7206                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7207                if (cur == null) {
7208                    mPermissionGroups.put(pg.info.name, pg);
7209                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7210                        if (r == null) {
7211                            r = new StringBuilder(256);
7212                        } else {
7213                            r.append(' ');
7214                        }
7215                        r.append(pg.info.name);
7216                    }
7217                } else {
7218                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7219                            + pg.info.packageName + " ignored: original from "
7220                            + cur.info.packageName);
7221                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7222                        if (r == null) {
7223                            r = new StringBuilder(256);
7224                        } else {
7225                            r.append(' ');
7226                        }
7227                        r.append("DUP:");
7228                        r.append(pg.info.name);
7229                    }
7230                }
7231            }
7232            if (r != null) {
7233                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7234            }
7235
7236            N = pkg.permissions.size();
7237            r = null;
7238            for (i=0; i<N; i++) {
7239                PackageParser.Permission p = pkg.permissions.get(i);
7240
7241                // Now that permission groups have a special meaning, we ignore permission
7242                // groups for legacy apps to prevent unexpected behavior. In particular,
7243                // permissions for one app being granted to someone just becuase they happen
7244                // to be in a group defined by another app (before this had no implications).
7245                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7246                    p.group = mPermissionGroups.get(p.info.group);
7247                    // Warn for a permission in an unknown group.
7248                    if (p.info.group != null && p.group == null) {
7249                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7250                                + p.info.packageName + " in an unknown group " + p.info.group);
7251                    }
7252                }
7253
7254                ArrayMap<String, BasePermission> permissionMap =
7255                        p.tree ? mSettings.mPermissionTrees
7256                                : mSettings.mPermissions;
7257                BasePermission bp = permissionMap.get(p.info.name);
7258
7259                // Allow system apps to redefine non-system permissions
7260                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7261                    final boolean currentOwnerIsSystem = (bp.perm != null
7262                            && isSystemApp(bp.perm.owner));
7263                    if (isSystemApp(p.owner)) {
7264                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7265                            // It's a built-in permission and no owner, take ownership now
7266                            bp.packageSetting = pkgSetting;
7267                            bp.perm = p;
7268                            bp.uid = pkg.applicationInfo.uid;
7269                            bp.sourcePackage = p.info.packageName;
7270                        } else if (!currentOwnerIsSystem) {
7271                            String msg = "New decl " + p.owner + " of permission  "
7272                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7273                            reportSettingsProblem(Log.WARN, msg);
7274                            bp = null;
7275                        }
7276                    }
7277                }
7278
7279                if (bp == null) {
7280                    bp = new BasePermission(p.info.name, p.info.packageName,
7281                            BasePermission.TYPE_NORMAL);
7282                    permissionMap.put(p.info.name, bp);
7283                }
7284
7285                if (bp.perm == null) {
7286                    if (bp.sourcePackage == null
7287                            || bp.sourcePackage.equals(p.info.packageName)) {
7288                        BasePermission tree = findPermissionTreeLP(p.info.name);
7289                        if (tree == null
7290                                || tree.sourcePackage.equals(p.info.packageName)) {
7291                            bp.packageSetting = pkgSetting;
7292                            bp.perm = p;
7293                            bp.uid = pkg.applicationInfo.uid;
7294                            bp.sourcePackage = p.info.packageName;
7295                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7296                                if (r == null) {
7297                                    r = new StringBuilder(256);
7298                                } else {
7299                                    r.append(' ');
7300                                }
7301                                r.append(p.info.name);
7302                            }
7303                        } else {
7304                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7305                                    + p.info.packageName + " ignored: base tree "
7306                                    + tree.name + " is from package "
7307                                    + tree.sourcePackage);
7308                        }
7309                    } else {
7310                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7311                                + p.info.packageName + " ignored: original from "
7312                                + bp.sourcePackage);
7313                    }
7314                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7315                    if (r == null) {
7316                        r = new StringBuilder(256);
7317                    } else {
7318                        r.append(' ');
7319                    }
7320                    r.append("DUP:");
7321                    r.append(p.info.name);
7322                }
7323                if (bp.perm == p) {
7324                    bp.protectionLevel = p.info.protectionLevel;
7325                }
7326            }
7327
7328            if (r != null) {
7329                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7330            }
7331
7332            N = pkg.instrumentation.size();
7333            r = null;
7334            for (i=0; i<N; i++) {
7335                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7336                a.info.packageName = pkg.applicationInfo.packageName;
7337                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7338                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7339                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7340                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7341                a.info.dataDir = pkg.applicationInfo.dataDir;
7342
7343                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7344                // need other information about the application, like the ABI and what not ?
7345                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7346                mInstrumentation.put(a.getComponentName(), a);
7347                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7348                    if (r == null) {
7349                        r = new StringBuilder(256);
7350                    } else {
7351                        r.append(' ');
7352                    }
7353                    r.append(a.info.name);
7354                }
7355            }
7356            if (r != null) {
7357                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7358            }
7359
7360            if (pkg.protectedBroadcasts != null) {
7361                N = pkg.protectedBroadcasts.size();
7362                for (i=0; i<N; i++) {
7363                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7364                }
7365            }
7366
7367            pkgSetting.setTimeStamp(scanFileTime);
7368
7369            // Create idmap files for pairs of (packages, overlay packages).
7370            // Note: "android", ie framework-res.apk, is handled by native layers.
7371            if (pkg.mOverlayTarget != null) {
7372                // This is an overlay package.
7373                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7374                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7375                        mOverlays.put(pkg.mOverlayTarget,
7376                                new ArrayMap<String, PackageParser.Package>());
7377                    }
7378                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7379                    map.put(pkg.packageName, pkg);
7380                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7381                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7382                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7383                                "scanPackageLI failed to createIdmap");
7384                    }
7385                }
7386            } else if (mOverlays.containsKey(pkg.packageName) &&
7387                    !pkg.packageName.equals("android")) {
7388                // This is a regular package, with one or more known overlay packages.
7389                createIdmapsForPackageLI(pkg);
7390            }
7391        }
7392
7393        return pkg;
7394    }
7395
7396    /**
7397     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7398     * is derived purely on the basis of the contents of {@code scanFile} and
7399     * {@code cpuAbiOverride}.
7400     *
7401     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7402     */
7403    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7404                                 String cpuAbiOverride, boolean extractLibs)
7405            throws PackageManagerException {
7406        // TODO: We can probably be smarter about this stuff. For installed apps,
7407        // we can calculate this information at install time once and for all. For
7408        // system apps, we can probably assume that this information doesn't change
7409        // after the first boot scan. As things stand, we do lots of unnecessary work.
7410
7411        // Give ourselves some initial paths; we'll come back for another
7412        // pass once we've determined ABI below.
7413        setNativeLibraryPaths(pkg);
7414
7415        // We would never need to extract libs for forward-locked and external packages,
7416        // since the container service will do it for us. We shouldn't attempt to
7417        // extract libs from system app when it was not updated.
7418        if (pkg.isForwardLocked() || isExternal(pkg) ||
7419            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7420            extractLibs = false;
7421        }
7422
7423        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7424        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7425
7426        NativeLibraryHelper.Handle handle = null;
7427        try {
7428            handle = NativeLibraryHelper.Handle.create(scanFile);
7429            // TODO(multiArch): This can be null for apps that didn't go through the
7430            // usual installation process. We can calculate it again, like we
7431            // do during install time.
7432            //
7433            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7434            // unnecessary.
7435            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7436
7437            // Null out the abis so that they can be recalculated.
7438            pkg.applicationInfo.primaryCpuAbi = null;
7439            pkg.applicationInfo.secondaryCpuAbi = null;
7440            if (isMultiArch(pkg.applicationInfo)) {
7441                // Warn if we've set an abiOverride for multi-lib packages..
7442                // By definition, we need to copy both 32 and 64 bit libraries for
7443                // such packages.
7444                if (pkg.cpuAbiOverride != null
7445                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7446                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7447                }
7448
7449                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7450                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7451                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7452                    if (extractLibs) {
7453                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7454                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7455                                useIsaSpecificSubdirs);
7456                    } else {
7457                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7458                    }
7459                }
7460
7461                maybeThrowExceptionForMultiArchCopy(
7462                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7463
7464                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7465                    if (extractLibs) {
7466                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7467                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7468                                useIsaSpecificSubdirs);
7469                    } else {
7470                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7471                    }
7472                }
7473
7474                maybeThrowExceptionForMultiArchCopy(
7475                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7476
7477                if (abi64 >= 0) {
7478                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7479                }
7480
7481                if (abi32 >= 0) {
7482                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7483                    if (abi64 >= 0) {
7484                        pkg.applicationInfo.secondaryCpuAbi = abi;
7485                    } else {
7486                        pkg.applicationInfo.primaryCpuAbi = abi;
7487                    }
7488                }
7489            } else {
7490                String[] abiList = (cpuAbiOverride != null) ?
7491                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7492
7493                // Enable gross and lame hacks for apps that are built with old
7494                // SDK tools. We must scan their APKs for renderscript bitcode and
7495                // not launch them if it's present. Don't bother checking on devices
7496                // that don't have 64 bit support.
7497                boolean needsRenderScriptOverride = false;
7498                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7499                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7500                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7501                    needsRenderScriptOverride = true;
7502                }
7503
7504                final int copyRet;
7505                if (extractLibs) {
7506                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7507                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7508                } else {
7509                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7510                }
7511
7512                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7513                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7514                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7515                }
7516
7517                if (copyRet >= 0) {
7518                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7519                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7520                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7521                } else if (needsRenderScriptOverride) {
7522                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7523                }
7524            }
7525        } catch (IOException ioe) {
7526            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7527        } finally {
7528            IoUtils.closeQuietly(handle);
7529        }
7530
7531        // Now that we've calculated the ABIs and determined if it's an internal app,
7532        // we will go ahead and populate the nativeLibraryPath.
7533        setNativeLibraryPaths(pkg);
7534    }
7535
7536    /**
7537     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7538     * i.e, so that all packages can be run inside a single process if required.
7539     *
7540     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7541     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7542     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7543     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7544     * updating a package that belongs to a shared user.
7545     *
7546     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7547     * adds unnecessary complexity.
7548     */
7549    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7550            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7551        String requiredInstructionSet = null;
7552        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7553            requiredInstructionSet = VMRuntime.getInstructionSet(
7554                     scannedPackage.applicationInfo.primaryCpuAbi);
7555        }
7556
7557        PackageSetting requirer = null;
7558        for (PackageSetting ps : packagesForUser) {
7559            // If packagesForUser contains scannedPackage, we skip it. This will happen
7560            // when scannedPackage is an update of an existing package. Without this check,
7561            // we will never be able to change the ABI of any package belonging to a shared
7562            // user, even if it's compatible with other packages.
7563            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7564                if (ps.primaryCpuAbiString == null) {
7565                    continue;
7566                }
7567
7568                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7569                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7570                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7571                    // this but there's not much we can do.
7572                    String errorMessage = "Instruction set mismatch, "
7573                            + ((requirer == null) ? "[caller]" : requirer)
7574                            + " requires " + requiredInstructionSet + " whereas " + ps
7575                            + " requires " + instructionSet;
7576                    Slog.w(TAG, errorMessage);
7577                }
7578
7579                if (requiredInstructionSet == null) {
7580                    requiredInstructionSet = instructionSet;
7581                    requirer = ps;
7582                }
7583            }
7584        }
7585
7586        if (requiredInstructionSet != null) {
7587            String adjustedAbi;
7588            if (requirer != null) {
7589                // requirer != null implies that either scannedPackage was null or that scannedPackage
7590                // did not require an ABI, in which case we have to adjust scannedPackage to match
7591                // the ABI of the set (which is the same as requirer's ABI)
7592                adjustedAbi = requirer.primaryCpuAbiString;
7593                if (scannedPackage != null) {
7594                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7595                }
7596            } else {
7597                // requirer == null implies that we're updating all ABIs in the set to
7598                // match scannedPackage.
7599                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7600            }
7601
7602            for (PackageSetting ps : packagesForUser) {
7603                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7604                    if (ps.primaryCpuAbiString != null) {
7605                        continue;
7606                    }
7607
7608                    ps.primaryCpuAbiString = adjustedAbi;
7609                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7610                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7611                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7612
7613                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7614                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7615                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7616                            ps.primaryCpuAbiString = null;
7617                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7618                            return;
7619                        } else {
7620                            mInstaller.rmdex(ps.codePathString,
7621                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7622                        }
7623                    }
7624                }
7625            }
7626        }
7627    }
7628
7629    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7630        synchronized (mPackages) {
7631            mResolverReplaced = true;
7632            // Set up information for custom user intent resolution activity.
7633            mResolveActivity.applicationInfo = pkg.applicationInfo;
7634            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7635            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7636            mResolveActivity.processName = pkg.applicationInfo.packageName;
7637            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7638            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7639                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7640            mResolveActivity.theme = 0;
7641            mResolveActivity.exported = true;
7642            mResolveActivity.enabled = true;
7643            mResolveInfo.activityInfo = mResolveActivity;
7644            mResolveInfo.priority = 0;
7645            mResolveInfo.preferredOrder = 0;
7646            mResolveInfo.match = 0;
7647            mResolveComponentName = mCustomResolverComponentName;
7648            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7649                    mResolveComponentName);
7650        }
7651    }
7652
7653    private static String calculateBundledApkRoot(final String codePathString) {
7654        final File codePath = new File(codePathString);
7655        final File codeRoot;
7656        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7657            codeRoot = Environment.getRootDirectory();
7658        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7659            codeRoot = Environment.getOemDirectory();
7660        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7661            codeRoot = Environment.getVendorDirectory();
7662        } else {
7663            // Unrecognized code path; take its top real segment as the apk root:
7664            // e.g. /something/app/blah.apk => /something
7665            try {
7666                File f = codePath.getCanonicalFile();
7667                File parent = f.getParentFile();    // non-null because codePath is a file
7668                File tmp;
7669                while ((tmp = parent.getParentFile()) != null) {
7670                    f = parent;
7671                    parent = tmp;
7672                }
7673                codeRoot = f;
7674                Slog.w(TAG, "Unrecognized code path "
7675                        + codePath + " - using " + codeRoot);
7676            } catch (IOException e) {
7677                // Can't canonicalize the code path -- shenanigans?
7678                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7679                return Environment.getRootDirectory().getPath();
7680            }
7681        }
7682        return codeRoot.getPath();
7683    }
7684
7685    /**
7686     * Derive and set the location of native libraries for the given package,
7687     * which varies depending on where and how the package was installed.
7688     */
7689    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7690        final ApplicationInfo info = pkg.applicationInfo;
7691        final String codePath = pkg.codePath;
7692        final File codeFile = new File(codePath);
7693        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7694        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7695
7696        info.nativeLibraryRootDir = null;
7697        info.nativeLibraryRootRequiresIsa = false;
7698        info.nativeLibraryDir = null;
7699        info.secondaryNativeLibraryDir = null;
7700
7701        if (isApkFile(codeFile)) {
7702            // Monolithic install
7703            if (bundledApp) {
7704                // If "/system/lib64/apkname" exists, assume that is the per-package
7705                // native library directory to use; otherwise use "/system/lib/apkname".
7706                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7707                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7708                        getPrimaryInstructionSet(info));
7709
7710                // This is a bundled system app so choose the path based on the ABI.
7711                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7712                // is just the default path.
7713                final String apkName = deriveCodePathName(codePath);
7714                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7715                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7716                        apkName).getAbsolutePath();
7717
7718                if (info.secondaryCpuAbi != null) {
7719                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7720                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7721                            secondaryLibDir, apkName).getAbsolutePath();
7722                }
7723            } else if (asecApp) {
7724                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7725                        .getAbsolutePath();
7726            } else {
7727                final String apkName = deriveCodePathName(codePath);
7728                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7729                        .getAbsolutePath();
7730            }
7731
7732            info.nativeLibraryRootRequiresIsa = false;
7733            info.nativeLibraryDir = info.nativeLibraryRootDir;
7734        } else {
7735            // Cluster install
7736            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7737            info.nativeLibraryRootRequiresIsa = true;
7738
7739            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7740                    getPrimaryInstructionSet(info)).getAbsolutePath();
7741
7742            if (info.secondaryCpuAbi != null) {
7743                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7744                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7745            }
7746        }
7747    }
7748
7749    /**
7750     * Calculate the abis and roots for a bundled app. These can uniquely
7751     * be determined from the contents of the system partition, i.e whether
7752     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7753     * of this information, and instead assume that the system was built
7754     * sensibly.
7755     */
7756    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7757                                           PackageSetting pkgSetting) {
7758        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7759
7760        // If "/system/lib64/apkname" exists, assume that is the per-package
7761        // native library directory to use; otherwise use "/system/lib/apkname".
7762        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7763        setBundledAppAbi(pkg, apkRoot, apkName);
7764        // pkgSetting might be null during rescan following uninstall of updates
7765        // to a bundled app, so accommodate that possibility.  The settings in
7766        // that case will be established later from the parsed package.
7767        //
7768        // If the settings aren't null, sync them up with what we've just derived.
7769        // note that apkRoot isn't stored in the package settings.
7770        if (pkgSetting != null) {
7771            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7772            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7773        }
7774    }
7775
7776    /**
7777     * Deduces the ABI of a bundled app and sets the relevant fields on the
7778     * parsed pkg object.
7779     *
7780     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7781     *        under which system libraries are installed.
7782     * @param apkName the name of the installed package.
7783     */
7784    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7785        final File codeFile = new File(pkg.codePath);
7786
7787        final boolean has64BitLibs;
7788        final boolean has32BitLibs;
7789        if (isApkFile(codeFile)) {
7790            // Monolithic install
7791            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7792            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7793        } else {
7794            // Cluster install
7795            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7796            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7797                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7798                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7799                has64BitLibs = (new File(rootDir, isa)).exists();
7800            } else {
7801                has64BitLibs = false;
7802            }
7803            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7804                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7805                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7806                has32BitLibs = (new File(rootDir, isa)).exists();
7807            } else {
7808                has32BitLibs = false;
7809            }
7810        }
7811
7812        if (has64BitLibs && !has32BitLibs) {
7813            // The package has 64 bit libs, but not 32 bit libs. Its primary
7814            // ABI should be 64 bit. We can safely assume here that the bundled
7815            // native libraries correspond to the most preferred ABI in the list.
7816
7817            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7818            pkg.applicationInfo.secondaryCpuAbi = null;
7819        } else if (has32BitLibs && !has64BitLibs) {
7820            // The package has 32 bit libs but not 64 bit libs. Its primary
7821            // ABI should be 32 bit.
7822
7823            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7824            pkg.applicationInfo.secondaryCpuAbi = null;
7825        } else if (has32BitLibs && has64BitLibs) {
7826            // The application has both 64 and 32 bit bundled libraries. We check
7827            // here that the app declares multiArch support, and warn if it doesn't.
7828            //
7829            // We will be lenient here and record both ABIs. The primary will be the
7830            // ABI that's higher on the list, i.e, a device that's configured to prefer
7831            // 64 bit apps will see a 64 bit primary ABI,
7832
7833            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7834                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7835            }
7836
7837            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7838                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7839                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7840            } else {
7841                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7842                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7843            }
7844        } else {
7845            pkg.applicationInfo.primaryCpuAbi = null;
7846            pkg.applicationInfo.secondaryCpuAbi = null;
7847        }
7848    }
7849
7850    private void killApplication(String pkgName, int appId, String reason) {
7851        // Request the ActivityManager to kill the process(only for existing packages)
7852        // so that we do not end up in a confused state while the user is still using the older
7853        // version of the application while the new one gets installed.
7854        IActivityManager am = ActivityManagerNative.getDefault();
7855        if (am != null) {
7856            try {
7857                am.killApplicationWithAppId(pkgName, appId, reason);
7858            } catch (RemoteException e) {
7859            }
7860        }
7861    }
7862
7863    void removePackageLI(PackageSetting ps, boolean chatty) {
7864        if (DEBUG_INSTALL) {
7865            if (chatty)
7866                Log.d(TAG, "Removing package " + ps.name);
7867        }
7868
7869        // writer
7870        synchronized (mPackages) {
7871            mPackages.remove(ps.name);
7872            final PackageParser.Package pkg = ps.pkg;
7873            if (pkg != null) {
7874                cleanPackageDataStructuresLILPw(pkg, chatty);
7875            }
7876        }
7877    }
7878
7879    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7880        if (DEBUG_INSTALL) {
7881            if (chatty)
7882                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7883        }
7884
7885        // writer
7886        synchronized (mPackages) {
7887            mPackages.remove(pkg.applicationInfo.packageName);
7888            cleanPackageDataStructuresLILPw(pkg, chatty);
7889        }
7890    }
7891
7892    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7893        int N = pkg.providers.size();
7894        StringBuilder r = null;
7895        int i;
7896        for (i=0; i<N; i++) {
7897            PackageParser.Provider p = pkg.providers.get(i);
7898            mProviders.removeProvider(p);
7899            if (p.info.authority == null) {
7900
7901                /* There was another ContentProvider with this authority when
7902                 * this app was installed so this authority is null,
7903                 * Ignore it as we don't have to unregister the provider.
7904                 */
7905                continue;
7906            }
7907            String names[] = p.info.authority.split(";");
7908            for (int j = 0; j < names.length; j++) {
7909                if (mProvidersByAuthority.get(names[j]) == p) {
7910                    mProvidersByAuthority.remove(names[j]);
7911                    if (DEBUG_REMOVE) {
7912                        if (chatty)
7913                            Log.d(TAG, "Unregistered content provider: " + names[j]
7914                                    + ", className = " + p.info.name + ", isSyncable = "
7915                                    + p.info.isSyncable);
7916                    }
7917                }
7918            }
7919            if (DEBUG_REMOVE && chatty) {
7920                if (r == null) {
7921                    r = new StringBuilder(256);
7922                } else {
7923                    r.append(' ');
7924                }
7925                r.append(p.info.name);
7926            }
7927        }
7928        if (r != null) {
7929            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7930        }
7931
7932        N = pkg.services.size();
7933        r = null;
7934        for (i=0; i<N; i++) {
7935            PackageParser.Service s = pkg.services.get(i);
7936            mServices.removeService(s);
7937            if (chatty) {
7938                if (r == null) {
7939                    r = new StringBuilder(256);
7940                } else {
7941                    r.append(' ');
7942                }
7943                r.append(s.info.name);
7944            }
7945        }
7946        if (r != null) {
7947            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7948        }
7949
7950        N = pkg.receivers.size();
7951        r = null;
7952        for (i=0; i<N; i++) {
7953            PackageParser.Activity a = pkg.receivers.get(i);
7954            mReceivers.removeActivity(a, "receiver");
7955            if (DEBUG_REMOVE && chatty) {
7956                if (r == null) {
7957                    r = new StringBuilder(256);
7958                } else {
7959                    r.append(' ');
7960                }
7961                r.append(a.info.name);
7962            }
7963        }
7964        if (r != null) {
7965            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7966        }
7967
7968        N = pkg.activities.size();
7969        r = null;
7970        for (i=0; i<N; i++) {
7971            PackageParser.Activity a = pkg.activities.get(i);
7972            mActivities.removeActivity(a, "activity");
7973            if (DEBUG_REMOVE && chatty) {
7974                if (r == null) {
7975                    r = new StringBuilder(256);
7976                } else {
7977                    r.append(' ');
7978                }
7979                r.append(a.info.name);
7980            }
7981        }
7982        if (r != null) {
7983            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7984        }
7985
7986        N = pkg.permissions.size();
7987        r = null;
7988        for (i=0; i<N; i++) {
7989            PackageParser.Permission p = pkg.permissions.get(i);
7990            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7991            if (bp == null) {
7992                bp = mSettings.mPermissionTrees.get(p.info.name);
7993            }
7994            if (bp != null && bp.perm == p) {
7995                bp.perm = null;
7996                if (DEBUG_REMOVE && chatty) {
7997                    if (r == null) {
7998                        r = new StringBuilder(256);
7999                    } else {
8000                        r.append(' ');
8001                    }
8002                    r.append(p.info.name);
8003                }
8004            }
8005            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8006                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8007                if (appOpPerms != null) {
8008                    appOpPerms.remove(pkg.packageName);
8009                }
8010            }
8011        }
8012        if (r != null) {
8013            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8014        }
8015
8016        N = pkg.requestedPermissions.size();
8017        r = null;
8018        for (i=0; i<N; i++) {
8019            String perm = pkg.requestedPermissions.get(i);
8020            BasePermission bp = mSettings.mPermissions.get(perm);
8021            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8022                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8023                if (appOpPerms != null) {
8024                    appOpPerms.remove(pkg.packageName);
8025                    if (appOpPerms.isEmpty()) {
8026                        mAppOpPermissionPackages.remove(perm);
8027                    }
8028                }
8029            }
8030        }
8031        if (r != null) {
8032            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8033        }
8034
8035        N = pkg.instrumentation.size();
8036        r = null;
8037        for (i=0; i<N; i++) {
8038            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8039            mInstrumentation.remove(a.getComponentName());
8040            if (DEBUG_REMOVE && chatty) {
8041                if (r == null) {
8042                    r = new StringBuilder(256);
8043                } else {
8044                    r.append(' ');
8045                }
8046                r.append(a.info.name);
8047            }
8048        }
8049        if (r != null) {
8050            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8051        }
8052
8053        r = null;
8054        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8055            // Only system apps can hold shared libraries.
8056            if (pkg.libraryNames != null) {
8057                for (i=0; i<pkg.libraryNames.size(); i++) {
8058                    String name = pkg.libraryNames.get(i);
8059                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8060                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8061                        mSharedLibraries.remove(name);
8062                        if (DEBUG_REMOVE && chatty) {
8063                            if (r == null) {
8064                                r = new StringBuilder(256);
8065                            } else {
8066                                r.append(' ');
8067                            }
8068                            r.append(name);
8069                        }
8070                    }
8071                }
8072            }
8073        }
8074        if (r != null) {
8075            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8076        }
8077    }
8078
8079    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8080        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8081            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8082                return true;
8083            }
8084        }
8085        return false;
8086    }
8087
8088    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8089    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8090    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8091
8092    private void updatePermissionsLPw(String changingPkg,
8093            PackageParser.Package pkgInfo, int flags) {
8094        // Make sure there are no dangling permission trees.
8095        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8096        while (it.hasNext()) {
8097            final BasePermission bp = it.next();
8098            if (bp.packageSetting == null) {
8099                // We may not yet have parsed the package, so just see if
8100                // we still know about its settings.
8101                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8102            }
8103            if (bp.packageSetting == null) {
8104                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8105                        + " from package " + bp.sourcePackage);
8106                it.remove();
8107            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8108                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8109                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8110                            + " from package " + bp.sourcePackage);
8111                    flags |= UPDATE_PERMISSIONS_ALL;
8112                    it.remove();
8113                }
8114            }
8115        }
8116
8117        // Make sure all dynamic permissions have been assigned to a package,
8118        // and make sure there are no dangling permissions.
8119        it = mSettings.mPermissions.values().iterator();
8120        while (it.hasNext()) {
8121            final BasePermission bp = it.next();
8122            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8123                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8124                        + bp.name + " pkg=" + bp.sourcePackage
8125                        + " info=" + bp.pendingInfo);
8126                if (bp.packageSetting == null && bp.pendingInfo != null) {
8127                    final BasePermission tree = findPermissionTreeLP(bp.name);
8128                    if (tree != null && tree.perm != null) {
8129                        bp.packageSetting = tree.packageSetting;
8130                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8131                                new PermissionInfo(bp.pendingInfo));
8132                        bp.perm.info.packageName = tree.perm.info.packageName;
8133                        bp.perm.info.name = bp.name;
8134                        bp.uid = tree.uid;
8135                    }
8136                }
8137            }
8138            if (bp.packageSetting == null) {
8139                // We may not yet have parsed the package, so just see if
8140                // we still know about its settings.
8141                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8142            }
8143            if (bp.packageSetting == null) {
8144                Slog.w(TAG, "Removing dangling permission: " + bp.name
8145                        + " from package " + bp.sourcePackage);
8146                it.remove();
8147            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8148                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8149                    Slog.i(TAG, "Removing old permission: " + bp.name
8150                            + " from package " + bp.sourcePackage);
8151                    flags |= UPDATE_PERMISSIONS_ALL;
8152                    it.remove();
8153                }
8154            }
8155        }
8156
8157        // Now update the permissions for all packages, in particular
8158        // replace the granted permissions of the system packages.
8159        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8160            for (PackageParser.Package pkg : mPackages.values()) {
8161                if (pkg != pkgInfo) {
8162                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8163                            changingPkg);
8164                }
8165            }
8166        }
8167
8168        if (pkgInfo != null) {
8169            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8170        }
8171    }
8172
8173    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8174            String packageOfInterest) {
8175        // IMPORTANT: There are two types of permissions: install and runtime.
8176        // Install time permissions are granted when the app is installed to
8177        // all device users and users added in the future. Runtime permissions
8178        // are granted at runtime explicitly to specific users. Normal and signature
8179        // protected permissions are install time permissions. Dangerous permissions
8180        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8181        // otherwise they are runtime permissions. This function does not manage
8182        // runtime permissions except for the case an app targeting Lollipop MR1
8183        // being upgraded to target a newer SDK, in which case dangerous permissions
8184        // are transformed from install time to runtime ones.
8185
8186        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8187        if (ps == null) {
8188            return;
8189        }
8190
8191        PermissionsState permissionsState = ps.getPermissionsState();
8192        PermissionsState origPermissions = permissionsState;
8193
8194        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8195
8196        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8197
8198        boolean changedInstallPermission = false;
8199
8200        if (replace) {
8201            ps.installPermissionsFixed = false;
8202            if (!ps.isSharedUser()) {
8203                origPermissions = new PermissionsState(permissionsState);
8204                permissionsState.reset();
8205            }
8206        }
8207
8208        permissionsState.setGlobalGids(mGlobalGids);
8209
8210        final int N = pkg.requestedPermissions.size();
8211        for (int i=0; i<N; i++) {
8212            final String name = pkg.requestedPermissions.get(i);
8213            final BasePermission bp = mSettings.mPermissions.get(name);
8214
8215            if (DEBUG_INSTALL) {
8216                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8217            }
8218
8219            if (bp == null || bp.packageSetting == null) {
8220                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8221                    Slog.w(TAG, "Unknown permission " + name
8222                            + " in package " + pkg.packageName);
8223                }
8224                continue;
8225            }
8226
8227            final String perm = bp.name;
8228            boolean allowedSig = false;
8229            int grant = GRANT_DENIED;
8230
8231            // Keep track of app op permissions.
8232            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8233                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8234                if (pkgs == null) {
8235                    pkgs = new ArraySet<>();
8236                    mAppOpPermissionPackages.put(bp.name, pkgs);
8237                }
8238                pkgs.add(pkg.packageName);
8239            }
8240
8241            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8242            switch (level) {
8243                case PermissionInfo.PROTECTION_NORMAL: {
8244                    // For all apps normal permissions are install time ones.
8245                    grant = GRANT_INSTALL;
8246                } break;
8247
8248                case PermissionInfo.PROTECTION_DANGEROUS: {
8249                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8250                        // For legacy apps dangerous permissions are install time ones.
8251                        grant = GRANT_INSTALL_LEGACY;
8252                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8253                        // For legacy apps that became modern, install becomes runtime.
8254                        grant = GRANT_UPGRADE;
8255                    } else {
8256                        // For modern apps keep runtime permissions unchanged.
8257                        grant = GRANT_RUNTIME;
8258                    }
8259                } break;
8260
8261                case PermissionInfo.PROTECTION_SIGNATURE: {
8262                    // For all apps signature permissions are install time ones.
8263                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8264                    if (allowedSig) {
8265                        grant = GRANT_INSTALL;
8266                    }
8267                } break;
8268            }
8269
8270            if (DEBUG_INSTALL) {
8271                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8272            }
8273
8274            if (grant != GRANT_DENIED) {
8275                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8276                    // If this is an existing, non-system package, then
8277                    // we can't add any new permissions to it.
8278                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8279                        // Except...  if this is a permission that was added
8280                        // to the platform (note: need to only do this when
8281                        // updating the platform).
8282                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8283                            grant = GRANT_DENIED;
8284                        }
8285                    }
8286                }
8287
8288                switch (grant) {
8289                    case GRANT_INSTALL: {
8290                        // Revoke this as runtime permission to handle the case of
8291                        // a runtime permission being downgraded to an install one.
8292                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8293                            if (origPermissions.getRuntimePermissionState(
8294                                    bp.name, userId) != null) {
8295                                // Revoke the runtime permission and clear the flags.
8296                                origPermissions.revokeRuntimePermission(bp, userId);
8297                                origPermissions.updatePermissionFlags(bp, userId,
8298                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8299                                // If we revoked a permission permission, we have to write.
8300                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8301                                        changedRuntimePermissionUserIds, userId);
8302                            }
8303                        }
8304                        // Grant an install permission.
8305                        if (permissionsState.grantInstallPermission(bp) !=
8306                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8307                            changedInstallPermission = true;
8308                        }
8309                    } break;
8310
8311                    case GRANT_INSTALL_LEGACY: {
8312                        // Grant an install permission.
8313                        if (permissionsState.grantInstallPermission(bp) !=
8314                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8315                            changedInstallPermission = true;
8316                        }
8317                    } break;
8318
8319                    case GRANT_RUNTIME: {
8320                        // Grant previously granted runtime permissions.
8321                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8322                            PermissionState permissionState = origPermissions
8323                                    .getRuntimePermissionState(bp.name, userId);
8324                            final int flags = permissionState != null
8325                                    ? permissionState.getFlags() : 0;
8326                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8327                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8328                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8329                                    // If we cannot put the permission as it was, we have to write.
8330                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8331                                            changedRuntimePermissionUserIds, userId);
8332                                }
8333                            }
8334                            // Propagate the permission flags.
8335                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8336                        }
8337                    } break;
8338
8339                    case GRANT_UPGRADE: {
8340                        // Grant runtime permissions for a previously held install permission.
8341                        PermissionState permissionState = origPermissions
8342                                .getInstallPermissionState(bp.name);
8343                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8344
8345                        if (origPermissions.revokeInstallPermission(bp)
8346                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8347                            // We will be transferring the permission flags, so clear them.
8348                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8349                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8350                            changedInstallPermission = true;
8351                        }
8352
8353                        // If the permission is not to be promoted to runtime we ignore it and
8354                        // also its other flags as they are not applicable to install permissions.
8355                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8356                            for (int userId : currentUserIds) {
8357                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8358                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8359                                    // Transfer the permission flags.
8360                                    permissionsState.updatePermissionFlags(bp, userId,
8361                                            flags, flags);
8362                                    // If we granted the permission, we have to write.
8363                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8364                                            changedRuntimePermissionUserIds, userId);
8365                                }
8366                            }
8367                        }
8368                    } break;
8369
8370                    default: {
8371                        if (packageOfInterest == null
8372                                || packageOfInterest.equals(pkg.packageName)) {
8373                            Slog.w(TAG, "Not granting permission " + perm
8374                                    + " to package " + pkg.packageName
8375                                    + " because it was previously installed without");
8376                        }
8377                    } break;
8378                }
8379            } else {
8380                if (permissionsState.revokeInstallPermission(bp) !=
8381                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8382                    // Also drop the permission flags.
8383                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8384                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8385                    changedInstallPermission = true;
8386                    Slog.i(TAG, "Un-granting permission " + perm
8387                            + " from package " + pkg.packageName
8388                            + " (protectionLevel=" + bp.protectionLevel
8389                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8390                            + ")");
8391                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8392                    // Don't print warning for app op permissions, since it is fine for them
8393                    // not to be granted, there is a UI for the user to decide.
8394                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8395                        Slog.w(TAG, "Not granting permission " + perm
8396                                + " to package " + pkg.packageName
8397                                + " (protectionLevel=" + bp.protectionLevel
8398                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8399                                + ")");
8400                    }
8401                }
8402            }
8403        }
8404
8405        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8406                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8407            // This is the first that we have heard about this package, so the
8408            // permissions we have now selected are fixed until explicitly
8409            // changed.
8410            ps.installPermissionsFixed = true;
8411        }
8412
8413        // Persist the runtime permissions state for users with changes.
8414        for (int userId : changedRuntimePermissionUserIds) {
8415            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8416        }
8417    }
8418
8419    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8420        boolean allowed = false;
8421        final int NP = PackageParser.NEW_PERMISSIONS.length;
8422        for (int ip=0; ip<NP; ip++) {
8423            final PackageParser.NewPermissionInfo npi
8424                    = PackageParser.NEW_PERMISSIONS[ip];
8425            if (npi.name.equals(perm)
8426                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8427                allowed = true;
8428                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8429                        + pkg.packageName);
8430                break;
8431            }
8432        }
8433        return allowed;
8434    }
8435
8436    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8437            BasePermission bp, PermissionsState origPermissions) {
8438        boolean allowed;
8439        allowed = (compareSignatures(
8440                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8441                        == PackageManager.SIGNATURE_MATCH)
8442                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8443                        == PackageManager.SIGNATURE_MATCH);
8444        if (!allowed && (bp.protectionLevel
8445                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8446            if (isSystemApp(pkg)) {
8447                // For updated system applications, a system permission
8448                // is granted only if it had been defined by the original application.
8449                if (pkg.isUpdatedSystemApp()) {
8450                    final PackageSetting sysPs = mSettings
8451                            .getDisabledSystemPkgLPr(pkg.packageName);
8452                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8453                        // If the original was granted this permission, we take
8454                        // that grant decision as read and propagate it to the
8455                        // update.
8456                        if (sysPs.isPrivileged()) {
8457                            allowed = true;
8458                        }
8459                    } else {
8460                        // The system apk may have been updated with an older
8461                        // version of the one on the data partition, but which
8462                        // granted a new system permission that it didn't have
8463                        // before.  In this case we do want to allow the app to
8464                        // now get the new permission if the ancestral apk is
8465                        // privileged to get it.
8466                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8467                            for (int j=0;
8468                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8469                                if (perm.equals(
8470                                        sysPs.pkg.requestedPermissions.get(j))) {
8471                                    allowed = true;
8472                                    break;
8473                                }
8474                            }
8475                        }
8476                    }
8477                } else {
8478                    allowed = isPrivilegedApp(pkg);
8479                }
8480            }
8481        }
8482        if (!allowed) {
8483            if (!allowed && (bp.protectionLevel
8484                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8485                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8486                // If this was a previously normal/dangerous permission that got moved
8487                // to a system permission as part of the runtime permission redesign, then
8488                // we still want to blindly grant it to old apps.
8489                allowed = true;
8490            }
8491            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8492                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8493                // If this permission is to be granted to the system installer and
8494                // this app is an installer, then it gets the permission.
8495                allowed = true;
8496            }
8497            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8498                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8499                // If this permission is to be granted to the system verifier and
8500                // this app is a verifier, then it gets the permission.
8501                allowed = true;
8502            }
8503            if (!allowed && (bp.protectionLevel
8504                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8505                    && isSystemApp(pkg)) {
8506                // Any pre-installed system app is allowed to get this permission.
8507                allowed = true;
8508            }
8509            if (!allowed && (bp.protectionLevel
8510                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8511                // For development permissions, a development permission
8512                // is granted only if it was already granted.
8513                allowed = origPermissions.hasInstallPermission(perm);
8514            }
8515        }
8516        return allowed;
8517    }
8518
8519    final class ActivityIntentResolver
8520            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8521        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8522                boolean defaultOnly, int userId) {
8523            if (!sUserManager.exists(userId)) return null;
8524            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8525            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8526        }
8527
8528        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8529                int userId) {
8530            if (!sUserManager.exists(userId)) return null;
8531            mFlags = flags;
8532            return super.queryIntent(intent, resolvedType,
8533                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8534        }
8535
8536        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8537                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8538            if (!sUserManager.exists(userId)) return null;
8539            if (packageActivities == null) {
8540                return null;
8541            }
8542            mFlags = flags;
8543            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8544            final int N = packageActivities.size();
8545            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8546                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8547
8548            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8549            for (int i = 0; i < N; ++i) {
8550                intentFilters = packageActivities.get(i).intents;
8551                if (intentFilters != null && intentFilters.size() > 0) {
8552                    PackageParser.ActivityIntentInfo[] array =
8553                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8554                    intentFilters.toArray(array);
8555                    listCut.add(array);
8556                }
8557            }
8558            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8559        }
8560
8561        public final void addActivity(PackageParser.Activity a, String type) {
8562            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8563            mActivities.put(a.getComponentName(), a);
8564            if (DEBUG_SHOW_INFO)
8565                Log.v(
8566                TAG, "  " + type + " " +
8567                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8568            if (DEBUG_SHOW_INFO)
8569                Log.v(TAG, "    Class=" + a.info.name);
8570            final int NI = a.intents.size();
8571            for (int j=0; j<NI; j++) {
8572                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8573                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8574                    intent.setPriority(0);
8575                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8576                            + a.className + " with priority > 0, forcing to 0");
8577                }
8578                if (DEBUG_SHOW_INFO) {
8579                    Log.v(TAG, "    IntentFilter:");
8580                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8581                }
8582                if (!intent.debugCheck()) {
8583                    Log.w(TAG, "==> For Activity " + a.info.name);
8584                }
8585                addFilter(intent);
8586            }
8587        }
8588
8589        public final void removeActivity(PackageParser.Activity a, String type) {
8590            mActivities.remove(a.getComponentName());
8591            if (DEBUG_SHOW_INFO) {
8592                Log.v(TAG, "  " + type + " "
8593                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8594                                : a.info.name) + ":");
8595                Log.v(TAG, "    Class=" + a.info.name);
8596            }
8597            final int NI = a.intents.size();
8598            for (int j=0; j<NI; j++) {
8599                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8600                if (DEBUG_SHOW_INFO) {
8601                    Log.v(TAG, "    IntentFilter:");
8602                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8603                }
8604                removeFilter(intent);
8605            }
8606        }
8607
8608        @Override
8609        protected boolean allowFilterResult(
8610                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8611            ActivityInfo filterAi = filter.activity.info;
8612            for (int i=dest.size()-1; i>=0; i--) {
8613                ActivityInfo destAi = dest.get(i).activityInfo;
8614                if (destAi.name == filterAi.name
8615                        && destAi.packageName == filterAi.packageName) {
8616                    return false;
8617                }
8618            }
8619            return true;
8620        }
8621
8622        @Override
8623        protected ActivityIntentInfo[] newArray(int size) {
8624            return new ActivityIntentInfo[size];
8625        }
8626
8627        @Override
8628        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8629            if (!sUserManager.exists(userId)) return true;
8630            PackageParser.Package p = filter.activity.owner;
8631            if (p != null) {
8632                PackageSetting ps = (PackageSetting)p.mExtras;
8633                if (ps != null) {
8634                    // System apps are never considered stopped for purposes of
8635                    // filtering, because there may be no way for the user to
8636                    // actually re-launch them.
8637                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8638                            && ps.getStopped(userId);
8639                }
8640            }
8641            return false;
8642        }
8643
8644        @Override
8645        protected boolean isPackageForFilter(String packageName,
8646                PackageParser.ActivityIntentInfo info) {
8647            return packageName.equals(info.activity.owner.packageName);
8648        }
8649
8650        @Override
8651        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8652                int match, int userId) {
8653            if (!sUserManager.exists(userId)) return null;
8654            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8655                return null;
8656            }
8657            final PackageParser.Activity activity = info.activity;
8658            if (mSafeMode && (activity.info.applicationInfo.flags
8659                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8660                return null;
8661            }
8662            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8663            if (ps == null) {
8664                return null;
8665            }
8666            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8667                    ps.readUserState(userId), userId);
8668            if (ai == null) {
8669                return null;
8670            }
8671            final ResolveInfo res = new ResolveInfo();
8672            res.activityInfo = ai;
8673            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8674                res.filter = info;
8675            }
8676            if (info != null) {
8677                res.handleAllWebDataURI = info.handleAllWebDataURI();
8678            }
8679            res.priority = info.getPriority();
8680            res.preferredOrder = activity.owner.mPreferredOrder;
8681            //System.out.println("Result: " + res.activityInfo.className +
8682            //                   " = " + res.priority);
8683            res.match = match;
8684            res.isDefault = info.hasDefault;
8685            res.labelRes = info.labelRes;
8686            res.nonLocalizedLabel = info.nonLocalizedLabel;
8687            if (userNeedsBadging(userId)) {
8688                res.noResourceId = true;
8689            } else {
8690                res.icon = info.icon;
8691            }
8692            res.iconResourceId = info.icon;
8693            res.system = res.activityInfo.applicationInfo.isSystemApp();
8694            return res;
8695        }
8696
8697        @Override
8698        protected void sortResults(List<ResolveInfo> results) {
8699            Collections.sort(results, mResolvePrioritySorter);
8700        }
8701
8702        @Override
8703        protected void dumpFilter(PrintWriter out, String prefix,
8704                PackageParser.ActivityIntentInfo filter) {
8705            out.print(prefix); out.print(
8706                    Integer.toHexString(System.identityHashCode(filter.activity)));
8707                    out.print(' ');
8708                    filter.activity.printComponentShortName(out);
8709                    out.print(" filter ");
8710                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8711        }
8712
8713        @Override
8714        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8715            return filter.activity;
8716        }
8717
8718        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8719            PackageParser.Activity activity = (PackageParser.Activity)label;
8720            out.print(prefix); out.print(
8721                    Integer.toHexString(System.identityHashCode(activity)));
8722                    out.print(' ');
8723                    activity.printComponentShortName(out);
8724            if (count > 1) {
8725                out.print(" ("); out.print(count); out.print(" filters)");
8726            }
8727            out.println();
8728        }
8729
8730//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8731//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8732//            final List<ResolveInfo> retList = Lists.newArrayList();
8733//            while (i.hasNext()) {
8734//                final ResolveInfo resolveInfo = i.next();
8735//                if (isEnabledLP(resolveInfo.activityInfo)) {
8736//                    retList.add(resolveInfo);
8737//                }
8738//            }
8739//            return retList;
8740//        }
8741
8742        // Keys are String (activity class name), values are Activity.
8743        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8744                = new ArrayMap<ComponentName, PackageParser.Activity>();
8745        private int mFlags;
8746    }
8747
8748    private final class ServiceIntentResolver
8749            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8750        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8751                boolean defaultOnly, int userId) {
8752            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8753            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8754        }
8755
8756        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8757                int userId) {
8758            if (!sUserManager.exists(userId)) return null;
8759            mFlags = flags;
8760            return super.queryIntent(intent, resolvedType,
8761                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8762        }
8763
8764        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8765                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8766            if (!sUserManager.exists(userId)) return null;
8767            if (packageServices == null) {
8768                return null;
8769            }
8770            mFlags = flags;
8771            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8772            final int N = packageServices.size();
8773            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8774                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8775
8776            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8777            for (int i = 0; i < N; ++i) {
8778                intentFilters = packageServices.get(i).intents;
8779                if (intentFilters != null && intentFilters.size() > 0) {
8780                    PackageParser.ServiceIntentInfo[] array =
8781                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8782                    intentFilters.toArray(array);
8783                    listCut.add(array);
8784                }
8785            }
8786            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8787        }
8788
8789        public final void addService(PackageParser.Service s) {
8790            mServices.put(s.getComponentName(), s);
8791            if (DEBUG_SHOW_INFO) {
8792                Log.v(TAG, "  "
8793                        + (s.info.nonLocalizedLabel != null
8794                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8795                Log.v(TAG, "    Class=" + s.info.name);
8796            }
8797            final int NI = s.intents.size();
8798            int j;
8799            for (j=0; j<NI; j++) {
8800                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8801                if (DEBUG_SHOW_INFO) {
8802                    Log.v(TAG, "    IntentFilter:");
8803                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8804                }
8805                if (!intent.debugCheck()) {
8806                    Log.w(TAG, "==> For Service " + s.info.name);
8807                }
8808                addFilter(intent);
8809            }
8810        }
8811
8812        public final void removeService(PackageParser.Service s) {
8813            mServices.remove(s.getComponentName());
8814            if (DEBUG_SHOW_INFO) {
8815                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8816                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8817                Log.v(TAG, "    Class=" + s.info.name);
8818            }
8819            final int NI = s.intents.size();
8820            int j;
8821            for (j=0; j<NI; j++) {
8822                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8823                if (DEBUG_SHOW_INFO) {
8824                    Log.v(TAG, "    IntentFilter:");
8825                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8826                }
8827                removeFilter(intent);
8828            }
8829        }
8830
8831        @Override
8832        protected boolean allowFilterResult(
8833                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8834            ServiceInfo filterSi = filter.service.info;
8835            for (int i=dest.size()-1; i>=0; i--) {
8836                ServiceInfo destAi = dest.get(i).serviceInfo;
8837                if (destAi.name == filterSi.name
8838                        && destAi.packageName == filterSi.packageName) {
8839                    return false;
8840                }
8841            }
8842            return true;
8843        }
8844
8845        @Override
8846        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8847            return new PackageParser.ServiceIntentInfo[size];
8848        }
8849
8850        @Override
8851        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8852            if (!sUserManager.exists(userId)) return true;
8853            PackageParser.Package p = filter.service.owner;
8854            if (p != null) {
8855                PackageSetting ps = (PackageSetting)p.mExtras;
8856                if (ps != null) {
8857                    // System apps are never considered stopped for purposes of
8858                    // filtering, because there may be no way for the user to
8859                    // actually re-launch them.
8860                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8861                            && ps.getStopped(userId);
8862                }
8863            }
8864            return false;
8865        }
8866
8867        @Override
8868        protected boolean isPackageForFilter(String packageName,
8869                PackageParser.ServiceIntentInfo info) {
8870            return packageName.equals(info.service.owner.packageName);
8871        }
8872
8873        @Override
8874        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8875                int match, int userId) {
8876            if (!sUserManager.exists(userId)) return null;
8877            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8878            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8879                return null;
8880            }
8881            final PackageParser.Service service = info.service;
8882            if (mSafeMode && (service.info.applicationInfo.flags
8883                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8884                return null;
8885            }
8886            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8887            if (ps == null) {
8888                return null;
8889            }
8890            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8891                    ps.readUserState(userId), userId);
8892            if (si == null) {
8893                return null;
8894            }
8895            final ResolveInfo res = new ResolveInfo();
8896            res.serviceInfo = si;
8897            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8898                res.filter = filter;
8899            }
8900            res.priority = info.getPriority();
8901            res.preferredOrder = service.owner.mPreferredOrder;
8902            res.match = match;
8903            res.isDefault = info.hasDefault;
8904            res.labelRes = info.labelRes;
8905            res.nonLocalizedLabel = info.nonLocalizedLabel;
8906            res.icon = info.icon;
8907            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8908            return res;
8909        }
8910
8911        @Override
8912        protected void sortResults(List<ResolveInfo> results) {
8913            Collections.sort(results, mResolvePrioritySorter);
8914        }
8915
8916        @Override
8917        protected void dumpFilter(PrintWriter out, String prefix,
8918                PackageParser.ServiceIntentInfo filter) {
8919            out.print(prefix); out.print(
8920                    Integer.toHexString(System.identityHashCode(filter.service)));
8921                    out.print(' ');
8922                    filter.service.printComponentShortName(out);
8923                    out.print(" filter ");
8924                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8925        }
8926
8927        @Override
8928        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8929            return filter.service;
8930        }
8931
8932        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8933            PackageParser.Service service = (PackageParser.Service)label;
8934            out.print(prefix); out.print(
8935                    Integer.toHexString(System.identityHashCode(service)));
8936                    out.print(' ');
8937                    service.printComponentShortName(out);
8938            if (count > 1) {
8939                out.print(" ("); out.print(count); out.print(" filters)");
8940            }
8941            out.println();
8942        }
8943
8944//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8945//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8946//            final List<ResolveInfo> retList = Lists.newArrayList();
8947//            while (i.hasNext()) {
8948//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8949//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8950//                    retList.add(resolveInfo);
8951//                }
8952//            }
8953//            return retList;
8954//        }
8955
8956        // Keys are String (activity class name), values are Activity.
8957        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8958                = new ArrayMap<ComponentName, PackageParser.Service>();
8959        private int mFlags;
8960    };
8961
8962    private final class ProviderIntentResolver
8963            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8964        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8965                boolean defaultOnly, int userId) {
8966            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8967            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8968        }
8969
8970        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8971                int userId) {
8972            if (!sUserManager.exists(userId))
8973                return null;
8974            mFlags = flags;
8975            return super.queryIntent(intent, resolvedType,
8976                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8977        }
8978
8979        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8980                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8981            if (!sUserManager.exists(userId))
8982                return null;
8983            if (packageProviders == null) {
8984                return null;
8985            }
8986            mFlags = flags;
8987            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8988            final int N = packageProviders.size();
8989            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8990                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8991
8992            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8993            for (int i = 0; i < N; ++i) {
8994                intentFilters = packageProviders.get(i).intents;
8995                if (intentFilters != null && intentFilters.size() > 0) {
8996                    PackageParser.ProviderIntentInfo[] array =
8997                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8998                    intentFilters.toArray(array);
8999                    listCut.add(array);
9000                }
9001            }
9002            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9003        }
9004
9005        public final void addProvider(PackageParser.Provider p) {
9006            if (mProviders.containsKey(p.getComponentName())) {
9007                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9008                return;
9009            }
9010
9011            mProviders.put(p.getComponentName(), p);
9012            if (DEBUG_SHOW_INFO) {
9013                Log.v(TAG, "  "
9014                        + (p.info.nonLocalizedLabel != null
9015                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9016                Log.v(TAG, "    Class=" + p.info.name);
9017            }
9018            final int NI = p.intents.size();
9019            int j;
9020            for (j = 0; j < NI; j++) {
9021                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9022                if (DEBUG_SHOW_INFO) {
9023                    Log.v(TAG, "    IntentFilter:");
9024                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9025                }
9026                if (!intent.debugCheck()) {
9027                    Log.w(TAG, "==> For Provider " + p.info.name);
9028                }
9029                addFilter(intent);
9030            }
9031        }
9032
9033        public final void removeProvider(PackageParser.Provider p) {
9034            mProviders.remove(p.getComponentName());
9035            if (DEBUG_SHOW_INFO) {
9036                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9037                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9038                Log.v(TAG, "    Class=" + p.info.name);
9039            }
9040            final int NI = p.intents.size();
9041            int j;
9042            for (j = 0; j < NI; j++) {
9043                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9044                if (DEBUG_SHOW_INFO) {
9045                    Log.v(TAG, "    IntentFilter:");
9046                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9047                }
9048                removeFilter(intent);
9049            }
9050        }
9051
9052        @Override
9053        protected boolean allowFilterResult(
9054                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9055            ProviderInfo filterPi = filter.provider.info;
9056            for (int i = dest.size() - 1; i >= 0; i--) {
9057                ProviderInfo destPi = dest.get(i).providerInfo;
9058                if (destPi.name == filterPi.name
9059                        && destPi.packageName == filterPi.packageName) {
9060                    return false;
9061                }
9062            }
9063            return true;
9064        }
9065
9066        @Override
9067        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9068            return new PackageParser.ProviderIntentInfo[size];
9069        }
9070
9071        @Override
9072        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9073            if (!sUserManager.exists(userId))
9074                return true;
9075            PackageParser.Package p = filter.provider.owner;
9076            if (p != null) {
9077                PackageSetting ps = (PackageSetting) p.mExtras;
9078                if (ps != null) {
9079                    // System apps are never considered stopped for purposes of
9080                    // filtering, because there may be no way for the user to
9081                    // actually re-launch them.
9082                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9083                            && ps.getStopped(userId);
9084                }
9085            }
9086            return false;
9087        }
9088
9089        @Override
9090        protected boolean isPackageForFilter(String packageName,
9091                PackageParser.ProviderIntentInfo info) {
9092            return packageName.equals(info.provider.owner.packageName);
9093        }
9094
9095        @Override
9096        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9097                int match, int userId) {
9098            if (!sUserManager.exists(userId))
9099                return null;
9100            final PackageParser.ProviderIntentInfo info = filter;
9101            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9102                return null;
9103            }
9104            final PackageParser.Provider provider = info.provider;
9105            if (mSafeMode && (provider.info.applicationInfo.flags
9106                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9107                return null;
9108            }
9109            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9110            if (ps == null) {
9111                return null;
9112            }
9113            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9114                    ps.readUserState(userId), userId);
9115            if (pi == null) {
9116                return null;
9117            }
9118            final ResolveInfo res = new ResolveInfo();
9119            res.providerInfo = pi;
9120            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9121                res.filter = filter;
9122            }
9123            res.priority = info.getPriority();
9124            res.preferredOrder = provider.owner.mPreferredOrder;
9125            res.match = match;
9126            res.isDefault = info.hasDefault;
9127            res.labelRes = info.labelRes;
9128            res.nonLocalizedLabel = info.nonLocalizedLabel;
9129            res.icon = info.icon;
9130            res.system = res.providerInfo.applicationInfo.isSystemApp();
9131            return res;
9132        }
9133
9134        @Override
9135        protected void sortResults(List<ResolveInfo> results) {
9136            Collections.sort(results, mResolvePrioritySorter);
9137        }
9138
9139        @Override
9140        protected void dumpFilter(PrintWriter out, String prefix,
9141                PackageParser.ProviderIntentInfo filter) {
9142            out.print(prefix);
9143            out.print(
9144                    Integer.toHexString(System.identityHashCode(filter.provider)));
9145            out.print(' ');
9146            filter.provider.printComponentShortName(out);
9147            out.print(" filter ");
9148            out.println(Integer.toHexString(System.identityHashCode(filter)));
9149        }
9150
9151        @Override
9152        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9153            return filter.provider;
9154        }
9155
9156        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9157            PackageParser.Provider provider = (PackageParser.Provider)label;
9158            out.print(prefix); out.print(
9159                    Integer.toHexString(System.identityHashCode(provider)));
9160                    out.print(' ');
9161                    provider.printComponentShortName(out);
9162            if (count > 1) {
9163                out.print(" ("); out.print(count); out.print(" filters)");
9164            }
9165            out.println();
9166        }
9167
9168        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9169                = new ArrayMap<ComponentName, PackageParser.Provider>();
9170        private int mFlags;
9171    };
9172
9173    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9174            new Comparator<ResolveInfo>() {
9175        public int compare(ResolveInfo r1, ResolveInfo r2) {
9176            int v1 = r1.priority;
9177            int v2 = r2.priority;
9178            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9179            if (v1 != v2) {
9180                return (v1 > v2) ? -1 : 1;
9181            }
9182            v1 = r1.preferredOrder;
9183            v2 = r2.preferredOrder;
9184            if (v1 != v2) {
9185                return (v1 > v2) ? -1 : 1;
9186            }
9187            if (r1.isDefault != r2.isDefault) {
9188                return r1.isDefault ? -1 : 1;
9189            }
9190            v1 = r1.match;
9191            v2 = r2.match;
9192            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9193            if (v1 != v2) {
9194                return (v1 > v2) ? -1 : 1;
9195            }
9196            if (r1.system != r2.system) {
9197                return r1.system ? -1 : 1;
9198            }
9199            return 0;
9200        }
9201    };
9202
9203    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9204            new Comparator<ProviderInfo>() {
9205        public int compare(ProviderInfo p1, ProviderInfo p2) {
9206            final int v1 = p1.initOrder;
9207            final int v2 = p2.initOrder;
9208            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9209        }
9210    };
9211
9212    final void sendPackageBroadcast(final String action, final String pkg,
9213            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9214            final int[] userIds) {
9215        mHandler.post(new Runnable() {
9216            @Override
9217            public void run() {
9218                try {
9219                    final IActivityManager am = ActivityManagerNative.getDefault();
9220                    if (am == null) return;
9221                    final int[] resolvedUserIds;
9222                    if (userIds == null) {
9223                        resolvedUserIds = am.getRunningUserIds();
9224                    } else {
9225                        resolvedUserIds = userIds;
9226                    }
9227                    for (int id : resolvedUserIds) {
9228                        final Intent intent = new Intent(action,
9229                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9230                        if (extras != null) {
9231                            intent.putExtras(extras);
9232                        }
9233                        if (targetPkg != null) {
9234                            intent.setPackage(targetPkg);
9235                        }
9236                        // Modify the UID when posting to other users
9237                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9238                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9239                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9240                            intent.putExtra(Intent.EXTRA_UID, uid);
9241                        }
9242                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9243                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9244                        if (DEBUG_BROADCASTS) {
9245                            RuntimeException here = new RuntimeException("here");
9246                            here.fillInStackTrace();
9247                            Slog.d(TAG, "Sending to user " + id + ": "
9248                                    + intent.toShortString(false, true, false, false)
9249                                    + " " + intent.getExtras(), here);
9250                        }
9251                        am.broadcastIntent(null, intent, null, finishedReceiver,
9252                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9253                                null, finishedReceiver != null, false, id);
9254                    }
9255                } catch (RemoteException ex) {
9256                }
9257            }
9258        });
9259    }
9260
9261    /**
9262     * Check if the external storage media is available. This is true if there
9263     * is a mounted external storage medium or if the external storage is
9264     * emulated.
9265     */
9266    private boolean isExternalMediaAvailable() {
9267        return mMediaMounted || Environment.isExternalStorageEmulated();
9268    }
9269
9270    @Override
9271    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9272        // writer
9273        synchronized (mPackages) {
9274            if (!isExternalMediaAvailable()) {
9275                // If the external storage is no longer mounted at this point,
9276                // the caller may not have been able to delete all of this
9277                // packages files and can not delete any more.  Bail.
9278                return null;
9279            }
9280            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9281            if (lastPackage != null) {
9282                pkgs.remove(lastPackage);
9283            }
9284            if (pkgs.size() > 0) {
9285                return pkgs.get(0);
9286            }
9287        }
9288        return null;
9289    }
9290
9291    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9292        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9293                userId, andCode ? 1 : 0, packageName);
9294        if (mSystemReady) {
9295            msg.sendToTarget();
9296        } else {
9297            if (mPostSystemReadyMessages == null) {
9298                mPostSystemReadyMessages = new ArrayList<>();
9299            }
9300            mPostSystemReadyMessages.add(msg);
9301        }
9302    }
9303
9304    void startCleaningPackages() {
9305        // reader
9306        synchronized (mPackages) {
9307            if (!isExternalMediaAvailable()) {
9308                return;
9309            }
9310            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9311                return;
9312            }
9313        }
9314        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9315        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9316        IActivityManager am = ActivityManagerNative.getDefault();
9317        if (am != null) {
9318            try {
9319                am.startService(null, intent, null, mContext.getOpPackageName(),
9320                        UserHandle.USER_OWNER);
9321            } catch (RemoteException e) {
9322            }
9323        }
9324    }
9325
9326    @Override
9327    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9328            int installFlags, String installerPackageName, VerificationParams verificationParams,
9329            String packageAbiOverride) {
9330        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9331                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9332    }
9333
9334    @Override
9335    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9336            int installFlags, String installerPackageName, VerificationParams verificationParams,
9337            String packageAbiOverride, int userId) {
9338        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9339
9340        final int callingUid = Binder.getCallingUid();
9341        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9342
9343        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9344            try {
9345                if (observer != null) {
9346                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9347                }
9348            } catch (RemoteException re) {
9349            }
9350            return;
9351        }
9352
9353        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9354            installFlags |= PackageManager.INSTALL_FROM_ADB;
9355
9356        } else {
9357            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9358            // about installerPackageName.
9359
9360            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9361            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9362        }
9363
9364        UserHandle user;
9365        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9366            user = UserHandle.ALL;
9367        } else {
9368            user = new UserHandle(userId);
9369        }
9370
9371        // Only system components can circumvent runtime permissions when installing.
9372        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9373                && mContext.checkCallingOrSelfPermission(Manifest.permission
9374                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9375            throw new SecurityException("You need the "
9376                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9377                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9378        }
9379
9380        verificationParams.setInstallerUid(callingUid);
9381
9382        final File originFile = new File(originPath);
9383        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9384
9385        final Message msg = mHandler.obtainMessage(INIT_COPY);
9386        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9387                null, verificationParams, user, packageAbiOverride);
9388        mHandler.sendMessage(msg);
9389    }
9390
9391    void installStage(String packageName, File stagedDir, String stagedCid,
9392            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9393            String installerPackageName, int installerUid, UserHandle user) {
9394        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9395                params.referrerUri, installerUid, null);
9396        verifParams.setInstallerUid(installerUid);
9397
9398        final OriginInfo origin;
9399        if (stagedDir != null) {
9400            origin = OriginInfo.fromStagedFile(stagedDir);
9401        } else {
9402            origin = OriginInfo.fromStagedContainer(stagedCid);
9403        }
9404
9405        final Message msg = mHandler.obtainMessage(INIT_COPY);
9406        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9407                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9408        mHandler.sendMessage(msg);
9409    }
9410
9411    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9412        Bundle extras = new Bundle(1);
9413        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9414
9415        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9416                packageName, extras, null, null, new int[] {userId});
9417        try {
9418            IActivityManager am = ActivityManagerNative.getDefault();
9419            final boolean isSystem =
9420                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9421            if (isSystem && am.isUserRunning(userId, false)) {
9422                // The just-installed/enabled app is bundled on the system, so presumed
9423                // to be able to run automatically without needing an explicit launch.
9424                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9425                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9426                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9427                        .setPackage(packageName);
9428                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9429                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9430            }
9431        } catch (RemoteException e) {
9432            // shouldn't happen
9433            Slog.w(TAG, "Unable to bootstrap installed package", e);
9434        }
9435    }
9436
9437    @Override
9438    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9439            int userId) {
9440        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9441        PackageSetting pkgSetting;
9442        final int uid = Binder.getCallingUid();
9443        enforceCrossUserPermission(uid, userId, true, true,
9444                "setApplicationHiddenSetting for user " + userId);
9445
9446        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9447            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9448            return false;
9449        }
9450
9451        long callingId = Binder.clearCallingIdentity();
9452        try {
9453            boolean sendAdded = false;
9454            boolean sendRemoved = false;
9455            // writer
9456            synchronized (mPackages) {
9457                pkgSetting = mSettings.mPackages.get(packageName);
9458                if (pkgSetting == null) {
9459                    return false;
9460                }
9461                if (pkgSetting.getHidden(userId) != hidden) {
9462                    pkgSetting.setHidden(hidden, userId);
9463                    mSettings.writePackageRestrictionsLPr(userId);
9464                    if (hidden) {
9465                        sendRemoved = true;
9466                    } else {
9467                        sendAdded = true;
9468                    }
9469                }
9470            }
9471            if (sendAdded) {
9472                sendPackageAddedForUser(packageName, pkgSetting, userId);
9473                return true;
9474            }
9475            if (sendRemoved) {
9476                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9477                        "hiding pkg");
9478                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9479            }
9480        } finally {
9481            Binder.restoreCallingIdentity(callingId);
9482        }
9483        return false;
9484    }
9485
9486    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9487            int userId) {
9488        final PackageRemovedInfo info = new PackageRemovedInfo();
9489        info.removedPackage = packageName;
9490        info.removedUsers = new int[] {userId};
9491        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9492        info.sendBroadcast(false, false, false);
9493    }
9494
9495    /**
9496     * Returns true if application is not found or there was an error. Otherwise it returns
9497     * the hidden state of the package for the given user.
9498     */
9499    @Override
9500    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9501        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9502        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9503                false, "getApplicationHidden for user " + userId);
9504        PackageSetting pkgSetting;
9505        long callingId = Binder.clearCallingIdentity();
9506        try {
9507            // writer
9508            synchronized (mPackages) {
9509                pkgSetting = mSettings.mPackages.get(packageName);
9510                if (pkgSetting == null) {
9511                    return true;
9512                }
9513                return pkgSetting.getHidden(userId);
9514            }
9515        } finally {
9516            Binder.restoreCallingIdentity(callingId);
9517        }
9518    }
9519
9520    /**
9521     * @hide
9522     */
9523    @Override
9524    public int installExistingPackageAsUser(String packageName, int userId) {
9525        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9526                null);
9527        PackageSetting pkgSetting;
9528        final int uid = Binder.getCallingUid();
9529        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9530                + userId);
9531        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9532            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9533        }
9534
9535        long callingId = Binder.clearCallingIdentity();
9536        try {
9537            boolean sendAdded = false;
9538
9539            // writer
9540            synchronized (mPackages) {
9541                pkgSetting = mSettings.mPackages.get(packageName);
9542                if (pkgSetting == null) {
9543                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9544                }
9545                if (!pkgSetting.getInstalled(userId)) {
9546                    pkgSetting.setInstalled(true, userId);
9547                    pkgSetting.setHidden(false, userId);
9548                    mSettings.writePackageRestrictionsLPr(userId);
9549                    sendAdded = true;
9550                }
9551            }
9552
9553            if (sendAdded) {
9554                sendPackageAddedForUser(packageName, pkgSetting, userId);
9555            }
9556        } finally {
9557            Binder.restoreCallingIdentity(callingId);
9558        }
9559
9560        return PackageManager.INSTALL_SUCCEEDED;
9561    }
9562
9563    boolean isUserRestricted(int userId, String restrictionKey) {
9564        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9565        if (restrictions.getBoolean(restrictionKey, false)) {
9566            Log.w(TAG, "User is restricted: " + restrictionKey);
9567            return true;
9568        }
9569        return false;
9570    }
9571
9572    @Override
9573    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9574        mContext.enforceCallingOrSelfPermission(
9575                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9576                "Only package verification agents can verify applications");
9577
9578        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9579        final PackageVerificationResponse response = new PackageVerificationResponse(
9580                verificationCode, Binder.getCallingUid());
9581        msg.arg1 = id;
9582        msg.obj = response;
9583        mHandler.sendMessage(msg);
9584    }
9585
9586    @Override
9587    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9588            long millisecondsToDelay) {
9589        mContext.enforceCallingOrSelfPermission(
9590                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9591                "Only package verification agents can extend verification timeouts");
9592
9593        final PackageVerificationState state = mPendingVerification.get(id);
9594        final PackageVerificationResponse response = new PackageVerificationResponse(
9595                verificationCodeAtTimeout, Binder.getCallingUid());
9596
9597        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9598            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9599        }
9600        if (millisecondsToDelay < 0) {
9601            millisecondsToDelay = 0;
9602        }
9603        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9604                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9605            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9606        }
9607
9608        if ((state != null) && !state.timeoutExtended()) {
9609            state.extendTimeout();
9610
9611            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9612            msg.arg1 = id;
9613            msg.obj = response;
9614            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9615        }
9616    }
9617
9618    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9619            int verificationCode, UserHandle user) {
9620        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9621        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9622        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9623        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9624        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9625
9626        mContext.sendBroadcastAsUser(intent, user,
9627                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9628    }
9629
9630    private ComponentName matchComponentForVerifier(String packageName,
9631            List<ResolveInfo> receivers) {
9632        ActivityInfo targetReceiver = null;
9633
9634        final int NR = receivers.size();
9635        for (int i = 0; i < NR; i++) {
9636            final ResolveInfo info = receivers.get(i);
9637            if (info.activityInfo == null) {
9638                continue;
9639            }
9640
9641            if (packageName.equals(info.activityInfo.packageName)) {
9642                targetReceiver = info.activityInfo;
9643                break;
9644            }
9645        }
9646
9647        if (targetReceiver == null) {
9648            return null;
9649        }
9650
9651        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9652    }
9653
9654    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9655            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9656        if (pkgInfo.verifiers.length == 0) {
9657            return null;
9658        }
9659
9660        final int N = pkgInfo.verifiers.length;
9661        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9662        for (int i = 0; i < N; i++) {
9663            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9664
9665            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9666                    receivers);
9667            if (comp == null) {
9668                continue;
9669            }
9670
9671            final int verifierUid = getUidForVerifier(verifierInfo);
9672            if (verifierUid == -1) {
9673                continue;
9674            }
9675
9676            if (DEBUG_VERIFY) {
9677                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9678                        + " with the correct signature");
9679            }
9680            sufficientVerifiers.add(comp);
9681            verificationState.addSufficientVerifier(verifierUid);
9682        }
9683
9684        return sufficientVerifiers;
9685    }
9686
9687    private int getUidForVerifier(VerifierInfo verifierInfo) {
9688        synchronized (mPackages) {
9689            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9690            if (pkg == null) {
9691                return -1;
9692            } else if (pkg.mSignatures.length != 1) {
9693                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9694                        + " has more than one signature; ignoring");
9695                return -1;
9696            }
9697
9698            /*
9699             * If the public key of the package's signature does not match
9700             * our expected public key, then this is a different package and
9701             * we should skip.
9702             */
9703
9704            final byte[] expectedPublicKey;
9705            try {
9706                final Signature verifierSig = pkg.mSignatures[0];
9707                final PublicKey publicKey = verifierSig.getPublicKey();
9708                expectedPublicKey = publicKey.getEncoded();
9709            } catch (CertificateException e) {
9710                return -1;
9711            }
9712
9713            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9714
9715            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9716                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9717                        + " does not have the expected public key; ignoring");
9718                return -1;
9719            }
9720
9721            return pkg.applicationInfo.uid;
9722        }
9723    }
9724
9725    @Override
9726    public void finishPackageInstall(int token) {
9727        enforceSystemOrRoot("Only the system is allowed to finish installs");
9728
9729        if (DEBUG_INSTALL) {
9730            Slog.v(TAG, "BM finishing package install for " + token);
9731        }
9732
9733        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9734        mHandler.sendMessage(msg);
9735    }
9736
9737    /**
9738     * Get the verification agent timeout.
9739     *
9740     * @return verification timeout in milliseconds
9741     */
9742    private long getVerificationTimeout() {
9743        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9744                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9745                DEFAULT_VERIFICATION_TIMEOUT);
9746    }
9747
9748    /**
9749     * Get the default verification agent response code.
9750     *
9751     * @return default verification response code
9752     */
9753    private int getDefaultVerificationResponse() {
9754        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9755                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9756                DEFAULT_VERIFICATION_RESPONSE);
9757    }
9758
9759    /**
9760     * Check whether or not package verification has been enabled.
9761     *
9762     * @return true if verification should be performed
9763     */
9764    private boolean isVerificationEnabled(int userId, int installFlags) {
9765        if (!DEFAULT_VERIFY_ENABLE) {
9766            return false;
9767        }
9768
9769        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9770
9771        // Check if installing from ADB
9772        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9773            // Do not run verification in a test harness environment
9774            if (ActivityManager.isRunningInTestHarness()) {
9775                return false;
9776            }
9777            if (ensureVerifyAppsEnabled) {
9778                return true;
9779            }
9780            // Check if the developer does not want package verification for ADB installs
9781            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9782                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9783                return false;
9784            }
9785        }
9786
9787        if (ensureVerifyAppsEnabled) {
9788            return true;
9789        }
9790
9791        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9792                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9793    }
9794
9795    @Override
9796    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9797            throws RemoteException {
9798        mContext.enforceCallingOrSelfPermission(
9799                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9800                "Only intentfilter verification agents can verify applications");
9801
9802        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9803        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9804                Binder.getCallingUid(), verificationCode, failedDomains);
9805        msg.arg1 = id;
9806        msg.obj = response;
9807        mHandler.sendMessage(msg);
9808    }
9809
9810    @Override
9811    public int getIntentVerificationStatus(String packageName, int userId) {
9812        synchronized (mPackages) {
9813            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9814        }
9815    }
9816
9817    @Override
9818    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9819        mContext.enforceCallingOrSelfPermission(
9820                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9821
9822        boolean result = false;
9823        synchronized (mPackages) {
9824            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9825        }
9826        if (result) {
9827            scheduleWritePackageRestrictionsLocked(userId);
9828        }
9829        return result;
9830    }
9831
9832    @Override
9833    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9834        synchronized (mPackages) {
9835            return mSettings.getIntentFilterVerificationsLPr(packageName);
9836        }
9837    }
9838
9839    @Override
9840    public List<IntentFilter> getAllIntentFilters(String packageName) {
9841        if (TextUtils.isEmpty(packageName)) {
9842            return Collections.<IntentFilter>emptyList();
9843        }
9844        synchronized (mPackages) {
9845            PackageParser.Package pkg = mPackages.get(packageName);
9846            if (pkg == null || pkg.activities == null) {
9847                return Collections.<IntentFilter>emptyList();
9848            }
9849            final int count = pkg.activities.size();
9850            ArrayList<IntentFilter> result = new ArrayList<>();
9851            for (int n=0; n<count; n++) {
9852                PackageParser.Activity activity = pkg.activities.get(n);
9853                if (activity.intents != null || activity.intents.size() > 0) {
9854                    result.addAll(activity.intents);
9855                }
9856            }
9857            return result;
9858        }
9859    }
9860
9861    @Override
9862    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9863        mContext.enforceCallingOrSelfPermission(
9864                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9865
9866        synchronized (mPackages) {
9867            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9868            if (packageName != null) {
9869                result |= updateIntentVerificationStatus(packageName,
9870                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9871                        UserHandle.myUserId());
9872                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9873                        packageName, userId);
9874            }
9875            return result;
9876        }
9877    }
9878
9879    @Override
9880    public String getDefaultBrowserPackageName(int userId) {
9881        synchronized (mPackages) {
9882            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9883        }
9884    }
9885
9886    /**
9887     * Get the "allow unknown sources" setting.
9888     *
9889     * @return the current "allow unknown sources" setting
9890     */
9891    private int getUnknownSourcesSettings() {
9892        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9893                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9894                -1);
9895    }
9896
9897    @Override
9898    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9899        final int uid = Binder.getCallingUid();
9900        // writer
9901        synchronized (mPackages) {
9902            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9903            if (targetPackageSetting == null) {
9904                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9905            }
9906
9907            PackageSetting installerPackageSetting;
9908            if (installerPackageName != null) {
9909                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9910                if (installerPackageSetting == null) {
9911                    throw new IllegalArgumentException("Unknown installer package: "
9912                            + installerPackageName);
9913                }
9914            } else {
9915                installerPackageSetting = null;
9916            }
9917
9918            Signature[] callerSignature;
9919            Object obj = mSettings.getUserIdLPr(uid);
9920            if (obj != null) {
9921                if (obj instanceof SharedUserSetting) {
9922                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9923                } else if (obj instanceof PackageSetting) {
9924                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9925                } else {
9926                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9927                }
9928            } else {
9929                throw new SecurityException("Unknown calling uid " + uid);
9930            }
9931
9932            // Verify: can't set installerPackageName to a package that is
9933            // not signed with the same cert as the caller.
9934            if (installerPackageSetting != null) {
9935                if (compareSignatures(callerSignature,
9936                        installerPackageSetting.signatures.mSignatures)
9937                        != PackageManager.SIGNATURE_MATCH) {
9938                    throw new SecurityException(
9939                            "Caller does not have same cert as new installer package "
9940                            + installerPackageName);
9941                }
9942            }
9943
9944            // Verify: if target already has an installer package, it must
9945            // be signed with the same cert as the caller.
9946            if (targetPackageSetting.installerPackageName != null) {
9947                PackageSetting setting = mSettings.mPackages.get(
9948                        targetPackageSetting.installerPackageName);
9949                // If the currently set package isn't valid, then it's always
9950                // okay to change it.
9951                if (setting != null) {
9952                    if (compareSignatures(callerSignature,
9953                            setting.signatures.mSignatures)
9954                            != PackageManager.SIGNATURE_MATCH) {
9955                        throw new SecurityException(
9956                                "Caller does not have same cert as old installer package "
9957                                + targetPackageSetting.installerPackageName);
9958                    }
9959                }
9960            }
9961
9962            // Okay!
9963            targetPackageSetting.installerPackageName = installerPackageName;
9964            scheduleWriteSettingsLocked();
9965        }
9966    }
9967
9968    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9969        // Queue up an async operation since the package installation may take a little while.
9970        mHandler.post(new Runnable() {
9971            public void run() {
9972                mHandler.removeCallbacks(this);
9973                 // Result object to be returned
9974                PackageInstalledInfo res = new PackageInstalledInfo();
9975                res.returnCode = currentStatus;
9976                res.uid = -1;
9977                res.pkg = null;
9978                res.removedInfo = new PackageRemovedInfo();
9979                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9980                    args.doPreInstall(res.returnCode);
9981                    synchronized (mInstallLock) {
9982                        installPackageLI(args, res);
9983                    }
9984                    args.doPostInstall(res.returnCode, res.uid);
9985                }
9986
9987                // A restore should be performed at this point if (a) the install
9988                // succeeded, (b) the operation is not an update, and (c) the new
9989                // package has not opted out of backup participation.
9990                final boolean update = res.removedInfo.removedPackage != null;
9991                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9992                boolean doRestore = !update
9993                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9994
9995                // Set up the post-install work request bookkeeping.  This will be used
9996                // and cleaned up by the post-install event handling regardless of whether
9997                // there's a restore pass performed.  Token values are >= 1.
9998                int token;
9999                if (mNextInstallToken < 0) mNextInstallToken = 1;
10000                token = mNextInstallToken++;
10001
10002                PostInstallData data = new PostInstallData(args, res);
10003                mRunningInstalls.put(token, data);
10004                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10005
10006                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10007                    // Pass responsibility to the Backup Manager.  It will perform a
10008                    // restore if appropriate, then pass responsibility back to the
10009                    // Package Manager to run the post-install observer callbacks
10010                    // and broadcasts.
10011                    IBackupManager bm = IBackupManager.Stub.asInterface(
10012                            ServiceManager.getService(Context.BACKUP_SERVICE));
10013                    if (bm != null) {
10014                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10015                                + " to BM for possible restore");
10016                        try {
10017                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10018                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10019                            } else {
10020                                doRestore = false;
10021                            }
10022                        } catch (RemoteException e) {
10023                            // can't happen; the backup manager is local
10024                        } catch (Exception e) {
10025                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10026                            doRestore = false;
10027                        }
10028                    } else {
10029                        Slog.e(TAG, "Backup Manager not found!");
10030                        doRestore = false;
10031                    }
10032                }
10033
10034                if (!doRestore) {
10035                    // No restore possible, or the Backup Manager was mysteriously not
10036                    // available -- just fire the post-install work request directly.
10037                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10038                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10039                    mHandler.sendMessage(msg);
10040                }
10041            }
10042        });
10043    }
10044
10045    private abstract class HandlerParams {
10046        private static final int MAX_RETRIES = 4;
10047
10048        /**
10049         * Number of times startCopy() has been attempted and had a non-fatal
10050         * error.
10051         */
10052        private int mRetries = 0;
10053
10054        /** User handle for the user requesting the information or installation. */
10055        private final UserHandle mUser;
10056
10057        HandlerParams(UserHandle user) {
10058            mUser = user;
10059        }
10060
10061        UserHandle getUser() {
10062            return mUser;
10063        }
10064
10065        final boolean startCopy() {
10066            boolean res;
10067            try {
10068                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10069
10070                if (++mRetries > MAX_RETRIES) {
10071                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10072                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10073                    handleServiceError();
10074                    return false;
10075                } else {
10076                    handleStartCopy();
10077                    res = true;
10078                }
10079            } catch (RemoteException e) {
10080                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10081                mHandler.sendEmptyMessage(MCS_RECONNECT);
10082                res = false;
10083            }
10084            handleReturnCode();
10085            return res;
10086        }
10087
10088        final void serviceError() {
10089            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10090            handleServiceError();
10091            handleReturnCode();
10092        }
10093
10094        abstract void handleStartCopy() throws RemoteException;
10095        abstract void handleServiceError();
10096        abstract void handleReturnCode();
10097    }
10098
10099    class MeasureParams extends HandlerParams {
10100        private final PackageStats mStats;
10101        private boolean mSuccess;
10102
10103        private final IPackageStatsObserver mObserver;
10104
10105        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10106            super(new UserHandle(stats.userHandle));
10107            mObserver = observer;
10108            mStats = stats;
10109        }
10110
10111        @Override
10112        public String toString() {
10113            return "MeasureParams{"
10114                + Integer.toHexString(System.identityHashCode(this))
10115                + " " + mStats.packageName + "}";
10116        }
10117
10118        @Override
10119        void handleStartCopy() throws RemoteException {
10120            synchronized (mInstallLock) {
10121                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10122            }
10123
10124            if (mSuccess) {
10125                final boolean mounted;
10126                if (Environment.isExternalStorageEmulated()) {
10127                    mounted = true;
10128                } else {
10129                    final String status = Environment.getExternalStorageState();
10130                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10131                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10132                }
10133
10134                if (mounted) {
10135                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10136
10137                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10138                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10139
10140                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10141                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10142
10143                    // Always subtract cache size, since it's a subdirectory
10144                    mStats.externalDataSize -= mStats.externalCacheSize;
10145
10146                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10147                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10148
10149                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10150                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10151                }
10152            }
10153        }
10154
10155        @Override
10156        void handleReturnCode() {
10157            if (mObserver != null) {
10158                try {
10159                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10160                } catch (RemoteException e) {
10161                    Slog.i(TAG, "Observer no longer exists.");
10162                }
10163            }
10164        }
10165
10166        @Override
10167        void handleServiceError() {
10168            Slog.e(TAG, "Could not measure application " + mStats.packageName
10169                            + " external storage");
10170        }
10171    }
10172
10173    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10174            throws RemoteException {
10175        long result = 0;
10176        for (File path : paths) {
10177            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10178        }
10179        return result;
10180    }
10181
10182    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10183        for (File path : paths) {
10184            try {
10185                mcs.clearDirectory(path.getAbsolutePath());
10186            } catch (RemoteException e) {
10187            }
10188        }
10189    }
10190
10191    static class OriginInfo {
10192        /**
10193         * Location where install is coming from, before it has been
10194         * copied/renamed into place. This could be a single monolithic APK
10195         * file, or a cluster directory. This location may be untrusted.
10196         */
10197        final File file;
10198        final String cid;
10199
10200        /**
10201         * Flag indicating that {@link #file} or {@link #cid} has already been
10202         * staged, meaning downstream users don't need to defensively copy the
10203         * contents.
10204         */
10205        final boolean staged;
10206
10207        /**
10208         * Flag indicating that {@link #file} or {@link #cid} is an already
10209         * installed app that is being moved.
10210         */
10211        final boolean existing;
10212
10213        final String resolvedPath;
10214        final File resolvedFile;
10215
10216        static OriginInfo fromNothing() {
10217            return new OriginInfo(null, null, false, false);
10218        }
10219
10220        static OriginInfo fromUntrustedFile(File file) {
10221            return new OriginInfo(file, null, false, false);
10222        }
10223
10224        static OriginInfo fromExistingFile(File file) {
10225            return new OriginInfo(file, null, false, true);
10226        }
10227
10228        static OriginInfo fromStagedFile(File file) {
10229            return new OriginInfo(file, null, true, false);
10230        }
10231
10232        static OriginInfo fromStagedContainer(String cid) {
10233            return new OriginInfo(null, cid, true, false);
10234        }
10235
10236        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10237            this.file = file;
10238            this.cid = cid;
10239            this.staged = staged;
10240            this.existing = existing;
10241
10242            if (cid != null) {
10243                resolvedPath = PackageHelper.getSdDir(cid);
10244                resolvedFile = new File(resolvedPath);
10245            } else if (file != null) {
10246                resolvedPath = file.getAbsolutePath();
10247                resolvedFile = file;
10248            } else {
10249                resolvedPath = null;
10250                resolvedFile = null;
10251            }
10252        }
10253    }
10254
10255    class MoveInfo {
10256        final int moveId;
10257        final String fromUuid;
10258        final String toUuid;
10259        final String packageName;
10260        final String dataAppName;
10261        final int appId;
10262        final String seinfo;
10263
10264        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10265                String dataAppName, int appId, String seinfo) {
10266            this.moveId = moveId;
10267            this.fromUuid = fromUuid;
10268            this.toUuid = toUuid;
10269            this.packageName = packageName;
10270            this.dataAppName = dataAppName;
10271            this.appId = appId;
10272            this.seinfo = seinfo;
10273        }
10274    }
10275
10276    class InstallParams extends HandlerParams {
10277        final OriginInfo origin;
10278        final MoveInfo move;
10279        final IPackageInstallObserver2 observer;
10280        int installFlags;
10281        final String installerPackageName;
10282        final String volumeUuid;
10283        final VerificationParams verificationParams;
10284        private InstallArgs mArgs;
10285        private int mRet;
10286        final String packageAbiOverride;
10287
10288        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10289                int installFlags, String installerPackageName, String volumeUuid,
10290                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10291            super(user);
10292            this.origin = origin;
10293            this.move = move;
10294            this.observer = observer;
10295            this.installFlags = installFlags;
10296            this.installerPackageName = installerPackageName;
10297            this.volumeUuid = volumeUuid;
10298            this.verificationParams = verificationParams;
10299            this.packageAbiOverride = packageAbiOverride;
10300        }
10301
10302        @Override
10303        public String toString() {
10304            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10305                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10306        }
10307
10308        public ManifestDigest getManifestDigest() {
10309            if (verificationParams == null) {
10310                return null;
10311            }
10312            return verificationParams.getManifestDigest();
10313        }
10314
10315        private int installLocationPolicy(PackageInfoLite pkgLite) {
10316            String packageName = pkgLite.packageName;
10317            int installLocation = pkgLite.installLocation;
10318            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10319            // reader
10320            synchronized (mPackages) {
10321                PackageParser.Package pkg = mPackages.get(packageName);
10322                if (pkg != null) {
10323                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10324                        // Check for downgrading.
10325                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10326                            try {
10327                                checkDowngrade(pkg, pkgLite);
10328                            } catch (PackageManagerException e) {
10329                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10330                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10331                            }
10332                        }
10333                        // Check for updated system application.
10334                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10335                            if (onSd) {
10336                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10337                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10338                            }
10339                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10340                        } else {
10341                            if (onSd) {
10342                                // Install flag overrides everything.
10343                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10344                            }
10345                            // If current upgrade specifies particular preference
10346                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10347                                // Application explicitly specified internal.
10348                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10349                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10350                                // App explictly prefers external. Let policy decide
10351                            } else {
10352                                // Prefer previous location
10353                                if (isExternal(pkg)) {
10354                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10355                                }
10356                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10357                            }
10358                        }
10359                    } else {
10360                        // Invalid install. Return error code
10361                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10362                    }
10363                }
10364            }
10365            // All the special cases have been taken care of.
10366            // Return result based on recommended install location.
10367            if (onSd) {
10368                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10369            }
10370            return pkgLite.recommendedInstallLocation;
10371        }
10372
10373        /*
10374         * Invoke remote method to get package information and install
10375         * location values. Override install location based on default
10376         * policy if needed and then create install arguments based
10377         * on the install location.
10378         */
10379        public void handleStartCopy() throws RemoteException {
10380            int ret = PackageManager.INSTALL_SUCCEEDED;
10381
10382            // If we're already staged, we've firmly committed to an install location
10383            if (origin.staged) {
10384                if (origin.file != null) {
10385                    installFlags |= PackageManager.INSTALL_INTERNAL;
10386                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10387                } else if (origin.cid != null) {
10388                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10389                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10390                } else {
10391                    throw new IllegalStateException("Invalid stage location");
10392                }
10393            }
10394
10395            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10396            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10397
10398            PackageInfoLite pkgLite = null;
10399
10400            if (onInt && onSd) {
10401                // Check if both bits are set.
10402                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10403                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10404            } else {
10405                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10406                        packageAbiOverride);
10407
10408                /*
10409                 * If we have too little free space, try to free cache
10410                 * before giving up.
10411                 */
10412                if (!origin.staged && pkgLite.recommendedInstallLocation
10413                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10414                    // TODO: focus freeing disk space on the target device
10415                    final StorageManager storage = StorageManager.from(mContext);
10416                    final long lowThreshold = storage.getStorageLowBytes(
10417                            Environment.getDataDirectory());
10418
10419                    final long sizeBytes = mContainerService.calculateInstalledSize(
10420                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10421
10422                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10423                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10424                                installFlags, packageAbiOverride);
10425                    }
10426
10427                    /*
10428                     * The cache free must have deleted the file we
10429                     * downloaded to install.
10430                     *
10431                     * TODO: fix the "freeCache" call to not delete
10432                     *       the file we care about.
10433                     */
10434                    if (pkgLite.recommendedInstallLocation
10435                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10436                        pkgLite.recommendedInstallLocation
10437                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10438                    }
10439                }
10440            }
10441
10442            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10443                int loc = pkgLite.recommendedInstallLocation;
10444                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10445                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10446                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10447                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10448                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10449                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10450                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10451                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10452                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10453                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10454                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10455                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10456                } else {
10457                    // Override with defaults if needed.
10458                    loc = installLocationPolicy(pkgLite);
10459                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10460                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10461                    } else if (!onSd && !onInt) {
10462                        // Override install location with flags
10463                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10464                            // Set the flag to install on external media.
10465                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10466                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10467                        } else {
10468                            // Make sure the flag for installing on external
10469                            // media is unset
10470                            installFlags |= PackageManager.INSTALL_INTERNAL;
10471                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10472                        }
10473                    }
10474                }
10475            }
10476
10477            final InstallArgs args = createInstallArgs(this);
10478            mArgs = args;
10479
10480            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10481                 /*
10482                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10483                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10484                 */
10485                int userIdentifier = getUser().getIdentifier();
10486                if (userIdentifier == UserHandle.USER_ALL
10487                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10488                    userIdentifier = UserHandle.USER_OWNER;
10489                }
10490
10491                /*
10492                 * Determine if we have any installed package verifiers. If we
10493                 * do, then we'll defer to them to verify the packages.
10494                 */
10495                final int requiredUid = mRequiredVerifierPackage == null ? -1
10496                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10497                if (!origin.existing && requiredUid != -1
10498                        && isVerificationEnabled(userIdentifier, installFlags)) {
10499                    final Intent verification = new Intent(
10500                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10501                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10502                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10503                            PACKAGE_MIME_TYPE);
10504                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10505
10506                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10507                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10508                            0 /* TODO: Which userId? */);
10509
10510                    if (DEBUG_VERIFY) {
10511                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10512                                + verification.toString() + " with " + pkgLite.verifiers.length
10513                                + " optional verifiers");
10514                    }
10515
10516                    final int verificationId = mPendingVerificationToken++;
10517
10518                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10519
10520                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10521                            installerPackageName);
10522
10523                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10524                            installFlags);
10525
10526                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10527                            pkgLite.packageName);
10528
10529                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10530                            pkgLite.versionCode);
10531
10532                    if (verificationParams != null) {
10533                        if (verificationParams.getVerificationURI() != null) {
10534                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10535                                 verificationParams.getVerificationURI());
10536                        }
10537                        if (verificationParams.getOriginatingURI() != null) {
10538                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10539                                  verificationParams.getOriginatingURI());
10540                        }
10541                        if (verificationParams.getReferrer() != null) {
10542                            verification.putExtra(Intent.EXTRA_REFERRER,
10543                                  verificationParams.getReferrer());
10544                        }
10545                        if (verificationParams.getOriginatingUid() >= 0) {
10546                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10547                                  verificationParams.getOriginatingUid());
10548                        }
10549                        if (verificationParams.getInstallerUid() >= 0) {
10550                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10551                                  verificationParams.getInstallerUid());
10552                        }
10553                    }
10554
10555                    final PackageVerificationState verificationState = new PackageVerificationState(
10556                            requiredUid, args);
10557
10558                    mPendingVerification.append(verificationId, verificationState);
10559
10560                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10561                            receivers, verificationState);
10562
10563                    /*
10564                     * If any sufficient verifiers were listed in the package
10565                     * manifest, attempt to ask them.
10566                     */
10567                    if (sufficientVerifiers != null) {
10568                        final int N = sufficientVerifiers.size();
10569                        if (N == 0) {
10570                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10571                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10572                        } else {
10573                            for (int i = 0; i < N; i++) {
10574                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10575
10576                                final Intent sufficientIntent = new Intent(verification);
10577                                sufficientIntent.setComponent(verifierComponent);
10578
10579                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10580                            }
10581                        }
10582                    }
10583
10584                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10585                            mRequiredVerifierPackage, receivers);
10586                    if (ret == PackageManager.INSTALL_SUCCEEDED
10587                            && mRequiredVerifierPackage != null) {
10588                        /*
10589                         * Send the intent to the required verification agent,
10590                         * but only start the verification timeout after the
10591                         * target BroadcastReceivers have run.
10592                         */
10593                        verification.setComponent(requiredVerifierComponent);
10594                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10595                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10596                                new BroadcastReceiver() {
10597                                    @Override
10598                                    public void onReceive(Context context, Intent intent) {
10599                                        final Message msg = mHandler
10600                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10601                                        msg.arg1 = verificationId;
10602                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10603                                    }
10604                                }, null, 0, null, null);
10605
10606                        /*
10607                         * We don't want the copy to proceed until verification
10608                         * succeeds, so null out this field.
10609                         */
10610                        mArgs = null;
10611                    }
10612                } else {
10613                    /*
10614                     * No package verification is enabled, so immediately start
10615                     * the remote call to initiate copy using temporary file.
10616                     */
10617                    ret = args.copyApk(mContainerService, true);
10618                }
10619            }
10620
10621            mRet = ret;
10622        }
10623
10624        @Override
10625        void handleReturnCode() {
10626            // If mArgs is null, then MCS couldn't be reached. When it
10627            // reconnects, it will try again to install. At that point, this
10628            // will succeed.
10629            if (mArgs != null) {
10630                processPendingInstall(mArgs, mRet);
10631            }
10632        }
10633
10634        @Override
10635        void handleServiceError() {
10636            mArgs = createInstallArgs(this);
10637            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10638        }
10639
10640        public boolean isForwardLocked() {
10641            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10642        }
10643    }
10644
10645    /**
10646     * Used during creation of InstallArgs
10647     *
10648     * @param installFlags package installation flags
10649     * @return true if should be installed on external storage
10650     */
10651    private static boolean installOnExternalAsec(int installFlags) {
10652        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10653            return false;
10654        }
10655        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10656            return true;
10657        }
10658        return false;
10659    }
10660
10661    /**
10662     * Used during creation of InstallArgs
10663     *
10664     * @param installFlags package installation flags
10665     * @return true if should be installed as forward locked
10666     */
10667    private static boolean installForwardLocked(int installFlags) {
10668        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10669    }
10670
10671    private InstallArgs createInstallArgs(InstallParams params) {
10672        if (params.move != null) {
10673            return new MoveInstallArgs(params);
10674        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10675            return new AsecInstallArgs(params);
10676        } else {
10677            return new FileInstallArgs(params);
10678        }
10679    }
10680
10681    /**
10682     * Create args that describe an existing installed package. Typically used
10683     * when cleaning up old installs, or used as a move source.
10684     */
10685    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10686            String resourcePath, String[] instructionSets) {
10687        final boolean isInAsec;
10688        if (installOnExternalAsec(installFlags)) {
10689            /* Apps on SD card are always in ASEC containers. */
10690            isInAsec = true;
10691        } else if (installForwardLocked(installFlags)
10692                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10693            /*
10694             * Forward-locked apps are only in ASEC containers if they're the
10695             * new style
10696             */
10697            isInAsec = true;
10698        } else {
10699            isInAsec = false;
10700        }
10701
10702        if (isInAsec) {
10703            return new AsecInstallArgs(codePath, instructionSets,
10704                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10705        } else {
10706            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10707        }
10708    }
10709
10710    static abstract class InstallArgs {
10711        /** @see InstallParams#origin */
10712        final OriginInfo origin;
10713        /** @see InstallParams#move */
10714        final MoveInfo move;
10715
10716        final IPackageInstallObserver2 observer;
10717        // Always refers to PackageManager flags only
10718        final int installFlags;
10719        final String installerPackageName;
10720        final String volumeUuid;
10721        final ManifestDigest manifestDigest;
10722        final UserHandle user;
10723        final String abiOverride;
10724
10725        // The list of instruction sets supported by this app. This is currently
10726        // only used during the rmdex() phase to clean up resources. We can get rid of this
10727        // if we move dex files under the common app path.
10728        /* nullable */ String[] instructionSets;
10729
10730        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10731                int installFlags, String installerPackageName, String volumeUuid,
10732                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10733                String abiOverride) {
10734            this.origin = origin;
10735            this.move = move;
10736            this.installFlags = installFlags;
10737            this.observer = observer;
10738            this.installerPackageName = installerPackageName;
10739            this.volumeUuid = volumeUuid;
10740            this.manifestDigest = manifestDigest;
10741            this.user = user;
10742            this.instructionSets = instructionSets;
10743            this.abiOverride = abiOverride;
10744        }
10745
10746        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10747        abstract int doPreInstall(int status);
10748
10749        /**
10750         * Rename package into final resting place. All paths on the given
10751         * scanned package should be updated to reflect the rename.
10752         */
10753        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10754        abstract int doPostInstall(int status, int uid);
10755
10756        /** @see PackageSettingBase#codePathString */
10757        abstract String getCodePath();
10758        /** @see PackageSettingBase#resourcePathString */
10759        abstract String getResourcePath();
10760
10761        // Need installer lock especially for dex file removal.
10762        abstract void cleanUpResourcesLI();
10763        abstract boolean doPostDeleteLI(boolean delete);
10764
10765        /**
10766         * Called before the source arguments are copied. This is used mostly
10767         * for MoveParams when it needs to read the source file to put it in the
10768         * destination.
10769         */
10770        int doPreCopy() {
10771            return PackageManager.INSTALL_SUCCEEDED;
10772        }
10773
10774        /**
10775         * Called after the source arguments are copied. This is used mostly for
10776         * MoveParams when it needs to read the source file to put it in the
10777         * destination.
10778         *
10779         * @return
10780         */
10781        int doPostCopy(int uid) {
10782            return PackageManager.INSTALL_SUCCEEDED;
10783        }
10784
10785        protected boolean isFwdLocked() {
10786            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10787        }
10788
10789        protected boolean isExternalAsec() {
10790            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10791        }
10792
10793        UserHandle getUser() {
10794            return user;
10795        }
10796    }
10797
10798    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10799        if (!allCodePaths.isEmpty()) {
10800            if (instructionSets == null) {
10801                throw new IllegalStateException("instructionSet == null");
10802            }
10803            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10804            for (String codePath : allCodePaths) {
10805                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10806                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10807                    if (retCode < 0) {
10808                        Slog.w(TAG, "Couldn't remove dex file for package: "
10809                                + " at location " + codePath + ", retcode=" + retCode);
10810                        // we don't consider this to be a failure of the core package deletion
10811                    }
10812                }
10813            }
10814        }
10815    }
10816
10817    /**
10818     * Logic to handle installation of non-ASEC applications, including copying
10819     * and renaming logic.
10820     */
10821    class FileInstallArgs extends InstallArgs {
10822        private File codeFile;
10823        private File resourceFile;
10824
10825        // Example topology:
10826        // /data/app/com.example/base.apk
10827        // /data/app/com.example/split_foo.apk
10828        // /data/app/com.example/lib/arm/libfoo.so
10829        // /data/app/com.example/lib/arm64/libfoo.so
10830        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10831
10832        /** New install */
10833        FileInstallArgs(InstallParams params) {
10834            super(params.origin, params.move, params.observer, params.installFlags,
10835                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10836                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10837            if (isFwdLocked()) {
10838                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10839            }
10840        }
10841
10842        /** Existing install */
10843        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10844            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10845                    null);
10846            this.codeFile = (codePath != null) ? new File(codePath) : null;
10847            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10848        }
10849
10850        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10851            if (origin.staged) {
10852                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10853                codeFile = origin.file;
10854                resourceFile = origin.file;
10855                return PackageManager.INSTALL_SUCCEEDED;
10856            }
10857
10858            try {
10859                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10860                codeFile = tempDir;
10861                resourceFile = tempDir;
10862            } catch (IOException e) {
10863                Slog.w(TAG, "Failed to create copy file: " + e);
10864                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10865            }
10866
10867            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10868                @Override
10869                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10870                    if (!FileUtils.isValidExtFilename(name)) {
10871                        throw new IllegalArgumentException("Invalid filename: " + name);
10872                    }
10873                    try {
10874                        final File file = new File(codeFile, name);
10875                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10876                                O_RDWR | O_CREAT, 0644);
10877                        Os.chmod(file.getAbsolutePath(), 0644);
10878                        return new ParcelFileDescriptor(fd);
10879                    } catch (ErrnoException e) {
10880                        throw new RemoteException("Failed to open: " + e.getMessage());
10881                    }
10882                }
10883            };
10884
10885            int ret = PackageManager.INSTALL_SUCCEEDED;
10886            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10887            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10888                Slog.e(TAG, "Failed to copy package");
10889                return ret;
10890            }
10891
10892            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10893            NativeLibraryHelper.Handle handle = null;
10894            try {
10895                handle = NativeLibraryHelper.Handle.create(codeFile);
10896                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10897                        abiOverride);
10898            } catch (IOException e) {
10899                Slog.e(TAG, "Copying native libraries failed", e);
10900                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10901            } finally {
10902                IoUtils.closeQuietly(handle);
10903            }
10904
10905            return ret;
10906        }
10907
10908        int doPreInstall(int status) {
10909            if (status != PackageManager.INSTALL_SUCCEEDED) {
10910                cleanUp();
10911            }
10912            return status;
10913        }
10914
10915        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10916            if (status != PackageManager.INSTALL_SUCCEEDED) {
10917                cleanUp();
10918                return false;
10919            }
10920
10921            final File targetDir = codeFile.getParentFile();
10922            final File beforeCodeFile = codeFile;
10923            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10924
10925            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10926            try {
10927                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10928            } catch (ErrnoException e) {
10929                Slog.w(TAG, "Failed to rename", e);
10930                return false;
10931            }
10932
10933            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10934                Slog.w(TAG, "Failed to restorecon");
10935                return false;
10936            }
10937
10938            // Reflect the rename internally
10939            codeFile = afterCodeFile;
10940            resourceFile = afterCodeFile;
10941
10942            // Reflect the rename in scanned details
10943            pkg.codePath = afterCodeFile.getAbsolutePath();
10944            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10945                    pkg.baseCodePath);
10946            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10947                    pkg.splitCodePaths);
10948
10949            // Reflect the rename in app info
10950            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10951            pkg.applicationInfo.setCodePath(pkg.codePath);
10952            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10953            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10954            pkg.applicationInfo.setResourcePath(pkg.codePath);
10955            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10956            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10957
10958            return true;
10959        }
10960
10961        int doPostInstall(int status, int uid) {
10962            if (status != PackageManager.INSTALL_SUCCEEDED) {
10963                cleanUp();
10964            }
10965            return status;
10966        }
10967
10968        @Override
10969        String getCodePath() {
10970            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10971        }
10972
10973        @Override
10974        String getResourcePath() {
10975            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10976        }
10977
10978        private boolean cleanUp() {
10979            if (codeFile == null || !codeFile.exists()) {
10980                return false;
10981            }
10982
10983            if (codeFile.isDirectory()) {
10984                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10985            } else {
10986                codeFile.delete();
10987            }
10988
10989            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10990                resourceFile.delete();
10991            }
10992
10993            return true;
10994        }
10995
10996        void cleanUpResourcesLI() {
10997            // Try enumerating all code paths before deleting
10998            List<String> allCodePaths = Collections.EMPTY_LIST;
10999            if (codeFile != null && codeFile.exists()) {
11000                try {
11001                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11002                    allCodePaths = pkg.getAllCodePaths();
11003                } catch (PackageParserException e) {
11004                    // Ignored; we tried our best
11005                }
11006            }
11007
11008            cleanUp();
11009            removeDexFiles(allCodePaths, instructionSets);
11010        }
11011
11012        boolean doPostDeleteLI(boolean delete) {
11013            // XXX err, shouldn't we respect the delete flag?
11014            cleanUpResourcesLI();
11015            return true;
11016        }
11017    }
11018
11019    private boolean isAsecExternal(String cid) {
11020        final String asecPath = PackageHelper.getSdFilesystem(cid);
11021        return !asecPath.startsWith(mAsecInternalPath);
11022    }
11023
11024    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11025            PackageManagerException {
11026        if (copyRet < 0) {
11027            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11028                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11029                throw new PackageManagerException(copyRet, message);
11030            }
11031        }
11032    }
11033
11034    /**
11035     * Extract the MountService "container ID" from the full code path of an
11036     * .apk.
11037     */
11038    static String cidFromCodePath(String fullCodePath) {
11039        int eidx = fullCodePath.lastIndexOf("/");
11040        String subStr1 = fullCodePath.substring(0, eidx);
11041        int sidx = subStr1.lastIndexOf("/");
11042        return subStr1.substring(sidx+1, eidx);
11043    }
11044
11045    /**
11046     * Logic to handle installation of ASEC applications, including copying and
11047     * renaming logic.
11048     */
11049    class AsecInstallArgs extends InstallArgs {
11050        static final String RES_FILE_NAME = "pkg.apk";
11051        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11052
11053        String cid;
11054        String packagePath;
11055        String resourcePath;
11056
11057        /** New install */
11058        AsecInstallArgs(InstallParams params) {
11059            super(params.origin, params.move, params.observer, params.installFlags,
11060                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11061                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11062        }
11063
11064        /** Existing install */
11065        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11066                        boolean isExternal, boolean isForwardLocked) {
11067            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11068                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11069                    instructionSets, null);
11070            // Hackily pretend we're still looking at a full code path
11071            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11072                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11073            }
11074
11075            // Extract cid from fullCodePath
11076            int eidx = fullCodePath.lastIndexOf("/");
11077            String subStr1 = fullCodePath.substring(0, eidx);
11078            int sidx = subStr1.lastIndexOf("/");
11079            cid = subStr1.substring(sidx+1, eidx);
11080            setMountPath(subStr1);
11081        }
11082
11083        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11084            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11085                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11086                    instructionSets, null);
11087            this.cid = cid;
11088            setMountPath(PackageHelper.getSdDir(cid));
11089        }
11090
11091        void createCopyFile() {
11092            cid = mInstallerService.allocateExternalStageCidLegacy();
11093        }
11094
11095        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11096            if (origin.staged) {
11097                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11098                cid = origin.cid;
11099                setMountPath(PackageHelper.getSdDir(cid));
11100                return PackageManager.INSTALL_SUCCEEDED;
11101            }
11102
11103            if (temp) {
11104                createCopyFile();
11105            } else {
11106                /*
11107                 * Pre-emptively destroy the container since it's destroyed if
11108                 * copying fails due to it existing anyway.
11109                 */
11110                PackageHelper.destroySdDir(cid);
11111            }
11112
11113            final String newMountPath = imcs.copyPackageToContainer(
11114                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11115                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11116
11117            if (newMountPath != null) {
11118                setMountPath(newMountPath);
11119                return PackageManager.INSTALL_SUCCEEDED;
11120            } else {
11121                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11122            }
11123        }
11124
11125        @Override
11126        String getCodePath() {
11127            return packagePath;
11128        }
11129
11130        @Override
11131        String getResourcePath() {
11132            return resourcePath;
11133        }
11134
11135        int doPreInstall(int status) {
11136            if (status != PackageManager.INSTALL_SUCCEEDED) {
11137                // Destroy container
11138                PackageHelper.destroySdDir(cid);
11139            } else {
11140                boolean mounted = PackageHelper.isContainerMounted(cid);
11141                if (!mounted) {
11142                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11143                            Process.SYSTEM_UID);
11144                    if (newMountPath != null) {
11145                        setMountPath(newMountPath);
11146                    } else {
11147                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11148                    }
11149                }
11150            }
11151            return status;
11152        }
11153
11154        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11155            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11156            String newMountPath = null;
11157            if (PackageHelper.isContainerMounted(cid)) {
11158                // Unmount the container
11159                if (!PackageHelper.unMountSdDir(cid)) {
11160                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11161                    return false;
11162                }
11163            }
11164            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11165                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11166                        " which might be stale. Will try to clean up.");
11167                // Clean up the stale container and proceed to recreate.
11168                if (!PackageHelper.destroySdDir(newCacheId)) {
11169                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11170                    return false;
11171                }
11172                // Successfully cleaned up stale container. Try to rename again.
11173                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11174                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11175                            + " inspite of cleaning it up.");
11176                    return false;
11177                }
11178            }
11179            if (!PackageHelper.isContainerMounted(newCacheId)) {
11180                Slog.w(TAG, "Mounting container " + newCacheId);
11181                newMountPath = PackageHelper.mountSdDir(newCacheId,
11182                        getEncryptKey(), Process.SYSTEM_UID);
11183            } else {
11184                newMountPath = PackageHelper.getSdDir(newCacheId);
11185            }
11186            if (newMountPath == null) {
11187                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11188                return false;
11189            }
11190            Log.i(TAG, "Succesfully renamed " + cid +
11191                    " to " + newCacheId +
11192                    " at new path: " + newMountPath);
11193            cid = newCacheId;
11194
11195            final File beforeCodeFile = new File(packagePath);
11196            setMountPath(newMountPath);
11197            final File afterCodeFile = new File(packagePath);
11198
11199            // Reflect the rename in scanned details
11200            pkg.codePath = afterCodeFile.getAbsolutePath();
11201            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11202                    pkg.baseCodePath);
11203            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11204                    pkg.splitCodePaths);
11205
11206            // Reflect the rename in app info
11207            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11208            pkg.applicationInfo.setCodePath(pkg.codePath);
11209            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11210            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11211            pkg.applicationInfo.setResourcePath(pkg.codePath);
11212            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11213            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11214
11215            return true;
11216        }
11217
11218        private void setMountPath(String mountPath) {
11219            final File mountFile = new File(mountPath);
11220
11221            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11222            if (monolithicFile.exists()) {
11223                packagePath = monolithicFile.getAbsolutePath();
11224                if (isFwdLocked()) {
11225                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11226                } else {
11227                    resourcePath = packagePath;
11228                }
11229            } else {
11230                packagePath = mountFile.getAbsolutePath();
11231                resourcePath = packagePath;
11232            }
11233        }
11234
11235        int doPostInstall(int status, int uid) {
11236            if (status != PackageManager.INSTALL_SUCCEEDED) {
11237                cleanUp();
11238            } else {
11239                final int groupOwner;
11240                final String protectedFile;
11241                if (isFwdLocked()) {
11242                    groupOwner = UserHandle.getSharedAppGid(uid);
11243                    protectedFile = RES_FILE_NAME;
11244                } else {
11245                    groupOwner = -1;
11246                    protectedFile = null;
11247                }
11248
11249                if (uid < Process.FIRST_APPLICATION_UID
11250                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11251                    Slog.e(TAG, "Failed to finalize " + cid);
11252                    PackageHelper.destroySdDir(cid);
11253                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11254                }
11255
11256                boolean mounted = PackageHelper.isContainerMounted(cid);
11257                if (!mounted) {
11258                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11259                }
11260            }
11261            return status;
11262        }
11263
11264        private void cleanUp() {
11265            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11266
11267            // Destroy secure container
11268            PackageHelper.destroySdDir(cid);
11269        }
11270
11271        private List<String> getAllCodePaths() {
11272            final File codeFile = new File(getCodePath());
11273            if (codeFile != null && codeFile.exists()) {
11274                try {
11275                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11276                    return pkg.getAllCodePaths();
11277                } catch (PackageParserException e) {
11278                    // Ignored; we tried our best
11279                }
11280            }
11281            return Collections.EMPTY_LIST;
11282        }
11283
11284        void cleanUpResourcesLI() {
11285            // Enumerate all code paths before deleting
11286            cleanUpResourcesLI(getAllCodePaths());
11287        }
11288
11289        private void cleanUpResourcesLI(List<String> allCodePaths) {
11290            cleanUp();
11291            removeDexFiles(allCodePaths, instructionSets);
11292        }
11293
11294        String getPackageName() {
11295            return getAsecPackageName(cid);
11296        }
11297
11298        boolean doPostDeleteLI(boolean delete) {
11299            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11300            final List<String> allCodePaths = getAllCodePaths();
11301            boolean mounted = PackageHelper.isContainerMounted(cid);
11302            if (mounted) {
11303                // Unmount first
11304                if (PackageHelper.unMountSdDir(cid)) {
11305                    mounted = false;
11306                }
11307            }
11308            if (!mounted && delete) {
11309                cleanUpResourcesLI(allCodePaths);
11310            }
11311            return !mounted;
11312        }
11313
11314        @Override
11315        int doPreCopy() {
11316            if (isFwdLocked()) {
11317                if (!PackageHelper.fixSdPermissions(cid,
11318                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11319                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11320                }
11321            }
11322
11323            return PackageManager.INSTALL_SUCCEEDED;
11324        }
11325
11326        @Override
11327        int doPostCopy(int uid) {
11328            if (isFwdLocked()) {
11329                if (uid < Process.FIRST_APPLICATION_UID
11330                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11331                                RES_FILE_NAME)) {
11332                    Slog.e(TAG, "Failed to finalize " + cid);
11333                    PackageHelper.destroySdDir(cid);
11334                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11335                }
11336            }
11337
11338            return PackageManager.INSTALL_SUCCEEDED;
11339        }
11340    }
11341
11342    /**
11343     * Logic to handle movement of existing installed applications.
11344     */
11345    class MoveInstallArgs extends InstallArgs {
11346        private File codeFile;
11347        private File resourceFile;
11348
11349        /** New install */
11350        MoveInstallArgs(InstallParams params) {
11351            super(params.origin, params.move, params.observer, params.installFlags,
11352                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11353                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11354        }
11355
11356        int copyApk(IMediaContainerService imcs, boolean temp) {
11357            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11358                    + move.fromUuid + " to " + move.toUuid);
11359            synchronized (mInstaller) {
11360                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11361                        move.dataAppName, move.appId, move.seinfo) != 0) {
11362                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11363                }
11364            }
11365
11366            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11367            resourceFile = codeFile;
11368            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11369
11370            return PackageManager.INSTALL_SUCCEEDED;
11371        }
11372
11373        int doPreInstall(int status) {
11374            if (status != PackageManager.INSTALL_SUCCEEDED) {
11375                cleanUp(move.toUuid);
11376            }
11377            return status;
11378        }
11379
11380        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11381            if (status != PackageManager.INSTALL_SUCCEEDED) {
11382                cleanUp(move.toUuid);
11383                return false;
11384            }
11385
11386            // Reflect the move in app info
11387            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11388            pkg.applicationInfo.setCodePath(pkg.codePath);
11389            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11390            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11391            pkg.applicationInfo.setResourcePath(pkg.codePath);
11392            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11393            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11394
11395            return true;
11396        }
11397
11398        int doPostInstall(int status, int uid) {
11399            if (status == PackageManager.INSTALL_SUCCEEDED) {
11400                cleanUp(move.fromUuid);
11401            } else {
11402                cleanUp(move.toUuid);
11403            }
11404            return status;
11405        }
11406
11407        @Override
11408        String getCodePath() {
11409            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11410        }
11411
11412        @Override
11413        String getResourcePath() {
11414            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11415        }
11416
11417        private boolean cleanUp(String volumeUuid) {
11418            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11419                    move.dataAppName);
11420            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11421            synchronized (mInstallLock) {
11422                // Clean up both app data and code
11423                removeDataDirsLI(volumeUuid, move.packageName);
11424                if (codeFile.isDirectory()) {
11425                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11426                } else {
11427                    codeFile.delete();
11428                }
11429            }
11430            return true;
11431        }
11432
11433        void cleanUpResourcesLI() {
11434            throw new UnsupportedOperationException();
11435        }
11436
11437        boolean doPostDeleteLI(boolean delete) {
11438            throw new UnsupportedOperationException();
11439        }
11440    }
11441
11442    static String getAsecPackageName(String packageCid) {
11443        int idx = packageCid.lastIndexOf("-");
11444        if (idx == -1) {
11445            return packageCid;
11446        }
11447        return packageCid.substring(0, idx);
11448    }
11449
11450    // Utility method used to create code paths based on package name and available index.
11451    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11452        String idxStr = "";
11453        int idx = 1;
11454        // Fall back to default value of idx=1 if prefix is not
11455        // part of oldCodePath
11456        if (oldCodePath != null) {
11457            String subStr = oldCodePath;
11458            // Drop the suffix right away
11459            if (suffix != null && subStr.endsWith(suffix)) {
11460                subStr = subStr.substring(0, subStr.length() - suffix.length());
11461            }
11462            // If oldCodePath already contains prefix find out the
11463            // ending index to either increment or decrement.
11464            int sidx = subStr.lastIndexOf(prefix);
11465            if (sidx != -1) {
11466                subStr = subStr.substring(sidx + prefix.length());
11467                if (subStr != null) {
11468                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11469                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11470                    }
11471                    try {
11472                        idx = Integer.parseInt(subStr);
11473                        if (idx <= 1) {
11474                            idx++;
11475                        } else {
11476                            idx--;
11477                        }
11478                    } catch(NumberFormatException e) {
11479                    }
11480                }
11481            }
11482        }
11483        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11484        return prefix + idxStr;
11485    }
11486
11487    private File getNextCodePath(File targetDir, String packageName) {
11488        int suffix = 1;
11489        File result;
11490        do {
11491            result = new File(targetDir, packageName + "-" + suffix);
11492            suffix++;
11493        } while (result.exists());
11494        return result;
11495    }
11496
11497    // Utility method that returns the relative package path with respect
11498    // to the installation directory. Like say for /data/data/com.test-1.apk
11499    // string com.test-1 is returned.
11500    static String deriveCodePathName(String codePath) {
11501        if (codePath == null) {
11502            return null;
11503        }
11504        final File codeFile = new File(codePath);
11505        final String name = codeFile.getName();
11506        if (codeFile.isDirectory()) {
11507            return name;
11508        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11509            final int lastDot = name.lastIndexOf('.');
11510            return name.substring(0, lastDot);
11511        } else {
11512            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11513            return null;
11514        }
11515    }
11516
11517    class PackageInstalledInfo {
11518        String name;
11519        int uid;
11520        // The set of users that originally had this package installed.
11521        int[] origUsers;
11522        // The set of users that now have this package installed.
11523        int[] newUsers;
11524        PackageParser.Package pkg;
11525        int returnCode;
11526        String returnMsg;
11527        PackageRemovedInfo removedInfo;
11528
11529        public void setError(int code, String msg) {
11530            returnCode = code;
11531            returnMsg = msg;
11532            Slog.w(TAG, msg);
11533        }
11534
11535        public void setError(String msg, PackageParserException e) {
11536            returnCode = e.error;
11537            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11538            Slog.w(TAG, msg, e);
11539        }
11540
11541        public void setError(String msg, PackageManagerException e) {
11542            returnCode = e.error;
11543            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11544            Slog.w(TAG, msg, e);
11545        }
11546
11547        // In some error cases we want to convey more info back to the observer
11548        String origPackage;
11549        String origPermission;
11550    }
11551
11552    /*
11553     * Install a non-existing package.
11554     */
11555    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11556            UserHandle user, String installerPackageName, String volumeUuid,
11557            PackageInstalledInfo res) {
11558        // Remember this for later, in case we need to rollback this install
11559        String pkgName = pkg.packageName;
11560
11561        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11562        final boolean dataDirExists = Environment
11563                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11564        synchronized(mPackages) {
11565            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11566                // A package with the same name is already installed, though
11567                // it has been renamed to an older name.  The package we
11568                // are trying to install should be installed as an update to
11569                // the existing one, but that has not been requested, so bail.
11570                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11571                        + " without first uninstalling package running as "
11572                        + mSettings.mRenamedPackages.get(pkgName));
11573                return;
11574            }
11575            if (mPackages.containsKey(pkgName)) {
11576                // Don't allow installation over an existing package with the same name.
11577                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11578                        + " without first uninstalling.");
11579                return;
11580            }
11581        }
11582
11583        try {
11584            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11585                    System.currentTimeMillis(), user);
11586
11587            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11588            // delete the partially installed application. the data directory will have to be
11589            // restored if it was already existing
11590            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11591                // remove package from internal structures.  Note that we want deletePackageX to
11592                // delete the package data and cache directories that it created in
11593                // scanPackageLocked, unless those directories existed before we even tried to
11594                // install.
11595                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11596                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11597                                res.removedInfo, true);
11598            }
11599
11600        } catch (PackageManagerException e) {
11601            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11602        }
11603    }
11604
11605    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11606        // Can't rotate keys during boot or if sharedUser.
11607        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11608                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11609            return false;
11610        }
11611        // app is using upgradeKeySets; make sure all are valid
11612        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11613        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11614        for (int i = 0; i < upgradeKeySets.length; i++) {
11615            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11616                Slog.wtf(TAG, "Package "
11617                         + (oldPs.name != null ? oldPs.name : "<null>")
11618                         + " contains upgrade-key-set reference to unknown key-set: "
11619                         + upgradeKeySets[i]
11620                         + " reverting to signatures check.");
11621                return false;
11622            }
11623        }
11624        return true;
11625    }
11626
11627    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11628        // Upgrade keysets are being used.  Determine if new package has a superset of the
11629        // required keys.
11630        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11631        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11632        for (int i = 0; i < upgradeKeySets.length; i++) {
11633            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11634            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11635                return true;
11636            }
11637        }
11638        return false;
11639    }
11640
11641    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11642            UserHandle user, String installerPackageName, String volumeUuid,
11643            PackageInstalledInfo res) {
11644        final PackageParser.Package oldPackage;
11645        final String pkgName = pkg.packageName;
11646        final int[] allUsers;
11647        final boolean[] perUserInstalled;
11648        final boolean weFroze;
11649
11650        // First find the old package info and check signatures
11651        synchronized(mPackages) {
11652            oldPackage = mPackages.get(pkgName);
11653            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11654            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11655            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11656                if(!checkUpgradeKeySetLP(ps, pkg)) {
11657                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11658                            "New package not signed by keys specified by upgrade-keysets: "
11659                            + pkgName);
11660                    return;
11661                }
11662            } else {
11663                // default to original signature matching
11664                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11665                    != PackageManager.SIGNATURE_MATCH) {
11666                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11667                            "New package has a different signature: " + pkgName);
11668                    return;
11669                }
11670            }
11671
11672            // In case of rollback, remember per-user/profile install state
11673            allUsers = sUserManager.getUserIds();
11674            perUserInstalled = new boolean[allUsers.length];
11675            for (int i = 0; i < allUsers.length; i++) {
11676                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11677            }
11678
11679            // Mark the app as frozen to prevent launching during the upgrade
11680            // process, and then kill all running instances
11681            if (!ps.frozen) {
11682                ps.frozen = true;
11683                weFroze = true;
11684            } else {
11685                weFroze = false;
11686            }
11687        }
11688
11689        // Now that we're guarded by frozen state, kill app during upgrade
11690        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11691
11692        try {
11693            boolean sysPkg = (isSystemApp(oldPackage));
11694            if (sysPkg) {
11695                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11696                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11697            } else {
11698                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11699                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11700            }
11701        } finally {
11702            // Regardless of success or failure of upgrade steps above, always
11703            // unfreeze the package if we froze it
11704            if (weFroze) {
11705                unfreezePackage(pkgName);
11706            }
11707        }
11708    }
11709
11710    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11711            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11712            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11713            String volumeUuid, PackageInstalledInfo res) {
11714        String pkgName = deletedPackage.packageName;
11715        boolean deletedPkg = true;
11716        boolean updatedSettings = false;
11717
11718        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11719                + deletedPackage);
11720        long origUpdateTime;
11721        if (pkg.mExtras != null) {
11722            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11723        } else {
11724            origUpdateTime = 0;
11725        }
11726
11727        // First delete the existing package while retaining the data directory
11728        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11729                res.removedInfo, true)) {
11730            // If the existing package wasn't successfully deleted
11731            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11732            deletedPkg = false;
11733        } else {
11734            // Successfully deleted the old package; proceed with replace.
11735
11736            // If deleted package lived in a container, give users a chance to
11737            // relinquish resources before killing.
11738            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11739                if (DEBUG_INSTALL) {
11740                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11741                }
11742                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11743                final ArrayList<String> pkgList = new ArrayList<String>(1);
11744                pkgList.add(deletedPackage.applicationInfo.packageName);
11745                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11746            }
11747
11748            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11749            try {
11750                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11751                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11752                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11753                        perUserInstalled, res, user);
11754                updatedSettings = true;
11755            } catch (PackageManagerException e) {
11756                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11757            }
11758        }
11759
11760        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11761            // remove package from internal structures.  Note that we want deletePackageX to
11762            // delete the package data and cache directories that it created in
11763            // scanPackageLocked, unless those directories existed before we even tried to
11764            // install.
11765            if(updatedSettings) {
11766                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11767                deletePackageLI(
11768                        pkgName, null, true, allUsers, perUserInstalled,
11769                        PackageManager.DELETE_KEEP_DATA,
11770                                res.removedInfo, true);
11771            }
11772            // Since we failed to install the new package we need to restore the old
11773            // package that we deleted.
11774            if (deletedPkg) {
11775                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11776                File restoreFile = new File(deletedPackage.codePath);
11777                // Parse old package
11778                boolean oldExternal = isExternal(deletedPackage);
11779                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11780                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11781                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11782                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11783                try {
11784                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11785                } catch (PackageManagerException e) {
11786                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11787                            + e.getMessage());
11788                    return;
11789                }
11790                // Restore of old package succeeded. Update permissions.
11791                // writer
11792                synchronized (mPackages) {
11793                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11794                            UPDATE_PERMISSIONS_ALL);
11795                    // can downgrade to reader
11796                    mSettings.writeLPr();
11797                }
11798                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11799            }
11800        }
11801    }
11802
11803    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11804            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11805            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11806            String volumeUuid, PackageInstalledInfo res) {
11807        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11808                + ", old=" + deletedPackage);
11809        boolean disabledSystem = false;
11810        boolean updatedSettings = false;
11811        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11812        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11813                != 0) {
11814            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11815        }
11816        String packageName = deletedPackage.packageName;
11817        if (packageName == null) {
11818            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11819                    "Attempt to delete null packageName.");
11820            return;
11821        }
11822        PackageParser.Package oldPkg;
11823        PackageSetting oldPkgSetting;
11824        // reader
11825        synchronized (mPackages) {
11826            oldPkg = mPackages.get(packageName);
11827            oldPkgSetting = mSettings.mPackages.get(packageName);
11828            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11829                    (oldPkgSetting == null)) {
11830                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11831                        "Couldn't find package:" + packageName + " information");
11832                return;
11833            }
11834        }
11835
11836        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11837        res.removedInfo.removedPackage = packageName;
11838        // Remove existing system package
11839        removePackageLI(oldPkgSetting, true);
11840        // writer
11841        synchronized (mPackages) {
11842            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11843            if (!disabledSystem && deletedPackage != null) {
11844                // We didn't need to disable the .apk as a current system package,
11845                // which means we are replacing another update that is already
11846                // installed.  We need to make sure to delete the older one's .apk.
11847                res.removedInfo.args = createInstallArgsForExisting(0,
11848                        deletedPackage.applicationInfo.getCodePath(),
11849                        deletedPackage.applicationInfo.getResourcePath(),
11850                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11851            } else {
11852                res.removedInfo.args = null;
11853            }
11854        }
11855
11856        // Successfully disabled the old package. Now proceed with re-installation
11857        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11858
11859        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11860        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11861
11862        PackageParser.Package newPackage = null;
11863        try {
11864            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11865            if (newPackage.mExtras != null) {
11866                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11867                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11868                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11869
11870                // is the update attempting to change shared user? that isn't going to work...
11871                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11872                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11873                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11874                            + " to " + newPkgSetting.sharedUser);
11875                    updatedSettings = true;
11876                }
11877            }
11878
11879            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11880                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11881                        perUserInstalled, res, user);
11882                updatedSettings = true;
11883            }
11884
11885        } catch (PackageManagerException e) {
11886            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11887        }
11888
11889        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11890            // Re installation failed. Restore old information
11891            // Remove new pkg information
11892            if (newPackage != null) {
11893                removeInstalledPackageLI(newPackage, true);
11894            }
11895            // Add back the old system package
11896            try {
11897                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11898            } catch (PackageManagerException e) {
11899                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11900            }
11901            // Restore the old system information in Settings
11902            synchronized (mPackages) {
11903                if (disabledSystem) {
11904                    mSettings.enableSystemPackageLPw(packageName);
11905                }
11906                if (updatedSettings) {
11907                    mSettings.setInstallerPackageName(packageName,
11908                            oldPkgSetting.installerPackageName);
11909                }
11910                mSettings.writeLPr();
11911            }
11912        }
11913    }
11914
11915    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11916            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11917            UserHandle user) {
11918        String pkgName = newPackage.packageName;
11919        synchronized (mPackages) {
11920            //write settings. the installStatus will be incomplete at this stage.
11921            //note that the new package setting would have already been
11922            //added to mPackages. It hasn't been persisted yet.
11923            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11924            mSettings.writeLPr();
11925        }
11926
11927        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11928
11929        synchronized (mPackages) {
11930            updatePermissionsLPw(newPackage.packageName, newPackage,
11931                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11932                            ? UPDATE_PERMISSIONS_ALL : 0));
11933            // For system-bundled packages, we assume that installing an upgraded version
11934            // of the package implies that the user actually wants to run that new code,
11935            // so we enable the package.
11936            PackageSetting ps = mSettings.mPackages.get(pkgName);
11937            if (ps != null) {
11938                if (isSystemApp(newPackage)) {
11939                    // NB: implicit assumption that system package upgrades apply to all users
11940                    if (DEBUG_INSTALL) {
11941                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11942                    }
11943                    if (res.origUsers != null) {
11944                        for (int userHandle : res.origUsers) {
11945                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11946                                    userHandle, installerPackageName);
11947                        }
11948                    }
11949                    // Also convey the prior install/uninstall state
11950                    if (allUsers != null && perUserInstalled != null) {
11951                        for (int i = 0; i < allUsers.length; i++) {
11952                            if (DEBUG_INSTALL) {
11953                                Slog.d(TAG, "    user " + allUsers[i]
11954                                        + " => " + perUserInstalled[i]);
11955                            }
11956                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11957                        }
11958                        // these install state changes will be persisted in the
11959                        // upcoming call to mSettings.writeLPr().
11960                    }
11961                }
11962                // It's implied that when a user requests installation, they want the app to be
11963                // installed and enabled.
11964                int userId = user.getIdentifier();
11965                if (userId != UserHandle.USER_ALL) {
11966                    ps.setInstalled(true, userId);
11967                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11968                }
11969            }
11970            res.name = pkgName;
11971            res.uid = newPackage.applicationInfo.uid;
11972            res.pkg = newPackage;
11973            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11974            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11975            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11976            //to update install status
11977            mSettings.writeLPr();
11978        }
11979    }
11980
11981    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11982        final int installFlags = args.installFlags;
11983        final String installerPackageName = args.installerPackageName;
11984        final String volumeUuid = args.volumeUuid;
11985        final File tmpPackageFile = new File(args.getCodePath());
11986        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11987        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11988                || (args.volumeUuid != null));
11989        boolean replace = false;
11990        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11991        if (args.move != null) {
11992            // moving a complete application; perfom an initial scan on the new install location
11993            scanFlags |= SCAN_INITIAL;
11994        }
11995        // Result object to be returned
11996        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11997
11998        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11999        // Retrieve PackageSettings and parse package
12000        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12001                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12002                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12003        PackageParser pp = new PackageParser();
12004        pp.setSeparateProcesses(mSeparateProcesses);
12005        pp.setDisplayMetrics(mMetrics);
12006
12007        final PackageParser.Package pkg;
12008        try {
12009            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12010        } catch (PackageParserException e) {
12011            res.setError("Failed parse during installPackageLI", e);
12012            return;
12013        }
12014
12015        // Mark that we have an install time CPU ABI override.
12016        pkg.cpuAbiOverride = args.abiOverride;
12017
12018        String pkgName = res.name = pkg.packageName;
12019        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12020            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12021                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12022                return;
12023            }
12024        }
12025
12026        try {
12027            pp.collectCertificates(pkg, parseFlags);
12028            pp.collectManifestDigest(pkg);
12029        } catch (PackageParserException e) {
12030            res.setError("Failed collect during installPackageLI", e);
12031            return;
12032        }
12033
12034        /* If the installer passed in a manifest digest, compare it now. */
12035        if (args.manifestDigest != null) {
12036            if (DEBUG_INSTALL) {
12037                final String parsedManifest = pkg.manifestDigest == null ? "null"
12038                        : pkg.manifestDigest.toString();
12039                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12040                        + parsedManifest);
12041            }
12042
12043            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12044                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12045                return;
12046            }
12047        } else if (DEBUG_INSTALL) {
12048            final String parsedManifest = pkg.manifestDigest == null
12049                    ? "null" : pkg.manifestDigest.toString();
12050            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12051        }
12052
12053        // Get rid of all references to package scan path via parser.
12054        pp = null;
12055        String oldCodePath = null;
12056        boolean systemApp = false;
12057        synchronized (mPackages) {
12058            // Check if installing already existing package
12059            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12060                String oldName = mSettings.mRenamedPackages.get(pkgName);
12061                if (pkg.mOriginalPackages != null
12062                        && pkg.mOriginalPackages.contains(oldName)
12063                        && mPackages.containsKey(oldName)) {
12064                    // This package is derived from an original package,
12065                    // and this device has been updating from that original
12066                    // name.  We must continue using the original name, so
12067                    // rename the new package here.
12068                    pkg.setPackageName(oldName);
12069                    pkgName = pkg.packageName;
12070                    replace = true;
12071                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12072                            + oldName + " pkgName=" + pkgName);
12073                } else if (mPackages.containsKey(pkgName)) {
12074                    // This package, under its official name, already exists
12075                    // on the device; we should replace it.
12076                    replace = true;
12077                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12078                }
12079
12080                // Prevent apps opting out from runtime permissions
12081                if (replace) {
12082                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12083                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12084                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12085                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12086                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12087                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12088                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12089                                        + " doesn't support runtime permissions but the old"
12090                                        + " target SDK " + oldTargetSdk + " does.");
12091                        return;
12092                    }
12093                }
12094            }
12095
12096            PackageSetting ps = mSettings.mPackages.get(pkgName);
12097            if (ps != null) {
12098                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12099
12100                // Quick sanity check that we're signed correctly if updating;
12101                // we'll check this again later when scanning, but we want to
12102                // bail early here before tripping over redefined permissions.
12103                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12104                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12105                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12106                                + pkg.packageName + " upgrade keys do not match the "
12107                                + "previously installed version");
12108                        return;
12109                    }
12110                } else {
12111                    try {
12112                        verifySignaturesLP(ps, pkg);
12113                    } catch (PackageManagerException e) {
12114                        res.setError(e.error, e.getMessage());
12115                        return;
12116                    }
12117                }
12118
12119                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12120                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12121                    systemApp = (ps.pkg.applicationInfo.flags &
12122                            ApplicationInfo.FLAG_SYSTEM) != 0;
12123                }
12124                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12125            }
12126
12127            // Check whether the newly-scanned package wants to define an already-defined perm
12128            int N = pkg.permissions.size();
12129            for (int i = N-1; i >= 0; i--) {
12130                PackageParser.Permission perm = pkg.permissions.get(i);
12131                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12132                if (bp != null) {
12133                    // If the defining package is signed with our cert, it's okay.  This
12134                    // also includes the "updating the same package" case, of course.
12135                    // "updating same package" could also involve key-rotation.
12136                    final boolean sigsOk;
12137                    if (bp.sourcePackage.equals(pkg.packageName)
12138                            && (bp.packageSetting instanceof PackageSetting)
12139                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12140                                    scanFlags))) {
12141                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12142                    } else {
12143                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12144                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12145                    }
12146                    if (!sigsOk) {
12147                        // If the owning package is the system itself, we log but allow
12148                        // install to proceed; we fail the install on all other permission
12149                        // redefinitions.
12150                        if (!bp.sourcePackage.equals("android")) {
12151                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12152                                    + pkg.packageName + " attempting to redeclare permission "
12153                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12154                            res.origPermission = perm.info.name;
12155                            res.origPackage = bp.sourcePackage;
12156                            return;
12157                        } else {
12158                            Slog.w(TAG, "Package " + pkg.packageName
12159                                    + " attempting to redeclare system permission "
12160                                    + perm.info.name + "; ignoring new declaration");
12161                            pkg.permissions.remove(i);
12162                        }
12163                    }
12164                }
12165            }
12166
12167        }
12168
12169        if (systemApp && onExternal) {
12170            // Disable updates to system apps on sdcard
12171            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12172                    "Cannot install updates to system apps on sdcard");
12173            return;
12174        }
12175
12176        if (args.move != null) {
12177            // We did an in-place move, so dex is ready to roll
12178            scanFlags |= SCAN_NO_DEX;
12179            scanFlags |= SCAN_MOVE;
12180        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12181            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12182            scanFlags |= SCAN_NO_DEX;
12183
12184            try {
12185                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12186                        true /* extract libs */);
12187            } catch (PackageManagerException pme) {
12188                Slog.e(TAG, "Error deriving application ABI", pme);
12189                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12190                return;
12191            }
12192
12193            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12194            int result = mPackageDexOptimizer
12195                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12196                            false /* defer */, false /* inclDependencies */);
12197            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12198                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12199                return;
12200            }
12201        }
12202
12203        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12204            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12205            return;
12206        }
12207
12208        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12209
12210        if (replace) {
12211            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12212                    installerPackageName, volumeUuid, res);
12213        } else {
12214            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12215                    args.user, installerPackageName, volumeUuid, res);
12216        }
12217        synchronized (mPackages) {
12218            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12219            if (ps != null) {
12220                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12221            }
12222        }
12223    }
12224
12225    private void startIntentFilterVerifications(int userId, boolean replacing,
12226            PackageParser.Package pkg) {
12227        if (mIntentFilterVerifierComponent == null) {
12228            Slog.w(TAG, "No IntentFilter verification will not be done as "
12229                    + "there is no IntentFilterVerifier available!");
12230            return;
12231        }
12232
12233        final int verifierUid = getPackageUid(
12234                mIntentFilterVerifierComponent.getPackageName(),
12235                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12236
12237        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12238        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12239        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12240        mHandler.sendMessage(msg);
12241    }
12242
12243    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12244            PackageParser.Package pkg) {
12245        int size = pkg.activities.size();
12246        if (size == 0) {
12247            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12248                    "No activity, so no need to verify any IntentFilter!");
12249            return;
12250        }
12251
12252        final boolean hasDomainURLs = hasDomainURLs(pkg);
12253        if (!hasDomainURLs) {
12254            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12255                    "No domain URLs, so no need to verify any IntentFilter!");
12256            return;
12257        }
12258
12259        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12260                + " if any IntentFilter from the " + size
12261                + " Activities needs verification ...");
12262
12263        int count = 0;
12264        final String packageName = pkg.packageName;
12265
12266        synchronized (mPackages) {
12267            // If this is a new install and we see that we've already run verification for this
12268            // package, we have nothing to do: it means the state was restored from backup.
12269            if (!replacing) {
12270                IntentFilterVerificationInfo ivi =
12271                        mSettings.getIntentFilterVerificationLPr(packageName);
12272                if (ivi != null) {
12273                    if (DEBUG_DOMAIN_VERIFICATION) {
12274                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12275                                + ivi.getStatusString());
12276                    }
12277                    return;
12278                }
12279            }
12280
12281            // If any filters need to be verified, then all need to be.
12282            boolean needToVerify = false;
12283            for (PackageParser.Activity a : pkg.activities) {
12284                for (ActivityIntentInfo filter : a.intents) {
12285                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12286                        if (DEBUG_DOMAIN_VERIFICATION) {
12287                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12288                        }
12289                        needToVerify = true;
12290                        break;
12291                    }
12292                }
12293            }
12294
12295            if (needToVerify) {
12296                final int verificationId = mIntentFilterVerificationToken++;
12297                for (PackageParser.Activity a : pkg.activities) {
12298                    for (ActivityIntentInfo filter : a.intents) {
12299                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12300                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12301                                    "Verification needed for IntentFilter:" + filter.toString());
12302                            mIntentFilterVerifier.addOneIntentFilterVerification(
12303                                    verifierUid, userId, verificationId, filter, packageName);
12304                            count++;
12305                        }
12306                    }
12307                }
12308            }
12309        }
12310
12311        if (count > 0) {
12312            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12313                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12314                    +  " for userId:" + userId);
12315            mIntentFilterVerifier.startVerifications(userId);
12316        } else {
12317            if (DEBUG_DOMAIN_VERIFICATION) {
12318                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12319            }
12320        }
12321    }
12322
12323    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12324        final ComponentName cn  = filter.activity.getComponentName();
12325        final String packageName = cn.getPackageName();
12326
12327        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12328                packageName);
12329        if (ivi == null) {
12330            return true;
12331        }
12332        int status = ivi.getStatus();
12333        switch (status) {
12334            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12335            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12336                return true;
12337
12338            default:
12339                // Nothing to do
12340                return false;
12341        }
12342    }
12343
12344    private static boolean isMultiArch(PackageSetting ps) {
12345        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12346    }
12347
12348    private static boolean isMultiArch(ApplicationInfo info) {
12349        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12350    }
12351
12352    private static boolean isExternal(PackageParser.Package pkg) {
12353        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12354    }
12355
12356    private static boolean isExternal(PackageSetting ps) {
12357        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12358    }
12359
12360    private static boolean isExternal(ApplicationInfo info) {
12361        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12362    }
12363
12364    private static boolean isSystemApp(PackageParser.Package pkg) {
12365        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12366    }
12367
12368    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12369        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12370    }
12371
12372    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12373        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12374    }
12375
12376    private static boolean isSystemApp(PackageSetting ps) {
12377        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12378    }
12379
12380    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12381        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12382    }
12383
12384    private int packageFlagsToInstallFlags(PackageSetting ps) {
12385        int installFlags = 0;
12386        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12387            // This existing package was an external ASEC install when we have
12388            // the external flag without a UUID
12389            installFlags |= PackageManager.INSTALL_EXTERNAL;
12390        }
12391        if (ps.isForwardLocked()) {
12392            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12393        }
12394        return installFlags;
12395    }
12396
12397    private void deleteTempPackageFiles() {
12398        final FilenameFilter filter = new FilenameFilter() {
12399            public boolean accept(File dir, String name) {
12400                return name.startsWith("vmdl") && name.endsWith(".tmp");
12401            }
12402        };
12403        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12404            file.delete();
12405        }
12406    }
12407
12408    @Override
12409    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12410            int flags) {
12411        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12412                flags);
12413    }
12414
12415    @Override
12416    public void deletePackage(final String packageName,
12417            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12418        mContext.enforceCallingOrSelfPermission(
12419                android.Manifest.permission.DELETE_PACKAGES, null);
12420        Preconditions.checkNotNull(packageName);
12421        Preconditions.checkNotNull(observer);
12422        final int uid = Binder.getCallingUid();
12423        if (UserHandle.getUserId(uid) != userId) {
12424            mContext.enforceCallingPermission(
12425                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12426                    "deletePackage for user " + userId);
12427        }
12428        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12429            try {
12430                observer.onPackageDeleted(packageName,
12431                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12432            } catch (RemoteException re) {
12433            }
12434            return;
12435        }
12436
12437        boolean uninstallBlocked = false;
12438        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12439            int[] users = sUserManager.getUserIds();
12440            for (int i = 0; i < users.length; ++i) {
12441                if (getBlockUninstallForUser(packageName, users[i])) {
12442                    uninstallBlocked = true;
12443                    break;
12444                }
12445            }
12446        } else {
12447            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12448        }
12449        if (uninstallBlocked) {
12450            try {
12451                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12452                        null);
12453            } catch (RemoteException re) {
12454            }
12455            return;
12456        }
12457
12458        if (DEBUG_REMOVE) {
12459            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12460        }
12461        // Queue up an async operation since the package deletion may take a little while.
12462        mHandler.post(new Runnable() {
12463            public void run() {
12464                mHandler.removeCallbacks(this);
12465                final int returnCode = deletePackageX(packageName, userId, flags);
12466                if (observer != null) {
12467                    try {
12468                        observer.onPackageDeleted(packageName, returnCode, null);
12469                    } catch (RemoteException e) {
12470                        Log.i(TAG, "Observer no longer exists.");
12471                    } //end catch
12472                } //end if
12473            } //end run
12474        });
12475    }
12476
12477    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12478        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12479                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12480        try {
12481            if (dpm != null) {
12482                if (dpm.isDeviceOwner(packageName)) {
12483                    return true;
12484                }
12485                int[] users;
12486                if (userId == UserHandle.USER_ALL) {
12487                    users = sUserManager.getUserIds();
12488                } else {
12489                    users = new int[]{userId};
12490                }
12491                for (int i = 0; i < users.length; ++i) {
12492                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12493                        return true;
12494                    }
12495                }
12496            }
12497        } catch (RemoteException e) {
12498        }
12499        return false;
12500    }
12501
12502    /**
12503     *  This method is an internal method that could be get invoked either
12504     *  to delete an installed package or to clean up a failed installation.
12505     *  After deleting an installed package, a broadcast is sent to notify any
12506     *  listeners that the package has been installed. For cleaning up a failed
12507     *  installation, the broadcast is not necessary since the package's
12508     *  installation wouldn't have sent the initial broadcast either
12509     *  The key steps in deleting a package are
12510     *  deleting the package information in internal structures like mPackages,
12511     *  deleting the packages base directories through installd
12512     *  updating mSettings to reflect current status
12513     *  persisting settings for later use
12514     *  sending a broadcast if necessary
12515     */
12516    private int deletePackageX(String packageName, int userId, int flags) {
12517        final PackageRemovedInfo info = new PackageRemovedInfo();
12518        final boolean res;
12519
12520        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12521                ? UserHandle.ALL : new UserHandle(userId);
12522
12523        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12524            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12525            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12526        }
12527
12528        boolean removedForAllUsers = false;
12529        boolean systemUpdate = false;
12530
12531        // for the uninstall-updates case and restricted profiles, remember the per-
12532        // userhandle installed state
12533        int[] allUsers;
12534        boolean[] perUserInstalled;
12535        synchronized (mPackages) {
12536            PackageSetting ps = mSettings.mPackages.get(packageName);
12537            allUsers = sUserManager.getUserIds();
12538            perUserInstalled = new boolean[allUsers.length];
12539            for (int i = 0; i < allUsers.length; i++) {
12540                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12541            }
12542        }
12543
12544        synchronized (mInstallLock) {
12545            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12546            res = deletePackageLI(packageName, removeForUser,
12547                    true, allUsers, perUserInstalled,
12548                    flags | REMOVE_CHATTY, info, true);
12549            systemUpdate = info.isRemovedPackageSystemUpdate;
12550            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12551                removedForAllUsers = true;
12552            }
12553            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12554                    + " removedForAllUsers=" + removedForAllUsers);
12555        }
12556
12557        if (res) {
12558            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12559
12560            // If the removed package was a system update, the old system package
12561            // was re-enabled; we need to broadcast this information
12562            if (systemUpdate) {
12563                Bundle extras = new Bundle(1);
12564                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12565                        ? info.removedAppId : info.uid);
12566                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12567
12568                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12569                        extras, null, null, null);
12570                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12571                        extras, null, null, null);
12572                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12573                        null, packageName, null, null);
12574            }
12575        }
12576        // Force a gc here.
12577        Runtime.getRuntime().gc();
12578        // Delete the resources here after sending the broadcast to let
12579        // other processes clean up before deleting resources.
12580        if (info.args != null) {
12581            synchronized (mInstallLock) {
12582                info.args.doPostDeleteLI(true);
12583            }
12584        }
12585
12586        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12587    }
12588
12589    class PackageRemovedInfo {
12590        String removedPackage;
12591        int uid = -1;
12592        int removedAppId = -1;
12593        int[] removedUsers = null;
12594        boolean isRemovedPackageSystemUpdate = false;
12595        // Clean up resources deleted packages.
12596        InstallArgs args = null;
12597
12598        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12599            Bundle extras = new Bundle(1);
12600            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12601            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12602            if (replacing) {
12603                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12604            }
12605            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12606            if (removedPackage != null) {
12607                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12608                        extras, null, null, removedUsers);
12609                if (fullRemove && !replacing) {
12610                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12611                            extras, null, null, removedUsers);
12612                }
12613            }
12614            if (removedAppId >= 0) {
12615                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12616                        removedUsers);
12617            }
12618        }
12619    }
12620
12621    /*
12622     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12623     * flag is not set, the data directory is removed as well.
12624     * make sure this flag is set for partially installed apps. If not its meaningless to
12625     * delete a partially installed application.
12626     */
12627    private void removePackageDataLI(PackageSetting ps,
12628            int[] allUserHandles, boolean[] perUserInstalled,
12629            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12630        String packageName = ps.name;
12631        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12632        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12633        // Retrieve object to delete permissions for shared user later on
12634        final PackageSetting deletedPs;
12635        // reader
12636        synchronized (mPackages) {
12637            deletedPs = mSettings.mPackages.get(packageName);
12638            if (outInfo != null) {
12639                outInfo.removedPackage = packageName;
12640                outInfo.removedUsers = deletedPs != null
12641                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12642                        : null;
12643            }
12644        }
12645        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12646            removeDataDirsLI(ps.volumeUuid, packageName);
12647            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12648        }
12649        // writer
12650        synchronized (mPackages) {
12651            if (deletedPs != null) {
12652                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12653                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12654                    clearDefaultBrowserIfNeeded(packageName);
12655                    if (outInfo != null) {
12656                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12657                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12658                    }
12659                    updatePermissionsLPw(deletedPs.name, null, 0);
12660                    if (deletedPs.sharedUser != null) {
12661                        // Remove permissions associated with package. Since runtime
12662                        // permissions are per user we have to kill the removed package
12663                        // or packages running under the shared user of the removed
12664                        // package if revoking the permissions requested only by the removed
12665                        // package is successful and this causes a change in gids.
12666                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12667                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12668                                    userId);
12669                            if (userIdToKill == UserHandle.USER_ALL
12670                                    || userIdToKill >= UserHandle.USER_OWNER) {
12671                                // If gids changed for this user, kill all affected packages.
12672                                mHandler.post(new Runnable() {
12673                                    @Override
12674                                    public void run() {
12675                                        // This has to happen with no lock held.
12676                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12677                                                KILL_APP_REASON_GIDS_CHANGED);
12678                                    }
12679                                });
12680                                break;
12681                            }
12682                        }
12683                    }
12684                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12685                }
12686                // make sure to preserve per-user disabled state if this removal was just
12687                // a downgrade of a system app to the factory package
12688                if (allUserHandles != null && perUserInstalled != null) {
12689                    if (DEBUG_REMOVE) {
12690                        Slog.d(TAG, "Propagating install state across downgrade");
12691                    }
12692                    for (int i = 0; i < allUserHandles.length; i++) {
12693                        if (DEBUG_REMOVE) {
12694                            Slog.d(TAG, "    user " + allUserHandles[i]
12695                                    + " => " + perUserInstalled[i]);
12696                        }
12697                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12698                    }
12699                }
12700            }
12701            // can downgrade to reader
12702            if (writeSettings) {
12703                // Save settings now
12704                mSettings.writeLPr();
12705            }
12706        }
12707        if (outInfo != null) {
12708            // A user ID was deleted here. Go through all users and remove it
12709            // from KeyStore.
12710            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12711        }
12712    }
12713
12714    static boolean locationIsPrivileged(File path) {
12715        try {
12716            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12717                    .getCanonicalPath();
12718            return path.getCanonicalPath().startsWith(privilegedAppDir);
12719        } catch (IOException e) {
12720            Slog.e(TAG, "Unable to access code path " + path);
12721        }
12722        return false;
12723    }
12724
12725    /*
12726     * Tries to delete system package.
12727     */
12728    private boolean deleteSystemPackageLI(PackageSetting newPs,
12729            int[] allUserHandles, boolean[] perUserInstalled,
12730            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12731        final boolean applyUserRestrictions
12732                = (allUserHandles != null) && (perUserInstalled != null);
12733        PackageSetting disabledPs = null;
12734        // Confirm if the system package has been updated
12735        // An updated system app can be deleted. This will also have to restore
12736        // the system pkg from system partition
12737        // reader
12738        synchronized (mPackages) {
12739            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12740        }
12741        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12742                + " disabledPs=" + disabledPs);
12743        if (disabledPs == null) {
12744            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12745            return false;
12746        } else if (DEBUG_REMOVE) {
12747            Slog.d(TAG, "Deleting system pkg from data partition");
12748        }
12749        if (DEBUG_REMOVE) {
12750            if (applyUserRestrictions) {
12751                Slog.d(TAG, "Remembering install states:");
12752                for (int i = 0; i < allUserHandles.length; i++) {
12753                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12754                }
12755            }
12756        }
12757        // Delete the updated package
12758        outInfo.isRemovedPackageSystemUpdate = true;
12759        if (disabledPs.versionCode < newPs.versionCode) {
12760            // Delete data for downgrades
12761            flags &= ~PackageManager.DELETE_KEEP_DATA;
12762        } else {
12763            // Preserve data by setting flag
12764            flags |= PackageManager.DELETE_KEEP_DATA;
12765        }
12766        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12767                allUserHandles, perUserInstalled, outInfo, writeSettings);
12768        if (!ret) {
12769            return false;
12770        }
12771        // writer
12772        synchronized (mPackages) {
12773            // Reinstate the old system package
12774            mSettings.enableSystemPackageLPw(newPs.name);
12775            // Remove any native libraries from the upgraded package.
12776            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12777        }
12778        // Install the system package
12779        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12780        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12781        if (locationIsPrivileged(disabledPs.codePath)) {
12782            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12783        }
12784
12785        final PackageParser.Package newPkg;
12786        try {
12787            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12788        } catch (PackageManagerException e) {
12789            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12790            return false;
12791        }
12792
12793        // writer
12794        synchronized (mPackages) {
12795            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12796
12797            // Propagate the permissions state as we do want to drop on the floor
12798            // runtime permissions. The update permissions method below will take
12799            // care of removing obsolete permissions and grant install permissions.
12800            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12801            updatePermissionsLPw(newPkg.packageName, newPkg,
12802                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12803
12804            if (applyUserRestrictions) {
12805                if (DEBUG_REMOVE) {
12806                    Slog.d(TAG, "Propagating install state across reinstall");
12807                }
12808                for (int i = 0; i < allUserHandles.length; i++) {
12809                    if (DEBUG_REMOVE) {
12810                        Slog.d(TAG, "    user " + allUserHandles[i]
12811                                + " => " + perUserInstalled[i]);
12812                    }
12813                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12814                }
12815                // Regardless of writeSettings we need to ensure that this restriction
12816                // state propagation is persisted
12817                mSettings.writeAllUsersPackageRestrictionsLPr();
12818            }
12819            // can downgrade to reader here
12820            if (writeSettings) {
12821                mSettings.writeLPr();
12822            }
12823        }
12824        return true;
12825    }
12826
12827    private boolean deleteInstalledPackageLI(PackageSetting ps,
12828            boolean deleteCodeAndResources, int flags,
12829            int[] allUserHandles, boolean[] perUserInstalled,
12830            PackageRemovedInfo outInfo, boolean writeSettings) {
12831        if (outInfo != null) {
12832            outInfo.uid = ps.appId;
12833        }
12834
12835        // Delete package data from internal structures and also remove data if flag is set
12836        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12837
12838        // Delete application code and resources
12839        if (deleteCodeAndResources && (outInfo != null)) {
12840            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12841                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12842            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12843        }
12844        return true;
12845    }
12846
12847    @Override
12848    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12849            int userId) {
12850        mContext.enforceCallingOrSelfPermission(
12851                android.Manifest.permission.DELETE_PACKAGES, null);
12852        synchronized (mPackages) {
12853            PackageSetting ps = mSettings.mPackages.get(packageName);
12854            if (ps == null) {
12855                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12856                return false;
12857            }
12858            if (!ps.getInstalled(userId)) {
12859                // Can't block uninstall for an app that is not installed or enabled.
12860                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12861                return false;
12862            }
12863            ps.setBlockUninstall(blockUninstall, userId);
12864            mSettings.writePackageRestrictionsLPr(userId);
12865        }
12866        return true;
12867    }
12868
12869    @Override
12870    public boolean getBlockUninstallForUser(String packageName, int userId) {
12871        synchronized (mPackages) {
12872            PackageSetting ps = mSettings.mPackages.get(packageName);
12873            if (ps == null) {
12874                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12875                return false;
12876            }
12877            return ps.getBlockUninstall(userId);
12878        }
12879    }
12880
12881    /*
12882     * This method handles package deletion in general
12883     */
12884    private boolean deletePackageLI(String packageName, UserHandle user,
12885            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12886            int flags, PackageRemovedInfo outInfo,
12887            boolean writeSettings) {
12888        if (packageName == null) {
12889            Slog.w(TAG, "Attempt to delete null packageName.");
12890            return false;
12891        }
12892        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12893        PackageSetting ps;
12894        boolean dataOnly = false;
12895        int removeUser = -1;
12896        int appId = -1;
12897        synchronized (mPackages) {
12898            ps = mSettings.mPackages.get(packageName);
12899            if (ps == null) {
12900                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12901                return false;
12902            }
12903            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12904                    && user.getIdentifier() != UserHandle.USER_ALL) {
12905                // The caller is asking that the package only be deleted for a single
12906                // user.  To do this, we just mark its uninstalled state and delete
12907                // its data.  If this is a system app, we only allow this to happen if
12908                // they have set the special DELETE_SYSTEM_APP which requests different
12909                // semantics than normal for uninstalling system apps.
12910                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12911                ps.setUserState(user.getIdentifier(),
12912                        COMPONENT_ENABLED_STATE_DEFAULT,
12913                        false, //installed
12914                        true,  //stopped
12915                        true,  //notLaunched
12916                        false, //hidden
12917                        null, null, null,
12918                        false, // blockUninstall
12919                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12920                if (!isSystemApp(ps)) {
12921                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12922                        // Other user still have this package installed, so all
12923                        // we need to do is clear this user's data and save that
12924                        // it is uninstalled.
12925                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12926                        removeUser = user.getIdentifier();
12927                        appId = ps.appId;
12928                        scheduleWritePackageRestrictionsLocked(removeUser);
12929                    } else {
12930                        // We need to set it back to 'installed' so the uninstall
12931                        // broadcasts will be sent correctly.
12932                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12933                        ps.setInstalled(true, user.getIdentifier());
12934                    }
12935                } else {
12936                    // This is a system app, so we assume that the
12937                    // other users still have this package installed, so all
12938                    // we need to do is clear this user's data and save that
12939                    // it is uninstalled.
12940                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12941                    removeUser = user.getIdentifier();
12942                    appId = ps.appId;
12943                    scheduleWritePackageRestrictionsLocked(removeUser);
12944                }
12945            }
12946        }
12947
12948        if (removeUser >= 0) {
12949            // From above, we determined that we are deleting this only
12950            // for a single user.  Continue the work here.
12951            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12952            if (outInfo != null) {
12953                outInfo.removedPackage = packageName;
12954                outInfo.removedAppId = appId;
12955                outInfo.removedUsers = new int[] {removeUser};
12956            }
12957            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12958            removeKeystoreDataIfNeeded(removeUser, appId);
12959            schedulePackageCleaning(packageName, removeUser, false);
12960            synchronized (mPackages) {
12961                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12962                    scheduleWritePackageRestrictionsLocked(removeUser);
12963                }
12964                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
12965            }
12966            return true;
12967        }
12968
12969        if (dataOnly) {
12970            // Delete application data first
12971            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12972            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12973            return true;
12974        }
12975
12976        boolean ret = false;
12977        if (isSystemApp(ps)) {
12978            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12979            // When an updated system application is deleted we delete the existing resources as well and
12980            // fall back to existing code in system partition
12981            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12982                    flags, outInfo, writeSettings);
12983        } else {
12984            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12985            // Kill application pre-emptively especially for apps on sd.
12986            killApplication(packageName, ps.appId, "uninstall pkg");
12987            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12988                    allUserHandles, perUserInstalled,
12989                    outInfo, writeSettings);
12990        }
12991
12992        return ret;
12993    }
12994
12995    private final class ClearStorageConnection implements ServiceConnection {
12996        IMediaContainerService mContainerService;
12997
12998        @Override
12999        public void onServiceConnected(ComponentName name, IBinder service) {
13000            synchronized (this) {
13001                mContainerService = IMediaContainerService.Stub.asInterface(service);
13002                notifyAll();
13003            }
13004        }
13005
13006        @Override
13007        public void onServiceDisconnected(ComponentName name) {
13008        }
13009    }
13010
13011    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13012        final boolean mounted;
13013        if (Environment.isExternalStorageEmulated()) {
13014            mounted = true;
13015        } else {
13016            final String status = Environment.getExternalStorageState();
13017
13018            mounted = status.equals(Environment.MEDIA_MOUNTED)
13019                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13020        }
13021
13022        if (!mounted) {
13023            return;
13024        }
13025
13026        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13027        int[] users;
13028        if (userId == UserHandle.USER_ALL) {
13029            users = sUserManager.getUserIds();
13030        } else {
13031            users = new int[] { userId };
13032        }
13033        final ClearStorageConnection conn = new ClearStorageConnection();
13034        if (mContext.bindServiceAsUser(
13035                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13036            try {
13037                for (int curUser : users) {
13038                    long timeout = SystemClock.uptimeMillis() + 5000;
13039                    synchronized (conn) {
13040                        long now = SystemClock.uptimeMillis();
13041                        while (conn.mContainerService == null && now < timeout) {
13042                            try {
13043                                conn.wait(timeout - now);
13044                            } catch (InterruptedException e) {
13045                            }
13046                        }
13047                    }
13048                    if (conn.mContainerService == null) {
13049                        return;
13050                    }
13051
13052                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13053                    clearDirectory(conn.mContainerService,
13054                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13055                    if (allData) {
13056                        clearDirectory(conn.mContainerService,
13057                                userEnv.buildExternalStorageAppDataDirs(packageName));
13058                        clearDirectory(conn.mContainerService,
13059                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13060                    }
13061                }
13062            } finally {
13063                mContext.unbindService(conn);
13064            }
13065        }
13066    }
13067
13068    @Override
13069    public void clearApplicationUserData(final String packageName,
13070            final IPackageDataObserver observer, final int userId) {
13071        mContext.enforceCallingOrSelfPermission(
13072                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13073        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13074        // Queue up an async operation since the package deletion may take a little while.
13075        mHandler.post(new Runnable() {
13076            public void run() {
13077                mHandler.removeCallbacks(this);
13078                final boolean succeeded;
13079                synchronized (mInstallLock) {
13080                    succeeded = clearApplicationUserDataLI(packageName, userId);
13081                }
13082                clearExternalStorageDataSync(packageName, userId, true);
13083                if (succeeded) {
13084                    // invoke DeviceStorageMonitor's update method to clear any notifications
13085                    DeviceStorageMonitorInternal
13086                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13087                    if (dsm != null) {
13088                        dsm.checkMemory();
13089                    }
13090                }
13091                if(observer != null) {
13092                    try {
13093                        observer.onRemoveCompleted(packageName, succeeded);
13094                    } catch (RemoteException e) {
13095                        Log.i(TAG, "Observer no longer exists.");
13096                    }
13097                } //end if observer
13098            } //end run
13099        });
13100    }
13101
13102    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13103        if (packageName == null) {
13104            Slog.w(TAG, "Attempt to delete null packageName.");
13105            return false;
13106        }
13107
13108        // Try finding details about the requested package
13109        PackageParser.Package pkg;
13110        synchronized (mPackages) {
13111            pkg = mPackages.get(packageName);
13112            if (pkg == null) {
13113                final PackageSetting ps = mSettings.mPackages.get(packageName);
13114                if (ps != null) {
13115                    pkg = ps.pkg;
13116                }
13117            }
13118
13119            if (pkg == null) {
13120                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13121                return false;
13122            }
13123
13124            PackageSetting ps = (PackageSetting) pkg.mExtras;
13125            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13126        }
13127
13128        // Always delete data directories for package, even if we found no other
13129        // record of app. This helps users recover from UID mismatches without
13130        // resorting to a full data wipe.
13131        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13132        if (retCode < 0) {
13133            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13134            return false;
13135        }
13136
13137        final int appId = pkg.applicationInfo.uid;
13138        removeKeystoreDataIfNeeded(userId, appId);
13139
13140        // Create a native library symlink only if we have native libraries
13141        // and if the native libraries are 32 bit libraries. We do not provide
13142        // this symlink for 64 bit libraries.
13143        if (pkg.applicationInfo.primaryCpuAbi != null &&
13144                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13145            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13146            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13147                    nativeLibPath, userId) < 0) {
13148                Slog.w(TAG, "Failed linking native library dir");
13149                return false;
13150            }
13151        }
13152
13153        return true;
13154    }
13155
13156    /**
13157     * Reverts user permission state changes (permissions and flags).
13158     *
13159     * @param ps The package for which to reset.
13160     * @param userId The device user for which to do a reset.
13161     */
13162    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13163            final PackageSetting ps, final int userId) {
13164        if (ps.pkg == null) {
13165            return;
13166        }
13167
13168        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13169                | FLAG_PERMISSION_USER_FIXED
13170                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13171
13172        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13173                | FLAG_PERMISSION_POLICY_FIXED;
13174
13175        boolean writeInstallPermissions = false;
13176        boolean writeRuntimePermissions = false;
13177
13178        final int permissionCount = ps.pkg.requestedPermissions.size();
13179        for (int i = 0; i < permissionCount; i++) {
13180            String permission = ps.pkg.requestedPermissions.get(i);
13181
13182            BasePermission bp = mSettings.mPermissions.get(permission);
13183            if (bp == null) {
13184                continue;
13185            }
13186
13187            // If shared user we just reset the state to which only this app contributed.
13188            if (ps.sharedUser != null) {
13189                boolean used = false;
13190                final int packageCount = ps.sharedUser.packages.size();
13191                for (int j = 0; j < packageCount; j++) {
13192                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13193                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13194                            && pkg.pkg.requestedPermissions.contains(permission)) {
13195                        used = true;
13196                        break;
13197                    }
13198                }
13199                if (used) {
13200                    continue;
13201                }
13202            }
13203
13204            PermissionsState permissionsState = ps.getPermissionsState();
13205
13206            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13207
13208            // Always clear the user settable flags.
13209            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13210                    bp.name) != null;
13211            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13212                if (hasInstallState) {
13213                    writeInstallPermissions = true;
13214                } else {
13215                    writeRuntimePermissions = true;
13216                }
13217            }
13218
13219            // Below is only runtime permission handling.
13220            if (!bp.isRuntime()) {
13221                continue;
13222            }
13223
13224            // Never clobber system or policy.
13225            if ((oldFlags & policyOrSystemFlags) != 0) {
13226                continue;
13227            }
13228
13229            // If this permission was granted by default, make sure it is.
13230            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13231                if (permissionsState.grantRuntimePermission(bp, userId)
13232                        != PERMISSION_OPERATION_FAILURE) {
13233                    writeRuntimePermissions = true;
13234                }
13235            } else {
13236                // Otherwise, reset the permission.
13237                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13238                switch (revokeResult) {
13239                    case PERMISSION_OPERATION_SUCCESS: {
13240                        writeRuntimePermissions = true;
13241                    } break;
13242
13243                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13244                        writeRuntimePermissions = true;
13245                        // If gids changed for this user, kill all affected packages.
13246                        mHandler.post(new Runnable() {
13247                            @Override
13248                            public void run() {
13249                                // This has to happen with no lock held.
13250                                killSettingPackagesForUser(ps, userId,
13251                                        KILL_APP_REASON_GIDS_CHANGED);
13252                            }
13253                        });
13254                    } break;
13255                }
13256            }
13257        }
13258
13259        // Synchronously write as we are taking permissions away.
13260        if (writeRuntimePermissions) {
13261            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13262        }
13263
13264        // Synchronously write as we are taking permissions away.
13265        if (writeInstallPermissions) {
13266            mSettings.writeLPr();
13267        }
13268    }
13269
13270    /**
13271     * Remove entries from the keystore daemon. Will only remove it if the
13272     * {@code appId} is valid.
13273     */
13274    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13275        if (appId < 0) {
13276            return;
13277        }
13278
13279        final KeyStore keyStore = KeyStore.getInstance();
13280        if (keyStore != null) {
13281            if (userId == UserHandle.USER_ALL) {
13282                for (final int individual : sUserManager.getUserIds()) {
13283                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13284                }
13285            } else {
13286                keyStore.clearUid(UserHandle.getUid(userId, appId));
13287            }
13288        } else {
13289            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13290        }
13291    }
13292
13293    @Override
13294    public void deleteApplicationCacheFiles(final String packageName,
13295            final IPackageDataObserver observer) {
13296        mContext.enforceCallingOrSelfPermission(
13297                android.Manifest.permission.DELETE_CACHE_FILES, null);
13298        // Queue up an async operation since the package deletion may take a little while.
13299        final int userId = UserHandle.getCallingUserId();
13300        mHandler.post(new Runnable() {
13301            public void run() {
13302                mHandler.removeCallbacks(this);
13303                final boolean succeded;
13304                synchronized (mInstallLock) {
13305                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13306                }
13307                clearExternalStorageDataSync(packageName, userId, false);
13308                if (observer != null) {
13309                    try {
13310                        observer.onRemoveCompleted(packageName, succeded);
13311                    } catch (RemoteException e) {
13312                        Log.i(TAG, "Observer no longer exists.");
13313                    }
13314                } //end if observer
13315            } //end run
13316        });
13317    }
13318
13319    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13320        if (packageName == null) {
13321            Slog.w(TAG, "Attempt to delete null packageName.");
13322            return false;
13323        }
13324        PackageParser.Package p;
13325        synchronized (mPackages) {
13326            p = mPackages.get(packageName);
13327        }
13328        if (p == null) {
13329            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13330            return false;
13331        }
13332        final ApplicationInfo applicationInfo = p.applicationInfo;
13333        if (applicationInfo == null) {
13334            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13335            return false;
13336        }
13337        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13338        if (retCode < 0) {
13339            Slog.w(TAG, "Couldn't remove cache files for package: "
13340                       + packageName + " u" + userId);
13341            return false;
13342        }
13343        return true;
13344    }
13345
13346    @Override
13347    public void getPackageSizeInfo(final String packageName, int userHandle,
13348            final IPackageStatsObserver observer) {
13349        mContext.enforceCallingOrSelfPermission(
13350                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13351        if (packageName == null) {
13352            throw new IllegalArgumentException("Attempt to get size of null packageName");
13353        }
13354
13355        PackageStats stats = new PackageStats(packageName, userHandle);
13356
13357        /*
13358         * Queue up an async operation since the package measurement may take a
13359         * little while.
13360         */
13361        Message msg = mHandler.obtainMessage(INIT_COPY);
13362        msg.obj = new MeasureParams(stats, observer);
13363        mHandler.sendMessage(msg);
13364    }
13365
13366    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13367            PackageStats pStats) {
13368        if (packageName == null) {
13369            Slog.w(TAG, "Attempt to get size of null packageName.");
13370            return false;
13371        }
13372        PackageParser.Package p;
13373        boolean dataOnly = false;
13374        String libDirRoot = null;
13375        String asecPath = null;
13376        PackageSetting ps = null;
13377        synchronized (mPackages) {
13378            p = mPackages.get(packageName);
13379            ps = mSettings.mPackages.get(packageName);
13380            if(p == null) {
13381                dataOnly = true;
13382                if((ps == null) || (ps.pkg == null)) {
13383                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13384                    return false;
13385                }
13386                p = ps.pkg;
13387            }
13388            if (ps != null) {
13389                libDirRoot = ps.legacyNativeLibraryPathString;
13390            }
13391            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13392                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13393                if (secureContainerId != null) {
13394                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13395                }
13396            }
13397        }
13398        String publicSrcDir = null;
13399        if(!dataOnly) {
13400            final ApplicationInfo applicationInfo = p.applicationInfo;
13401            if (applicationInfo == null) {
13402                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13403                return false;
13404            }
13405            if (p.isForwardLocked()) {
13406                publicSrcDir = applicationInfo.getBaseResourcePath();
13407            }
13408        }
13409        // TODO: extend to measure size of split APKs
13410        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13411        // not just the first level.
13412        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13413        // just the primary.
13414        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13415        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13416                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13417        if (res < 0) {
13418            return false;
13419        }
13420
13421        // Fix-up for forward-locked applications in ASEC containers.
13422        if (!isExternal(p)) {
13423            pStats.codeSize += pStats.externalCodeSize;
13424            pStats.externalCodeSize = 0L;
13425        }
13426
13427        return true;
13428    }
13429
13430
13431    @Override
13432    public void addPackageToPreferred(String packageName) {
13433        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13434    }
13435
13436    @Override
13437    public void removePackageFromPreferred(String packageName) {
13438        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13439    }
13440
13441    @Override
13442    public List<PackageInfo> getPreferredPackages(int flags) {
13443        return new ArrayList<PackageInfo>();
13444    }
13445
13446    private int getUidTargetSdkVersionLockedLPr(int uid) {
13447        Object obj = mSettings.getUserIdLPr(uid);
13448        if (obj instanceof SharedUserSetting) {
13449            final SharedUserSetting sus = (SharedUserSetting) obj;
13450            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13451            final Iterator<PackageSetting> it = sus.packages.iterator();
13452            while (it.hasNext()) {
13453                final PackageSetting ps = it.next();
13454                if (ps.pkg != null) {
13455                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13456                    if (v < vers) vers = v;
13457                }
13458            }
13459            return vers;
13460        } else if (obj instanceof PackageSetting) {
13461            final PackageSetting ps = (PackageSetting) obj;
13462            if (ps.pkg != null) {
13463                return ps.pkg.applicationInfo.targetSdkVersion;
13464            }
13465        }
13466        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13467    }
13468
13469    @Override
13470    public void addPreferredActivity(IntentFilter filter, int match,
13471            ComponentName[] set, ComponentName activity, int userId) {
13472        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13473                "Adding preferred");
13474    }
13475
13476    private void addPreferredActivityInternal(IntentFilter filter, int match,
13477            ComponentName[] set, ComponentName activity, boolean always, int userId,
13478            String opname) {
13479        // writer
13480        int callingUid = Binder.getCallingUid();
13481        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13482        if (filter.countActions() == 0) {
13483            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13484            return;
13485        }
13486        synchronized (mPackages) {
13487            if (mContext.checkCallingOrSelfPermission(
13488                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13489                    != PackageManager.PERMISSION_GRANTED) {
13490                if (getUidTargetSdkVersionLockedLPr(callingUid)
13491                        < Build.VERSION_CODES.FROYO) {
13492                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13493                            + callingUid);
13494                    return;
13495                }
13496                mContext.enforceCallingOrSelfPermission(
13497                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13498            }
13499
13500            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13501            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13502                    + userId + ":");
13503            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13504            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13505            scheduleWritePackageRestrictionsLocked(userId);
13506        }
13507    }
13508
13509    @Override
13510    public void replacePreferredActivity(IntentFilter filter, int match,
13511            ComponentName[] set, ComponentName activity, int userId) {
13512        if (filter.countActions() != 1) {
13513            throw new IllegalArgumentException(
13514                    "replacePreferredActivity expects filter to have only 1 action.");
13515        }
13516        if (filter.countDataAuthorities() != 0
13517                || filter.countDataPaths() != 0
13518                || filter.countDataSchemes() > 1
13519                || filter.countDataTypes() != 0) {
13520            throw new IllegalArgumentException(
13521                    "replacePreferredActivity expects filter to have no data authorities, " +
13522                    "paths, or types; and at most one scheme.");
13523        }
13524
13525        final int callingUid = Binder.getCallingUid();
13526        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13527        synchronized (mPackages) {
13528            if (mContext.checkCallingOrSelfPermission(
13529                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13530                    != PackageManager.PERMISSION_GRANTED) {
13531                if (getUidTargetSdkVersionLockedLPr(callingUid)
13532                        < Build.VERSION_CODES.FROYO) {
13533                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13534                            + Binder.getCallingUid());
13535                    return;
13536                }
13537                mContext.enforceCallingOrSelfPermission(
13538                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13539            }
13540
13541            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13542            if (pir != null) {
13543                // Get all of the existing entries that exactly match this filter.
13544                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13545                if (existing != null && existing.size() == 1) {
13546                    PreferredActivity cur = existing.get(0);
13547                    if (DEBUG_PREFERRED) {
13548                        Slog.i(TAG, "Checking replace of preferred:");
13549                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13550                        if (!cur.mPref.mAlways) {
13551                            Slog.i(TAG, "  -- CUR; not mAlways!");
13552                        } else {
13553                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13554                            Slog.i(TAG, "  -- CUR: mSet="
13555                                    + Arrays.toString(cur.mPref.mSetComponents));
13556                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13557                            Slog.i(TAG, "  -- NEW: mMatch="
13558                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13559                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13560                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13561                        }
13562                    }
13563                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13564                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13565                            && cur.mPref.sameSet(set)) {
13566                        // Setting the preferred activity to what it happens to be already
13567                        if (DEBUG_PREFERRED) {
13568                            Slog.i(TAG, "Replacing with same preferred activity "
13569                                    + cur.mPref.mShortComponent + " for user "
13570                                    + userId + ":");
13571                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13572                        }
13573                        return;
13574                    }
13575                }
13576
13577                if (existing != null) {
13578                    if (DEBUG_PREFERRED) {
13579                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13580                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13581                    }
13582                    for (int i = 0; i < existing.size(); i++) {
13583                        PreferredActivity pa = existing.get(i);
13584                        if (DEBUG_PREFERRED) {
13585                            Slog.i(TAG, "Removing existing preferred activity "
13586                                    + pa.mPref.mComponent + ":");
13587                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13588                        }
13589                        pir.removeFilter(pa);
13590                    }
13591                }
13592            }
13593            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13594                    "Replacing preferred");
13595        }
13596    }
13597
13598    @Override
13599    public void clearPackagePreferredActivities(String packageName) {
13600        final int uid = Binder.getCallingUid();
13601        // writer
13602        synchronized (mPackages) {
13603            PackageParser.Package pkg = mPackages.get(packageName);
13604            if (pkg == null || pkg.applicationInfo.uid != uid) {
13605                if (mContext.checkCallingOrSelfPermission(
13606                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13607                        != PackageManager.PERMISSION_GRANTED) {
13608                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13609                            < Build.VERSION_CODES.FROYO) {
13610                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13611                                + Binder.getCallingUid());
13612                        return;
13613                    }
13614                    mContext.enforceCallingOrSelfPermission(
13615                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13616                }
13617            }
13618
13619            int user = UserHandle.getCallingUserId();
13620            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13621                scheduleWritePackageRestrictionsLocked(user);
13622            }
13623        }
13624    }
13625
13626    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13627    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13628        ArrayList<PreferredActivity> removed = null;
13629        boolean changed = false;
13630        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13631            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13632            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13633            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13634                continue;
13635            }
13636            Iterator<PreferredActivity> it = pir.filterIterator();
13637            while (it.hasNext()) {
13638                PreferredActivity pa = it.next();
13639                // Mark entry for removal only if it matches the package name
13640                // and the entry is of type "always".
13641                if (packageName == null ||
13642                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13643                                && pa.mPref.mAlways)) {
13644                    if (removed == null) {
13645                        removed = new ArrayList<PreferredActivity>();
13646                    }
13647                    removed.add(pa);
13648                }
13649            }
13650            if (removed != null) {
13651                for (int j=0; j<removed.size(); j++) {
13652                    PreferredActivity pa = removed.get(j);
13653                    pir.removeFilter(pa);
13654                }
13655                changed = true;
13656            }
13657        }
13658        return changed;
13659    }
13660
13661    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13662    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13663        if (userId == UserHandle.USER_ALL) {
13664            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13665                    sUserManager.getUserIds())) {
13666                for (int oneUserId : sUserManager.getUserIds()) {
13667                    scheduleWritePackageRestrictionsLocked(oneUserId);
13668                }
13669            }
13670        } else {
13671            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13672                scheduleWritePackageRestrictionsLocked(userId);
13673            }
13674        }
13675    }
13676
13677
13678    void clearDefaultBrowserIfNeeded(String packageName) {
13679        for (int oneUserId : sUserManager.getUserIds()) {
13680            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13681            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13682            if (packageName.equals(defaultBrowserPackageName)) {
13683                setDefaultBrowserPackageName(null, oneUserId);
13684            }
13685        }
13686    }
13687
13688    @Override
13689    public void resetPreferredActivities(int userId) {
13690        mContext.enforceCallingOrSelfPermission(
13691                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13692        // writer
13693        synchronized (mPackages) {
13694            clearPackagePreferredActivitiesLPw(null, userId);
13695            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13696            applyFactoryDefaultBrowserLPw(userId);
13697
13698            scheduleWritePackageRestrictionsLocked(userId);
13699        }
13700    }
13701
13702    @Override
13703    public int getPreferredActivities(List<IntentFilter> outFilters,
13704            List<ComponentName> outActivities, String packageName) {
13705
13706        int num = 0;
13707        final int userId = UserHandle.getCallingUserId();
13708        // reader
13709        synchronized (mPackages) {
13710            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13711            if (pir != null) {
13712                final Iterator<PreferredActivity> it = pir.filterIterator();
13713                while (it.hasNext()) {
13714                    final PreferredActivity pa = it.next();
13715                    if (packageName == null
13716                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13717                                    && pa.mPref.mAlways)) {
13718                        if (outFilters != null) {
13719                            outFilters.add(new IntentFilter(pa));
13720                        }
13721                        if (outActivities != null) {
13722                            outActivities.add(pa.mPref.mComponent);
13723                        }
13724                    }
13725                }
13726            }
13727        }
13728
13729        return num;
13730    }
13731
13732    @Override
13733    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13734            int userId) {
13735        int callingUid = Binder.getCallingUid();
13736        if (callingUid != Process.SYSTEM_UID) {
13737            throw new SecurityException(
13738                    "addPersistentPreferredActivity can only be run by the system");
13739        }
13740        if (filter.countActions() == 0) {
13741            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13742            return;
13743        }
13744        synchronized (mPackages) {
13745            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13746                    " :");
13747            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13748            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13749                    new PersistentPreferredActivity(filter, activity));
13750            scheduleWritePackageRestrictionsLocked(userId);
13751        }
13752    }
13753
13754    @Override
13755    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13756        int callingUid = Binder.getCallingUid();
13757        if (callingUid != Process.SYSTEM_UID) {
13758            throw new SecurityException(
13759                    "clearPackagePersistentPreferredActivities can only be run by the system");
13760        }
13761        ArrayList<PersistentPreferredActivity> removed = null;
13762        boolean changed = false;
13763        synchronized (mPackages) {
13764            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13765                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13766                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13767                        .valueAt(i);
13768                if (userId != thisUserId) {
13769                    continue;
13770                }
13771                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13772                while (it.hasNext()) {
13773                    PersistentPreferredActivity ppa = it.next();
13774                    // Mark entry for removal only if it matches the package name.
13775                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13776                        if (removed == null) {
13777                            removed = new ArrayList<PersistentPreferredActivity>();
13778                        }
13779                        removed.add(ppa);
13780                    }
13781                }
13782                if (removed != null) {
13783                    for (int j=0; j<removed.size(); j++) {
13784                        PersistentPreferredActivity ppa = removed.get(j);
13785                        ppir.removeFilter(ppa);
13786                    }
13787                    changed = true;
13788                }
13789            }
13790
13791            if (changed) {
13792                scheduleWritePackageRestrictionsLocked(userId);
13793            }
13794        }
13795    }
13796
13797    /**
13798     * Common machinery for picking apart a restored XML blob and passing
13799     * it to a caller-supplied functor to be applied to the running system.
13800     */
13801    private void restoreFromXml(XmlPullParser parser, int userId,
13802            String expectedStartTag, BlobXmlRestorer functor)
13803            throws IOException, XmlPullParserException {
13804        int type;
13805        while ((type = parser.next()) != XmlPullParser.START_TAG
13806                && type != XmlPullParser.END_DOCUMENT) {
13807        }
13808        if (type != XmlPullParser.START_TAG) {
13809            // oops didn't find a start tag?!
13810            if (DEBUG_BACKUP) {
13811                Slog.e(TAG, "Didn't find start tag during restore");
13812            }
13813            return;
13814        }
13815
13816        // this is supposed to be TAG_PREFERRED_BACKUP
13817        if (!expectedStartTag.equals(parser.getName())) {
13818            if (DEBUG_BACKUP) {
13819                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13820            }
13821            return;
13822        }
13823
13824        // skip interfering stuff, then we're aligned with the backing implementation
13825        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13826        functor.apply(parser, userId);
13827    }
13828
13829    private interface BlobXmlRestorer {
13830        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13831    }
13832
13833    /**
13834     * Non-Binder method, support for the backup/restore mechanism: write the
13835     * full set of preferred activities in its canonical XML format.  Returns the
13836     * XML output as a byte array, or null if there is none.
13837     */
13838    @Override
13839    public byte[] getPreferredActivityBackup(int userId) {
13840        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13841            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13842        }
13843
13844        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13845        try {
13846            final XmlSerializer serializer = new FastXmlSerializer();
13847            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13848            serializer.startDocument(null, true);
13849            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13850
13851            synchronized (mPackages) {
13852                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13853            }
13854
13855            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13856            serializer.endDocument();
13857            serializer.flush();
13858        } catch (Exception e) {
13859            if (DEBUG_BACKUP) {
13860                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13861            }
13862            return null;
13863        }
13864
13865        return dataStream.toByteArray();
13866    }
13867
13868    @Override
13869    public void restorePreferredActivities(byte[] backup, int userId) {
13870        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13871            throw new SecurityException("Only the system may call restorePreferredActivities()");
13872        }
13873
13874        try {
13875            final XmlPullParser parser = Xml.newPullParser();
13876            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13877            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13878                    new BlobXmlRestorer() {
13879                        @Override
13880                        public void apply(XmlPullParser parser, int userId)
13881                                throws XmlPullParserException, IOException {
13882                            synchronized (mPackages) {
13883                                mSettings.readPreferredActivitiesLPw(parser, userId);
13884                            }
13885                        }
13886                    } );
13887        } catch (Exception e) {
13888            if (DEBUG_BACKUP) {
13889                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13890            }
13891        }
13892    }
13893
13894    /**
13895     * Non-Binder method, support for the backup/restore mechanism: write the
13896     * default browser (etc) settings in its canonical XML format.  Returns the default
13897     * browser XML representation as a byte array, or null if there is none.
13898     */
13899    @Override
13900    public byte[] getDefaultAppsBackup(int userId) {
13901        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13902            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13903        }
13904
13905        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13906        try {
13907            final XmlSerializer serializer = new FastXmlSerializer();
13908            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13909            serializer.startDocument(null, true);
13910            serializer.startTag(null, TAG_DEFAULT_APPS);
13911
13912            synchronized (mPackages) {
13913                mSettings.writeDefaultAppsLPr(serializer, userId);
13914            }
13915
13916            serializer.endTag(null, TAG_DEFAULT_APPS);
13917            serializer.endDocument();
13918            serializer.flush();
13919        } catch (Exception e) {
13920            if (DEBUG_BACKUP) {
13921                Slog.e(TAG, "Unable to write default apps for backup", e);
13922            }
13923            return null;
13924        }
13925
13926        return dataStream.toByteArray();
13927    }
13928
13929    @Override
13930    public void restoreDefaultApps(byte[] backup, int userId) {
13931        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13932            throw new SecurityException("Only the system may call restoreDefaultApps()");
13933        }
13934
13935        try {
13936            final XmlPullParser parser = Xml.newPullParser();
13937            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13938            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13939                    new BlobXmlRestorer() {
13940                        @Override
13941                        public void apply(XmlPullParser parser, int userId)
13942                                throws XmlPullParserException, IOException {
13943                            synchronized (mPackages) {
13944                                mSettings.readDefaultAppsLPw(parser, userId);
13945                            }
13946                        }
13947                    } );
13948        } catch (Exception e) {
13949            if (DEBUG_BACKUP) {
13950                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13951            }
13952        }
13953    }
13954
13955    @Override
13956    public byte[] getIntentFilterVerificationBackup(int userId) {
13957        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13958            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13959        }
13960
13961        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13962        try {
13963            final XmlSerializer serializer = new FastXmlSerializer();
13964            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13965            serializer.startDocument(null, true);
13966            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13967
13968            synchronized (mPackages) {
13969                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13970            }
13971
13972            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13973            serializer.endDocument();
13974            serializer.flush();
13975        } catch (Exception e) {
13976            if (DEBUG_BACKUP) {
13977                Slog.e(TAG, "Unable to write default apps for backup", e);
13978            }
13979            return null;
13980        }
13981
13982        return dataStream.toByteArray();
13983    }
13984
13985    @Override
13986    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13987        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13988            throw new SecurityException("Only the system may call restorePreferredActivities()");
13989        }
13990
13991        try {
13992            final XmlPullParser parser = Xml.newPullParser();
13993            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13994            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13995                    new BlobXmlRestorer() {
13996                        @Override
13997                        public void apply(XmlPullParser parser, int userId)
13998                                throws XmlPullParserException, IOException {
13999                            synchronized (mPackages) {
14000                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14001                                mSettings.writeLPr();
14002                            }
14003                        }
14004                    } );
14005        } catch (Exception e) {
14006            if (DEBUG_BACKUP) {
14007                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14008            }
14009        }
14010    }
14011
14012    @Override
14013    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14014            int sourceUserId, int targetUserId, int flags) {
14015        mContext.enforceCallingOrSelfPermission(
14016                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14017        int callingUid = Binder.getCallingUid();
14018        enforceOwnerRights(ownerPackage, callingUid);
14019        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14020        if (intentFilter.countActions() == 0) {
14021            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14022            return;
14023        }
14024        synchronized (mPackages) {
14025            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14026                    ownerPackage, targetUserId, flags);
14027            CrossProfileIntentResolver resolver =
14028                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14029            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14030            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14031            if (existing != null) {
14032                int size = existing.size();
14033                for (int i = 0; i < size; i++) {
14034                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14035                        return;
14036                    }
14037                }
14038            }
14039            resolver.addFilter(newFilter);
14040            scheduleWritePackageRestrictionsLocked(sourceUserId);
14041        }
14042    }
14043
14044    @Override
14045    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14046        mContext.enforceCallingOrSelfPermission(
14047                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14048        int callingUid = Binder.getCallingUid();
14049        enforceOwnerRights(ownerPackage, callingUid);
14050        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14051        synchronized (mPackages) {
14052            CrossProfileIntentResolver resolver =
14053                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14054            ArraySet<CrossProfileIntentFilter> set =
14055                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14056            for (CrossProfileIntentFilter filter : set) {
14057                if (filter.getOwnerPackage().equals(ownerPackage)) {
14058                    resolver.removeFilter(filter);
14059                }
14060            }
14061            scheduleWritePackageRestrictionsLocked(sourceUserId);
14062        }
14063    }
14064
14065    // Enforcing that callingUid is owning pkg on userId
14066    private void enforceOwnerRights(String pkg, int callingUid) {
14067        // The system owns everything.
14068        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14069            return;
14070        }
14071        int callingUserId = UserHandle.getUserId(callingUid);
14072        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14073        if (pi == null) {
14074            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14075                    + callingUserId);
14076        }
14077        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14078            throw new SecurityException("Calling uid " + callingUid
14079                    + " does not own package " + pkg);
14080        }
14081    }
14082
14083    @Override
14084    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14085        Intent intent = new Intent(Intent.ACTION_MAIN);
14086        intent.addCategory(Intent.CATEGORY_HOME);
14087
14088        final int callingUserId = UserHandle.getCallingUserId();
14089        List<ResolveInfo> list = queryIntentActivities(intent, null,
14090                PackageManager.GET_META_DATA, callingUserId);
14091        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14092                true, false, false, callingUserId);
14093
14094        allHomeCandidates.clear();
14095        if (list != null) {
14096            for (ResolveInfo ri : list) {
14097                allHomeCandidates.add(ri);
14098            }
14099        }
14100        return (preferred == null || preferred.activityInfo == null)
14101                ? null
14102                : new ComponentName(preferred.activityInfo.packageName,
14103                        preferred.activityInfo.name);
14104    }
14105
14106    @Override
14107    public void setApplicationEnabledSetting(String appPackageName,
14108            int newState, int flags, int userId, String callingPackage) {
14109        if (!sUserManager.exists(userId)) return;
14110        if (callingPackage == null) {
14111            callingPackage = Integer.toString(Binder.getCallingUid());
14112        }
14113        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14114    }
14115
14116    @Override
14117    public void setComponentEnabledSetting(ComponentName componentName,
14118            int newState, int flags, int userId) {
14119        if (!sUserManager.exists(userId)) return;
14120        setEnabledSetting(componentName.getPackageName(),
14121                componentName.getClassName(), newState, flags, userId, null);
14122    }
14123
14124    private void setEnabledSetting(final String packageName, String className, int newState,
14125            final int flags, int userId, String callingPackage) {
14126        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14127              || newState == COMPONENT_ENABLED_STATE_ENABLED
14128              || newState == COMPONENT_ENABLED_STATE_DISABLED
14129              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14130              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14131            throw new IllegalArgumentException("Invalid new component state: "
14132                    + newState);
14133        }
14134        PackageSetting pkgSetting;
14135        final int uid = Binder.getCallingUid();
14136        final int permission = mContext.checkCallingOrSelfPermission(
14137                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14138        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14139        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14140        boolean sendNow = false;
14141        boolean isApp = (className == null);
14142        String componentName = isApp ? packageName : className;
14143        int packageUid = -1;
14144        ArrayList<String> components;
14145
14146        // writer
14147        synchronized (mPackages) {
14148            pkgSetting = mSettings.mPackages.get(packageName);
14149            if (pkgSetting == null) {
14150                if (className == null) {
14151                    throw new IllegalArgumentException(
14152                            "Unknown package: " + packageName);
14153                }
14154                throw new IllegalArgumentException(
14155                        "Unknown component: " + packageName
14156                        + "/" + className);
14157            }
14158            // Allow root and verify that userId is not being specified by a different user
14159            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14160                throw new SecurityException(
14161                        "Permission Denial: attempt to change component state from pid="
14162                        + Binder.getCallingPid()
14163                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14164            }
14165            if (className == null) {
14166                // We're dealing with an application/package level state change
14167                if (pkgSetting.getEnabled(userId) == newState) {
14168                    // Nothing to do
14169                    return;
14170                }
14171                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14172                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14173                    // Don't care about who enables an app.
14174                    callingPackage = null;
14175                }
14176                pkgSetting.setEnabled(newState, userId, callingPackage);
14177                // pkgSetting.pkg.mSetEnabled = newState;
14178            } else {
14179                // We're dealing with a component level state change
14180                // First, verify that this is a valid class name.
14181                PackageParser.Package pkg = pkgSetting.pkg;
14182                if (pkg == null || !pkg.hasComponentClassName(className)) {
14183                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14184                        throw new IllegalArgumentException("Component class " + className
14185                                + " does not exist in " + packageName);
14186                    } else {
14187                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14188                                + className + " does not exist in " + packageName);
14189                    }
14190                }
14191                switch (newState) {
14192                case COMPONENT_ENABLED_STATE_ENABLED:
14193                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14194                        return;
14195                    }
14196                    break;
14197                case COMPONENT_ENABLED_STATE_DISABLED:
14198                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14199                        return;
14200                    }
14201                    break;
14202                case COMPONENT_ENABLED_STATE_DEFAULT:
14203                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14204                        return;
14205                    }
14206                    break;
14207                default:
14208                    Slog.e(TAG, "Invalid new component state: " + newState);
14209                    return;
14210                }
14211            }
14212            scheduleWritePackageRestrictionsLocked(userId);
14213            components = mPendingBroadcasts.get(userId, packageName);
14214            final boolean newPackage = components == null;
14215            if (newPackage) {
14216                components = new ArrayList<String>();
14217            }
14218            if (!components.contains(componentName)) {
14219                components.add(componentName);
14220            }
14221            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14222                sendNow = true;
14223                // Purge entry from pending broadcast list if another one exists already
14224                // since we are sending one right away.
14225                mPendingBroadcasts.remove(userId, packageName);
14226            } else {
14227                if (newPackage) {
14228                    mPendingBroadcasts.put(userId, packageName, components);
14229                }
14230                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14231                    // Schedule a message
14232                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14233                }
14234            }
14235        }
14236
14237        long callingId = Binder.clearCallingIdentity();
14238        try {
14239            if (sendNow) {
14240                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14241                sendPackageChangedBroadcast(packageName,
14242                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14243            }
14244        } finally {
14245            Binder.restoreCallingIdentity(callingId);
14246        }
14247    }
14248
14249    private void sendPackageChangedBroadcast(String packageName,
14250            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14251        if (DEBUG_INSTALL)
14252            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14253                    + componentNames);
14254        Bundle extras = new Bundle(4);
14255        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14256        String nameList[] = new String[componentNames.size()];
14257        componentNames.toArray(nameList);
14258        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14259        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14260        extras.putInt(Intent.EXTRA_UID, packageUid);
14261        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14262                new int[] {UserHandle.getUserId(packageUid)});
14263    }
14264
14265    @Override
14266    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14267        if (!sUserManager.exists(userId)) return;
14268        final int uid = Binder.getCallingUid();
14269        final int permission = mContext.checkCallingOrSelfPermission(
14270                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14271        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14272        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14273        // writer
14274        synchronized (mPackages) {
14275            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14276                    allowedByPermission, uid, userId)) {
14277                scheduleWritePackageRestrictionsLocked(userId);
14278            }
14279        }
14280    }
14281
14282    @Override
14283    public String getInstallerPackageName(String packageName) {
14284        // reader
14285        synchronized (mPackages) {
14286            return mSettings.getInstallerPackageNameLPr(packageName);
14287        }
14288    }
14289
14290    @Override
14291    public int getApplicationEnabledSetting(String packageName, int userId) {
14292        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14293        int uid = Binder.getCallingUid();
14294        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14295        // reader
14296        synchronized (mPackages) {
14297            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14298        }
14299    }
14300
14301    @Override
14302    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14303        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14304        int uid = Binder.getCallingUid();
14305        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14306        // reader
14307        synchronized (mPackages) {
14308            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14309        }
14310    }
14311
14312    @Override
14313    public void enterSafeMode() {
14314        enforceSystemOrRoot("Only the system can request entering safe mode");
14315
14316        if (!mSystemReady) {
14317            mSafeMode = true;
14318        }
14319    }
14320
14321    @Override
14322    public void systemReady() {
14323        mSystemReady = true;
14324
14325        // Read the compatibilty setting when the system is ready.
14326        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14327                mContext.getContentResolver(),
14328                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14329        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14330        if (DEBUG_SETTINGS) {
14331            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14332        }
14333
14334        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14335
14336        synchronized (mPackages) {
14337            // Verify that all of the preferred activity components actually
14338            // exist.  It is possible for applications to be updated and at
14339            // that point remove a previously declared activity component that
14340            // had been set as a preferred activity.  We try to clean this up
14341            // the next time we encounter that preferred activity, but it is
14342            // possible for the user flow to never be able to return to that
14343            // situation so here we do a sanity check to make sure we haven't
14344            // left any junk around.
14345            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14346            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14347                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14348                removed.clear();
14349                for (PreferredActivity pa : pir.filterSet()) {
14350                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14351                        removed.add(pa);
14352                    }
14353                }
14354                if (removed.size() > 0) {
14355                    for (int r=0; r<removed.size(); r++) {
14356                        PreferredActivity pa = removed.get(r);
14357                        Slog.w(TAG, "Removing dangling preferred activity: "
14358                                + pa.mPref.mComponent);
14359                        pir.removeFilter(pa);
14360                    }
14361                    mSettings.writePackageRestrictionsLPr(
14362                            mSettings.mPreferredActivities.keyAt(i));
14363                }
14364            }
14365
14366            for (int userId : UserManagerService.getInstance().getUserIds()) {
14367                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14368                    grantPermissionsUserIds = ArrayUtils.appendInt(
14369                            grantPermissionsUserIds, userId);
14370                }
14371            }
14372        }
14373        sUserManager.systemReady();
14374
14375        // If we upgraded grant all default permissions before kicking off.
14376        for (int userId : grantPermissionsUserIds) {
14377            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14378        }
14379
14380        // Kick off any messages waiting for system ready
14381        if (mPostSystemReadyMessages != null) {
14382            for (Message msg : mPostSystemReadyMessages) {
14383                msg.sendToTarget();
14384            }
14385            mPostSystemReadyMessages = null;
14386        }
14387
14388        // Watch for external volumes that come and go over time
14389        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14390        storage.registerListener(mStorageListener);
14391
14392        mInstallerService.systemReady();
14393        mPackageDexOptimizer.systemReady();
14394    }
14395
14396    @Override
14397    public boolean isSafeMode() {
14398        return mSafeMode;
14399    }
14400
14401    @Override
14402    public boolean hasSystemUidErrors() {
14403        return mHasSystemUidErrors;
14404    }
14405
14406    static String arrayToString(int[] array) {
14407        StringBuffer buf = new StringBuffer(128);
14408        buf.append('[');
14409        if (array != null) {
14410            for (int i=0; i<array.length; i++) {
14411                if (i > 0) buf.append(", ");
14412                buf.append(array[i]);
14413            }
14414        }
14415        buf.append(']');
14416        return buf.toString();
14417    }
14418
14419    static class DumpState {
14420        public static final int DUMP_LIBS = 1 << 0;
14421        public static final int DUMP_FEATURES = 1 << 1;
14422        public static final int DUMP_RESOLVERS = 1 << 2;
14423        public static final int DUMP_PERMISSIONS = 1 << 3;
14424        public static final int DUMP_PACKAGES = 1 << 4;
14425        public static final int DUMP_SHARED_USERS = 1 << 5;
14426        public static final int DUMP_MESSAGES = 1 << 6;
14427        public static final int DUMP_PROVIDERS = 1 << 7;
14428        public static final int DUMP_VERIFIERS = 1 << 8;
14429        public static final int DUMP_PREFERRED = 1 << 9;
14430        public static final int DUMP_PREFERRED_XML = 1 << 10;
14431        public static final int DUMP_KEYSETS = 1 << 11;
14432        public static final int DUMP_VERSION = 1 << 12;
14433        public static final int DUMP_INSTALLS = 1 << 13;
14434        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14435        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14436
14437        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14438
14439        private int mTypes;
14440
14441        private int mOptions;
14442
14443        private boolean mTitlePrinted;
14444
14445        private SharedUserSetting mSharedUser;
14446
14447        public boolean isDumping(int type) {
14448            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14449                return true;
14450            }
14451
14452            return (mTypes & type) != 0;
14453        }
14454
14455        public void setDump(int type) {
14456            mTypes |= type;
14457        }
14458
14459        public boolean isOptionEnabled(int option) {
14460            return (mOptions & option) != 0;
14461        }
14462
14463        public void setOptionEnabled(int option) {
14464            mOptions |= option;
14465        }
14466
14467        public boolean onTitlePrinted() {
14468            final boolean printed = mTitlePrinted;
14469            mTitlePrinted = true;
14470            return printed;
14471        }
14472
14473        public boolean getTitlePrinted() {
14474            return mTitlePrinted;
14475        }
14476
14477        public void setTitlePrinted(boolean enabled) {
14478            mTitlePrinted = enabled;
14479        }
14480
14481        public SharedUserSetting getSharedUser() {
14482            return mSharedUser;
14483        }
14484
14485        public void setSharedUser(SharedUserSetting user) {
14486            mSharedUser = user;
14487        }
14488    }
14489
14490    @Override
14491    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14492        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14493                != PackageManager.PERMISSION_GRANTED) {
14494            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14495                    + Binder.getCallingPid()
14496                    + ", uid=" + Binder.getCallingUid()
14497                    + " without permission "
14498                    + android.Manifest.permission.DUMP);
14499            return;
14500        }
14501
14502        DumpState dumpState = new DumpState();
14503        boolean fullPreferred = false;
14504        boolean checkin = false;
14505
14506        String packageName = null;
14507        ArraySet<String> permissionNames = null;
14508
14509        int opti = 0;
14510        while (opti < args.length) {
14511            String opt = args[opti];
14512            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14513                break;
14514            }
14515            opti++;
14516
14517            if ("-a".equals(opt)) {
14518                // Right now we only know how to print all.
14519            } else if ("-h".equals(opt)) {
14520                pw.println("Package manager dump options:");
14521                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14522                pw.println("    --checkin: dump for a checkin");
14523                pw.println("    -f: print details of intent filters");
14524                pw.println("    -h: print this help");
14525                pw.println("  cmd may be one of:");
14526                pw.println("    l[ibraries]: list known shared libraries");
14527                pw.println("    f[ibraries]: list device features");
14528                pw.println("    k[eysets]: print known keysets");
14529                pw.println("    r[esolvers]: dump intent resolvers");
14530                pw.println("    perm[issions]: dump permissions");
14531                pw.println("    permission [name ...]: dump declaration and use of given permission");
14532                pw.println("    pref[erred]: print preferred package settings");
14533                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14534                pw.println("    prov[iders]: dump content providers");
14535                pw.println("    p[ackages]: dump installed packages");
14536                pw.println("    s[hared-users]: dump shared user IDs");
14537                pw.println("    m[essages]: print collected runtime messages");
14538                pw.println("    v[erifiers]: print package verifier info");
14539                pw.println("    version: print database version info");
14540                pw.println("    write: write current settings now");
14541                pw.println("    <package.name>: info about given package");
14542                pw.println("    installs: details about install sessions");
14543                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14544                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14545                return;
14546            } else if ("--checkin".equals(opt)) {
14547                checkin = true;
14548            } else if ("-f".equals(opt)) {
14549                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14550            } else {
14551                pw.println("Unknown argument: " + opt + "; use -h for help");
14552            }
14553        }
14554
14555        // Is the caller requesting to dump a particular piece of data?
14556        if (opti < args.length) {
14557            String cmd = args[opti];
14558            opti++;
14559            // Is this a package name?
14560            if ("android".equals(cmd) || cmd.contains(".")) {
14561                packageName = cmd;
14562                // When dumping a single package, we always dump all of its
14563                // filter information since the amount of data will be reasonable.
14564                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14565            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14566                dumpState.setDump(DumpState.DUMP_LIBS);
14567            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14568                dumpState.setDump(DumpState.DUMP_FEATURES);
14569            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14570                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14571            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14572                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14573            } else if ("permission".equals(cmd)) {
14574                if (opti >= args.length) {
14575                    pw.println("Error: permission requires permission name");
14576                    return;
14577                }
14578                permissionNames = new ArraySet<>();
14579                while (opti < args.length) {
14580                    permissionNames.add(args[opti]);
14581                    opti++;
14582                }
14583                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14584                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14585            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14586                dumpState.setDump(DumpState.DUMP_PREFERRED);
14587            } else if ("preferred-xml".equals(cmd)) {
14588                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14589                if (opti < args.length && "--full".equals(args[opti])) {
14590                    fullPreferred = true;
14591                    opti++;
14592                }
14593            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14594                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14595            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14596                dumpState.setDump(DumpState.DUMP_PACKAGES);
14597            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14598                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14599            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14600                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14601            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14602                dumpState.setDump(DumpState.DUMP_MESSAGES);
14603            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14604                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14605            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14606                    || "intent-filter-verifiers".equals(cmd)) {
14607                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14608            } else if ("version".equals(cmd)) {
14609                dumpState.setDump(DumpState.DUMP_VERSION);
14610            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14611                dumpState.setDump(DumpState.DUMP_KEYSETS);
14612            } else if ("installs".equals(cmd)) {
14613                dumpState.setDump(DumpState.DUMP_INSTALLS);
14614            } else if ("write".equals(cmd)) {
14615                synchronized (mPackages) {
14616                    mSettings.writeLPr();
14617                    pw.println("Settings written.");
14618                    return;
14619                }
14620            }
14621        }
14622
14623        if (checkin) {
14624            pw.println("vers,1");
14625        }
14626
14627        // reader
14628        synchronized (mPackages) {
14629            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14630                if (!checkin) {
14631                    if (dumpState.onTitlePrinted())
14632                        pw.println();
14633                    pw.println("Database versions:");
14634                    pw.print("  SDK Version:");
14635                    pw.print(" internal=");
14636                    pw.print(mSettings.mInternalSdkPlatform);
14637                    pw.print(" external=");
14638                    pw.println(mSettings.mExternalSdkPlatform);
14639                    pw.print("  DB Version:");
14640                    pw.print(" internal=");
14641                    pw.print(mSettings.mInternalDatabaseVersion);
14642                    pw.print(" external=");
14643                    pw.println(mSettings.mExternalDatabaseVersion);
14644                }
14645            }
14646
14647            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14648                if (!checkin) {
14649                    if (dumpState.onTitlePrinted())
14650                        pw.println();
14651                    pw.println("Verifiers:");
14652                    pw.print("  Required: ");
14653                    pw.print(mRequiredVerifierPackage);
14654                    pw.print(" (uid=");
14655                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14656                    pw.println(")");
14657                } else if (mRequiredVerifierPackage != null) {
14658                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14659                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14660                }
14661            }
14662
14663            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14664                    packageName == null) {
14665                if (mIntentFilterVerifierComponent != null) {
14666                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14667                    if (!checkin) {
14668                        if (dumpState.onTitlePrinted())
14669                            pw.println();
14670                        pw.println("Intent Filter Verifier:");
14671                        pw.print("  Using: ");
14672                        pw.print(verifierPackageName);
14673                        pw.print(" (uid=");
14674                        pw.print(getPackageUid(verifierPackageName, 0));
14675                        pw.println(")");
14676                    } else if (verifierPackageName != null) {
14677                        pw.print("ifv,"); pw.print(verifierPackageName);
14678                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14679                    }
14680                } else {
14681                    pw.println();
14682                    pw.println("No Intent Filter Verifier available!");
14683                }
14684            }
14685
14686            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14687                boolean printedHeader = false;
14688                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14689                while (it.hasNext()) {
14690                    String name = it.next();
14691                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14692                    if (!checkin) {
14693                        if (!printedHeader) {
14694                            if (dumpState.onTitlePrinted())
14695                                pw.println();
14696                            pw.println("Libraries:");
14697                            printedHeader = true;
14698                        }
14699                        pw.print("  ");
14700                    } else {
14701                        pw.print("lib,");
14702                    }
14703                    pw.print(name);
14704                    if (!checkin) {
14705                        pw.print(" -> ");
14706                    }
14707                    if (ent.path != null) {
14708                        if (!checkin) {
14709                            pw.print("(jar) ");
14710                            pw.print(ent.path);
14711                        } else {
14712                            pw.print(",jar,");
14713                            pw.print(ent.path);
14714                        }
14715                    } else {
14716                        if (!checkin) {
14717                            pw.print("(apk) ");
14718                            pw.print(ent.apk);
14719                        } else {
14720                            pw.print(",apk,");
14721                            pw.print(ent.apk);
14722                        }
14723                    }
14724                    pw.println();
14725                }
14726            }
14727
14728            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14729                if (dumpState.onTitlePrinted())
14730                    pw.println();
14731                if (!checkin) {
14732                    pw.println("Features:");
14733                }
14734                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14735                while (it.hasNext()) {
14736                    String name = it.next();
14737                    if (!checkin) {
14738                        pw.print("  ");
14739                    } else {
14740                        pw.print("feat,");
14741                    }
14742                    pw.println(name);
14743                }
14744            }
14745
14746            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14747                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14748                        : "Activity Resolver Table:", "  ", packageName,
14749                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14750                    dumpState.setTitlePrinted(true);
14751                }
14752                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14753                        : "Receiver Resolver Table:", "  ", packageName,
14754                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14755                    dumpState.setTitlePrinted(true);
14756                }
14757                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14758                        : "Service Resolver Table:", "  ", packageName,
14759                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14760                    dumpState.setTitlePrinted(true);
14761                }
14762                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14763                        : "Provider Resolver Table:", "  ", packageName,
14764                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14765                    dumpState.setTitlePrinted(true);
14766                }
14767            }
14768
14769            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14770                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14771                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14772                    int user = mSettings.mPreferredActivities.keyAt(i);
14773                    if (pir.dump(pw,
14774                            dumpState.getTitlePrinted()
14775                                ? "\nPreferred Activities User " + user + ":"
14776                                : "Preferred Activities User " + user + ":", "  ",
14777                            packageName, true, false)) {
14778                        dumpState.setTitlePrinted(true);
14779                    }
14780                }
14781            }
14782
14783            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14784                pw.flush();
14785                FileOutputStream fout = new FileOutputStream(fd);
14786                BufferedOutputStream str = new BufferedOutputStream(fout);
14787                XmlSerializer serializer = new FastXmlSerializer();
14788                try {
14789                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14790                    serializer.startDocument(null, true);
14791                    serializer.setFeature(
14792                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14793                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14794                    serializer.endDocument();
14795                    serializer.flush();
14796                } catch (IllegalArgumentException e) {
14797                    pw.println("Failed writing: " + e);
14798                } catch (IllegalStateException e) {
14799                    pw.println("Failed writing: " + e);
14800                } catch (IOException e) {
14801                    pw.println("Failed writing: " + e);
14802                }
14803            }
14804
14805            if (!checkin
14806                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14807                    && packageName == null) {
14808                pw.println();
14809                int count = mSettings.mPackages.size();
14810                if (count == 0) {
14811                    pw.println("No domain preferred apps!");
14812                    pw.println();
14813                } else {
14814                    final String prefix = "  ";
14815                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14816                    if (allPackageSettings.size() == 0) {
14817                        pw.println("No domain preferred apps!");
14818                        pw.println();
14819                    } else {
14820                        pw.println("Domain preferred apps status:");
14821                        pw.println();
14822                        count = 0;
14823                        for (PackageSetting ps : allPackageSettings) {
14824                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14825                            if (ivi == null || ivi.getPackageName() == null) continue;
14826                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14827                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14828                            pw.println(prefix + "Status: " + ivi.getStatusString());
14829                            pw.println();
14830                            count++;
14831                        }
14832                        if (count == 0) {
14833                            pw.println(prefix + "No domain preferred app status!");
14834                            pw.println();
14835                        }
14836                        for (int userId : sUserManager.getUserIds()) {
14837                            pw.println("Domain preferred apps for User " + userId + ":");
14838                            pw.println();
14839                            count = 0;
14840                            for (PackageSetting ps : allPackageSettings) {
14841                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14842                                if (ivi == null || ivi.getPackageName() == null) {
14843                                    continue;
14844                                }
14845                                final int status = ps.getDomainVerificationStatusForUser(userId);
14846                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14847                                    continue;
14848                                }
14849                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14850                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14851                                String statusStr = IntentFilterVerificationInfo.
14852                                        getStatusStringFromValue(status);
14853                                pw.println(prefix + "Status: " + statusStr);
14854                                pw.println();
14855                                count++;
14856                            }
14857                            if (count == 0) {
14858                                pw.println(prefix + "No domain preferred apps!");
14859                                pw.println();
14860                            }
14861                        }
14862                    }
14863                }
14864            }
14865
14866            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14867                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14868                if (packageName == null && permissionNames == null) {
14869                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14870                        if (iperm == 0) {
14871                            if (dumpState.onTitlePrinted())
14872                                pw.println();
14873                            pw.println("AppOp Permissions:");
14874                        }
14875                        pw.print("  AppOp Permission ");
14876                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14877                        pw.println(":");
14878                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14879                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14880                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14881                        }
14882                    }
14883                }
14884            }
14885
14886            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14887                boolean printedSomething = false;
14888                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14889                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14890                        continue;
14891                    }
14892                    if (!printedSomething) {
14893                        if (dumpState.onTitlePrinted())
14894                            pw.println();
14895                        pw.println("Registered ContentProviders:");
14896                        printedSomething = true;
14897                    }
14898                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14899                    pw.print("    "); pw.println(p.toString());
14900                }
14901                printedSomething = false;
14902                for (Map.Entry<String, PackageParser.Provider> entry :
14903                        mProvidersByAuthority.entrySet()) {
14904                    PackageParser.Provider p = entry.getValue();
14905                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14906                        continue;
14907                    }
14908                    if (!printedSomething) {
14909                        if (dumpState.onTitlePrinted())
14910                            pw.println();
14911                        pw.println("ContentProvider Authorities:");
14912                        printedSomething = true;
14913                    }
14914                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14915                    pw.print("    "); pw.println(p.toString());
14916                    if (p.info != null && p.info.applicationInfo != null) {
14917                        final String appInfo = p.info.applicationInfo.toString();
14918                        pw.print("      applicationInfo="); pw.println(appInfo);
14919                    }
14920                }
14921            }
14922
14923            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14924                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14925            }
14926
14927            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14928                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14929            }
14930
14931            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14932                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14933            }
14934
14935            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14936                // XXX should handle packageName != null by dumping only install data that
14937                // the given package is involved with.
14938                if (dumpState.onTitlePrinted()) pw.println();
14939                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14940            }
14941
14942            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14943                if (dumpState.onTitlePrinted()) pw.println();
14944                mSettings.dumpReadMessagesLPr(pw, dumpState);
14945
14946                pw.println();
14947                pw.println("Package warning messages:");
14948                BufferedReader in = null;
14949                String line = null;
14950                try {
14951                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14952                    while ((line = in.readLine()) != null) {
14953                        if (line.contains("ignored: updated version")) continue;
14954                        pw.println(line);
14955                    }
14956                } catch (IOException ignored) {
14957                } finally {
14958                    IoUtils.closeQuietly(in);
14959                }
14960            }
14961
14962            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14963                BufferedReader in = null;
14964                String line = null;
14965                try {
14966                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14967                    while ((line = in.readLine()) != null) {
14968                        if (line.contains("ignored: updated version")) continue;
14969                        pw.print("msg,");
14970                        pw.println(line);
14971                    }
14972                } catch (IOException ignored) {
14973                } finally {
14974                    IoUtils.closeQuietly(in);
14975                }
14976            }
14977        }
14978    }
14979
14980    // ------- apps on sdcard specific code -------
14981    static final boolean DEBUG_SD_INSTALL = false;
14982
14983    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14984
14985    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14986
14987    private boolean mMediaMounted = false;
14988
14989    static String getEncryptKey() {
14990        try {
14991            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14992                    SD_ENCRYPTION_KEYSTORE_NAME);
14993            if (sdEncKey == null) {
14994                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14995                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14996                if (sdEncKey == null) {
14997                    Slog.e(TAG, "Failed to create encryption keys");
14998                    return null;
14999                }
15000            }
15001            return sdEncKey;
15002        } catch (NoSuchAlgorithmException nsae) {
15003            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15004            return null;
15005        } catch (IOException ioe) {
15006            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15007            return null;
15008        }
15009    }
15010
15011    /*
15012     * Update media status on PackageManager.
15013     */
15014    @Override
15015    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15016        int callingUid = Binder.getCallingUid();
15017        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15018            throw new SecurityException("Media status can only be updated by the system");
15019        }
15020        // reader; this apparently protects mMediaMounted, but should probably
15021        // be a different lock in that case.
15022        synchronized (mPackages) {
15023            Log.i(TAG, "Updating external media status from "
15024                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15025                    + (mediaStatus ? "mounted" : "unmounted"));
15026            if (DEBUG_SD_INSTALL)
15027                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15028                        + ", mMediaMounted=" + mMediaMounted);
15029            if (mediaStatus == mMediaMounted) {
15030                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15031                        : 0, -1);
15032                mHandler.sendMessage(msg);
15033                return;
15034            }
15035            mMediaMounted = mediaStatus;
15036        }
15037        // Queue up an async operation since the package installation may take a
15038        // little while.
15039        mHandler.post(new Runnable() {
15040            public void run() {
15041                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15042            }
15043        });
15044    }
15045
15046    /**
15047     * Called by MountService when the initial ASECs to scan are available.
15048     * Should block until all the ASEC containers are finished being scanned.
15049     */
15050    public void scanAvailableAsecs() {
15051        updateExternalMediaStatusInner(true, false, false);
15052        if (mShouldRestoreconData) {
15053            SELinuxMMAC.setRestoreconDone();
15054            mShouldRestoreconData = false;
15055        }
15056    }
15057
15058    /*
15059     * Collect information of applications on external media, map them against
15060     * existing containers and update information based on current mount status.
15061     * Please note that we always have to report status if reportStatus has been
15062     * set to true especially when unloading packages.
15063     */
15064    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15065            boolean externalStorage) {
15066        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15067        int[] uidArr = EmptyArray.INT;
15068
15069        final String[] list = PackageHelper.getSecureContainerList();
15070        if (ArrayUtils.isEmpty(list)) {
15071            Log.i(TAG, "No secure containers found");
15072        } else {
15073            // Process list of secure containers and categorize them
15074            // as active or stale based on their package internal state.
15075
15076            // reader
15077            synchronized (mPackages) {
15078                for (String cid : list) {
15079                    // Leave stages untouched for now; installer service owns them
15080                    if (PackageInstallerService.isStageName(cid)) continue;
15081
15082                    if (DEBUG_SD_INSTALL)
15083                        Log.i(TAG, "Processing container " + cid);
15084                    String pkgName = getAsecPackageName(cid);
15085                    if (pkgName == null) {
15086                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15087                        continue;
15088                    }
15089                    if (DEBUG_SD_INSTALL)
15090                        Log.i(TAG, "Looking for pkg : " + pkgName);
15091
15092                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15093                    if (ps == null) {
15094                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15095                        continue;
15096                    }
15097
15098                    /*
15099                     * Skip packages that are not external if we're unmounting
15100                     * external storage.
15101                     */
15102                    if (externalStorage && !isMounted && !isExternal(ps)) {
15103                        continue;
15104                    }
15105
15106                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15107                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15108                    // The package status is changed only if the code path
15109                    // matches between settings and the container id.
15110                    if (ps.codePathString != null
15111                            && ps.codePathString.startsWith(args.getCodePath())) {
15112                        if (DEBUG_SD_INSTALL) {
15113                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15114                                    + " at code path: " + ps.codePathString);
15115                        }
15116
15117                        // We do have a valid package installed on sdcard
15118                        processCids.put(args, ps.codePathString);
15119                        final int uid = ps.appId;
15120                        if (uid != -1) {
15121                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15122                        }
15123                    } else {
15124                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15125                                + ps.codePathString);
15126                    }
15127                }
15128            }
15129
15130            Arrays.sort(uidArr);
15131        }
15132
15133        // Process packages with valid entries.
15134        if (isMounted) {
15135            if (DEBUG_SD_INSTALL)
15136                Log.i(TAG, "Loading packages");
15137            loadMediaPackages(processCids, uidArr);
15138            startCleaningPackages();
15139            mInstallerService.onSecureContainersAvailable();
15140        } else {
15141            if (DEBUG_SD_INSTALL)
15142                Log.i(TAG, "Unloading packages");
15143            unloadMediaPackages(processCids, uidArr, reportStatus);
15144        }
15145    }
15146
15147    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15148            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15149        final int size = infos.size();
15150        final String[] packageNames = new String[size];
15151        final int[] packageUids = new int[size];
15152        for (int i = 0; i < size; i++) {
15153            final ApplicationInfo info = infos.get(i);
15154            packageNames[i] = info.packageName;
15155            packageUids[i] = info.uid;
15156        }
15157        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15158                finishedReceiver);
15159    }
15160
15161    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15162            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15163        sendResourcesChangedBroadcast(mediaStatus, replacing,
15164                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15165    }
15166
15167    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15168            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15169        int size = pkgList.length;
15170        if (size > 0) {
15171            // Send broadcasts here
15172            Bundle extras = new Bundle();
15173            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15174            if (uidArr != null) {
15175                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15176            }
15177            if (replacing) {
15178                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15179            }
15180            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15181                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15182            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15183        }
15184    }
15185
15186   /*
15187     * Look at potentially valid container ids from processCids If package
15188     * information doesn't match the one on record or package scanning fails,
15189     * the cid is added to list of removeCids. We currently don't delete stale
15190     * containers.
15191     */
15192    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15193        ArrayList<String> pkgList = new ArrayList<String>();
15194        Set<AsecInstallArgs> keys = processCids.keySet();
15195
15196        for (AsecInstallArgs args : keys) {
15197            String codePath = processCids.get(args);
15198            if (DEBUG_SD_INSTALL)
15199                Log.i(TAG, "Loading container : " + args.cid);
15200            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15201            try {
15202                // Make sure there are no container errors first.
15203                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15204                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15205                            + " when installing from sdcard");
15206                    continue;
15207                }
15208                // Check code path here.
15209                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15210                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15211                            + " does not match one in settings " + codePath);
15212                    continue;
15213                }
15214                // Parse package
15215                int parseFlags = mDefParseFlags;
15216                if (args.isExternalAsec()) {
15217                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15218                }
15219                if (args.isFwdLocked()) {
15220                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15221                }
15222
15223                synchronized (mInstallLock) {
15224                    PackageParser.Package pkg = null;
15225                    try {
15226                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15227                    } catch (PackageManagerException e) {
15228                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15229                    }
15230                    // Scan the package
15231                    if (pkg != null) {
15232                        /*
15233                         * TODO why is the lock being held? doPostInstall is
15234                         * called in other places without the lock. This needs
15235                         * to be straightened out.
15236                         */
15237                        // writer
15238                        synchronized (mPackages) {
15239                            retCode = PackageManager.INSTALL_SUCCEEDED;
15240                            pkgList.add(pkg.packageName);
15241                            // Post process args
15242                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15243                                    pkg.applicationInfo.uid);
15244                        }
15245                    } else {
15246                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15247                    }
15248                }
15249
15250            } finally {
15251                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15252                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15253                }
15254            }
15255        }
15256        // writer
15257        synchronized (mPackages) {
15258            // If the platform SDK has changed since the last time we booted,
15259            // we need to re-grant app permission to catch any new ones that
15260            // appear. This is really a hack, and means that apps can in some
15261            // cases get permissions that the user didn't initially explicitly
15262            // allow... it would be nice to have some better way to handle
15263            // this situation.
15264            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15265            if (regrantPermissions)
15266                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15267                        + mSdkVersion + "; regranting permissions for external storage");
15268            mSettings.mExternalSdkPlatform = mSdkVersion;
15269
15270            // Make sure group IDs have been assigned, and any permission
15271            // changes in other apps are accounted for
15272            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15273                    | (regrantPermissions
15274                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15275                            : 0));
15276
15277            mSettings.updateExternalDatabaseVersion();
15278
15279            // can downgrade to reader
15280            // Persist settings
15281            mSettings.writeLPr();
15282        }
15283        // Send a broadcast to let everyone know we are done processing
15284        if (pkgList.size() > 0) {
15285            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15286        }
15287    }
15288
15289   /*
15290     * Utility method to unload a list of specified containers
15291     */
15292    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15293        // Just unmount all valid containers.
15294        for (AsecInstallArgs arg : cidArgs) {
15295            synchronized (mInstallLock) {
15296                arg.doPostDeleteLI(false);
15297           }
15298       }
15299   }
15300
15301    /*
15302     * Unload packages mounted on external media. This involves deleting package
15303     * data from internal structures, sending broadcasts about diabled packages,
15304     * gc'ing to free up references, unmounting all secure containers
15305     * corresponding to packages on external media, and posting a
15306     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15307     * that we always have to post this message if status has been requested no
15308     * matter what.
15309     */
15310    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15311            final boolean reportStatus) {
15312        if (DEBUG_SD_INSTALL)
15313            Log.i(TAG, "unloading media packages");
15314        ArrayList<String> pkgList = new ArrayList<String>();
15315        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15316        final Set<AsecInstallArgs> keys = processCids.keySet();
15317        for (AsecInstallArgs args : keys) {
15318            String pkgName = args.getPackageName();
15319            if (DEBUG_SD_INSTALL)
15320                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15321            // Delete package internally
15322            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15323            synchronized (mInstallLock) {
15324                boolean res = deletePackageLI(pkgName, null, false, null, null,
15325                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15326                if (res) {
15327                    pkgList.add(pkgName);
15328                } else {
15329                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15330                    failedList.add(args);
15331                }
15332            }
15333        }
15334
15335        // reader
15336        synchronized (mPackages) {
15337            // We didn't update the settings after removing each package;
15338            // write them now for all packages.
15339            mSettings.writeLPr();
15340        }
15341
15342        // We have to absolutely send UPDATED_MEDIA_STATUS only
15343        // after confirming that all the receivers processed the ordered
15344        // broadcast when packages get disabled, force a gc to clean things up.
15345        // and unload all the containers.
15346        if (pkgList.size() > 0) {
15347            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15348                    new IIntentReceiver.Stub() {
15349                public void performReceive(Intent intent, int resultCode, String data,
15350                        Bundle extras, boolean ordered, boolean sticky,
15351                        int sendingUser) throws RemoteException {
15352                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15353                            reportStatus ? 1 : 0, 1, keys);
15354                    mHandler.sendMessage(msg);
15355                }
15356            });
15357        } else {
15358            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15359                    keys);
15360            mHandler.sendMessage(msg);
15361        }
15362    }
15363
15364    private void loadPrivatePackages(VolumeInfo vol) {
15365        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15366        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15367        synchronized (mInstallLock) {
15368        synchronized (mPackages) {
15369            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15370            for (PackageSetting ps : packages) {
15371                final PackageParser.Package pkg;
15372                try {
15373                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15374                    loaded.add(pkg.applicationInfo);
15375                } catch (PackageManagerException e) {
15376                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15377                }
15378            }
15379
15380            // TODO: regrant any permissions that changed based since original install
15381
15382            mSettings.writeLPr();
15383        }
15384        }
15385
15386        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15387        sendResourcesChangedBroadcast(true, false, loaded, null);
15388    }
15389
15390    private void unloadPrivatePackages(VolumeInfo vol) {
15391        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15392        synchronized (mInstallLock) {
15393        synchronized (mPackages) {
15394            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15395            for (PackageSetting ps : packages) {
15396                if (ps.pkg == null) continue;
15397
15398                final ApplicationInfo info = ps.pkg.applicationInfo;
15399                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15400                if (deletePackageLI(ps.name, null, false, null, null,
15401                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15402                    unloaded.add(info);
15403                } else {
15404                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15405                }
15406            }
15407
15408            mSettings.writeLPr();
15409        }
15410        }
15411
15412        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15413        sendResourcesChangedBroadcast(false, false, unloaded, null);
15414    }
15415
15416    /**
15417     * Examine all users present on given mounted volume, and destroy data
15418     * belonging to users that are no longer valid, or whose user ID has been
15419     * recycled.
15420     */
15421    private void reconcileUsers(String volumeUuid) {
15422        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15423        if (ArrayUtils.isEmpty(files)) {
15424            Slog.d(TAG, "No users found on " + volumeUuid);
15425            return;
15426        }
15427
15428        for (File file : files) {
15429            if (!file.isDirectory()) continue;
15430
15431            final int userId;
15432            final UserInfo info;
15433            try {
15434                userId = Integer.parseInt(file.getName());
15435                info = sUserManager.getUserInfo(userId);
15436            } catch (NumberFormatException e) {
15437                Slog.w(TAG, "Invalid user directory " + file);
15438                continue;
15439            }
15440
15441            boolean destroyUser = false;
15442            if (info == null) {
15443                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15444                        + " because no matching user was found");
15445                destroyUser = true;
15446            } else {
15447                try {
15448                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15449                } catch (IOException e) {
15450                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15451                            + " because we failed to enforce serial number: " + e);
15452                    destroyUser = true;
15453                }
15454            }
15455
15456            if (destroyUser) {
15457                synchronized (mInstallLock) {
15458                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15459                }
15460            }
15461        }
15462
15463        final UserManager um = mContext.getSystemService(UserManager.class);
15464        for (UserInfo user : um.getUsers()) {
15465            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15466            if (userDir.exists()) continue;
15467
15468            try {
15469                UserManagerService.prepareUserDirectory(userDir);
15470                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15471            } catch (IOException e) {
15472                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15473            }
15474        }
15475    }
15476
15477    /**
15478     * Examine all apps present on given mounted volume, and destroy apps that
15479     * aren't expected, either due to uninstallation or reinstallation on
15480     * another volume.
15481     */
15482    private void reconcileApps(String volumeUuid) {
15483        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15484        if (ArrayUtils.isEmpty(files)) {
15485            Slog.d(TAG, "No apps found on " + volumeUuid);
15486            return;
15487        }
15488
15489        for (File file : files) {
15490            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15491                    && !PackageInstallerService.isStageName(file.getName());
15492            if (!isPackage) {
15493                // Ignore entries which are not packages
15494                continue;
15495            }
15496
15497            boolean destroyApp = false;
15498            String packageName = null;
15499            try {
15500                final PackageLite pkg = PackageParser.parsePackageLite(file,
15501                        PackageParser.PARSE_MUST_BE_APK);
15502                packageName = pkg.packageName;
15503
15504                synchronized (mPackages) {
15505                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15506                    if (ps == null) {
15507                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15508                                + volumeUuid + " because we found no install record");
15509                        destroyApp = true;
15510                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15511                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15512                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15513                        destroyApp = true;
15514                    }
15515                }
15516
15517            } catch (PackageParserException e) {
15518                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15519                destroyApp = true;
15520            }
15521
15522            if (destroyApp) {
15523                synchronized (mInstallLock) {
15524                    if (packageName != null) {
15525                        removeDataDirsLI(volumeUuid, packageName);
15526                    }
15527                    if (file.isDirectory()) {
15528                        mInstaller.rmPackageDir(file.getAbsolutePath());
15529                    } else {
15530                        file.delete();
15531                    }
15532                }
15533            }
15534        }
15535    }
15536
15537    private void unfreezePackage(String packageName) {
15538        synchronized (mPackages) {
15539            final PackageSetting ps = mSettings.mPackages.get(packageName);
15540            if (ps != null) {
15541                ps.frozen = false;
15542            }
15543        }
15544    }
15545
15546    @Override
15547    public int movePackage(final String packageName, final String volumeUuid) {
15548        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15549
15550        final int moveId = mNextMoveId.getAndIncrement();
15551        try {
15552            movePackageInternal(packageName, volumeUuid, moveId);
15553        } catch (PackageManagerException e) {
15554            Slog.w(TAG, "Failed to move " + packageName, e);
15555            mMoveCallbacks.notifyStatusChanged(moveId,
15556                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15557        }
15558        return moveId;
15559    }
15560
15561    private void movePackageInternal(final String packageName, final String volumeUuid,
15562            final int moveId) throws PackageManagerException {
15563        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15564        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15565        final PackageManager pm = mContext.getPackageManager();
15566
15567        final boolean currentAsec;
15568        final String currentVolumeUuid;
15569        final File codeFile;
15570        final String installerPackageName;
15571        final String packageAbiOverride;
15572        final int appId;
15573        final String seinfo;
15574        final String label;
15575
15576        // reader
15577        synchronized (mPackages) {
15578            final PackageParser.Package pkg = mPackages.get(packageName);
15579            final PackageSetting ps = mSettings.mPackages.get(packageName);
15580            if (pkg == null || ps == null) {
15581                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15582            }
15583
15584            if (pkg.applicationInfo.isSystemApp()) {
15585                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15586                        "Cannot move system application");
15587            }
15588
15589            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15590                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15591                        "Package already moved to " + volumeUuid);
15592            }
15593
15594            final File probe = new File(pkg.codePath);
15595            final File probeOat = new File(probe, "oat");
15596            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15597                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15598                        "Move only supported for modern cluster style installs");
15599            }
15600
15601            if (ps.frozen) {
15602                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15603                        "Failed to move already frozen package");
15604            }
15605            ps.frozen = true;
15606
15607            currentAsec = pkg.applicationInfo.isForwardLocked()
15608                    || pkg.applicationInfo.isExternalAsec();
15609            currentVolumeUuid = ps.volumeUuid;
15610            codeFile = new File(pkg.codePath);
15611            installerPackageName = ps.installerPackageName;
15612            packageAbiOverride = ps.cpuAbiOverrideString;
15613            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15614            seinfo = pkg.applicationInfo.seinfo;
15615            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15616        }
15617
15618        // Now that we're guarded by frozen state, kill app during move
15619        killApplication(packageName, appId, "move pkg");
15620
15621        final Bundle extras = new Bundle();
15622        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15623        extras.putString(Intent.EXTRA_TITLE, label);
15624        mMoveCallbacks.notifyCreated(moveId, extras);
15625
15626        int installFlags;
15627        final boolean moveCompleteApp;
15628        final File measurePath;
15629
15630        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15631            installFlags = INSTALL_INTERNAL;
15632            moveCompleteApp = !currentAsec;
15633            measurePath = Environment.getDataAppDirectory(volumeUuid);
15634        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15635            installFlags = INSTALL_EXTERNAL;
15636            moveCompleteApp = false;
15637            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15638        } else {
15639            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15640            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15641                    || !volume.isMountedWritable()) {
15642                unfreezePackage(packageName);
15643                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15644                        "Move location not mounted private volume");
15645            }
15646
15647            Preconditions.checkState(!currentAsec);
15648
15649            installFlags = INSTALL_INTERNAL;
15650            moveCompleteApp = true;
15651            measurePath = Environment.getDataAppDirectory(volumeUuid);
15652        }
15653
15654        final PackageStats stats = new PackageStats(null, -1);
15655        synchronized (mInstaller) {
15656            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15657                unfreezePackage(packageName);
15658                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15659                        "Failed to measure package size");
15660            }
15661        }
15662
15663        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15664                + stats.dataSize);
15665
15666        final long startFreeBytes = measurePath.getFreeSpace();
15667        final long sizeBytes;
15668        if (moveCompleteApp) {
15669            sizeBytes = stats.codeSize + stats.dataSize;
15670        } else {
15671            sizeBytes = stats.codeSize;
15672        }
15673
15674        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15675            unfreezePackage(packageName);
15676            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15677                    "Not enough free space to move");
15678        }
15679
15680        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15681
15682        final CountDownLatch installedLatch = new CountDownLatch(1);
15683        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15684            @Override
15685            public void onUserActionRequired(Intent intent) throws RemoteException {
15686                throw new IllegalStateException();
15687            }
15688
15689            @Override
15690            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15691                    Bundle extras) throws RemoteException {
15692                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15693                        + PackageManager.installStatusToString(returnCode, msg));
15694
15695                installedLatch.countDown();
15696
15697                // Regardless of success or failure of the move operation,
15698                // always unfreeze the package
15699                unfreezePackage(packageName);
15700
15701                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15702                switch (status) {
15703                    case PackageInstaller.STATUS_SUCCESS:
15704                        mMoveCallbacks.notifyStatusChanged(moveId,
15705                                PackageManager.MOVE_SUCCEEDED);
15706                        break;
15707                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15708                        mMoveCallbacks.notifyStatusChanged(moveId,
15709                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15710                        break;
15711                    default:
15712                        mMoveCallbacks.notifyStatusChanged(moveId,
15713                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15714                        break;
15715                }
15716            }
15717        };
15718
15719        final MoveInfo move;
15720        if (moveCompleteApp) {
15721            // Kick off a thread to report progress estimates
15722            new Thread() {
15723                @Override
15724                public void run() {
15725                    while (true) {
15726                        try {
15727                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15728                                break;
15729                            }
15730                        } catch (InterruptedException ignored) {
15731                        }
15732
15733                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15734                        final int progress = 10 + (int) MathUtils.constrain(
15735                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15736                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15737                    }
15738                }
15739            }.start();
15740
15741            final String dataAppName = codeFile.getName();
15742            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15743                    dataAppName, appId, seinfo);
15744        } else {
15745            move = null;
15746        }
15747
15748        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15749
15750        final Message msg = mHandler.obtainMessage(INIT_COPY);
15751        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15752        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15753                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15754        mHandler.sendMessage(msg);
15755    }
15756
15757    @Override
15758    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15759        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15760
15761        final int realMoveId = mNextMoveId.getAndIncrement();
15762        final Bundle extras = new Bundle();
15763        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15764        mMoveCallbacks.notifyCreated(realMoveId, extras);
15765
15766        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15767            @Override
15768            public void onCreated(int moveId, Bundle extras) {
15769                // Ignored
15770            }
15771
15772            @Override
15773            public void onStatusChanged(int moveId, int status, long estMillis) {
15774                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15775            }
15776        };
15777
15778        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15779        storage.setPrimaryStorageUuid(volumeUuid, callback);
15780        return realMoveId;
15781    }
15782
15783    @Override
15784    public int getMoveStatus(int moveId) {
15785        mContext.enforceCallingOrSelfPermission(
15786                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15787        return mMoveCallbacks.mLastStatus.get(moveId);
15788    }
15789
15790    @Override
15791    public void registerMoveCallback(IPackageMoveObserver callback) {
15792        mContext.enforceCallingOrSelfPermission(
15793                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15794        mMoveCallbacks.register(callback);
15795    }
15796
15797    @Override
15798    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15799        mContext.enforceCallingOrSelfPermission(
15800                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15801        mMoveCallbacks.unregister(callback);
15802    }
15803
15804    @Override
15805    public boolean setInstallLocation(int loc) {
15806        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15807                null);
15808        if (getInstallLocation() == loc) {
15809            return true;
15810        }
15811        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15812                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15813            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15814                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15815            return true;
15816        }
15817        return false;
15818   }
15819
15820    @Override
15821    public int getInstallLocation() {
15822        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15823                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15824                PackageHelper.APP_INSTALL_AUTO);
15825    }
15826
15827    /** Called by UserManagerService */
15828    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15829        mDirtyUsers.remove(userHandle);
15830        mSettings.removeUserLPw(userHandle);
15831        mPendingBroadcasts.remove(userHandle);
15832        if (mInstaller != null) {
15833            // Technically, we shouldn't be doing this with the package lock
15834            // held.  However, this is very rare, and there is already so much
15835            // other disk I/O going on, that we'll let it slide for now.
15836            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15837            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15838                final String volumeUuid = vol.getFsUuid();
15839                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15840                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15841            }
15842        }
15843        mUserNeedsBadging.delete(userHandle);
15844        removeUnusedPackagesLILPw(userManager, userHandle);
15845    }
15846
15847    /**
15848     * We're removing userHandle and would like to remove any downloaded packages
15849     * that are no longer in use by any other user.
15850     * @param userHandle the user being removed
15851     */
15852    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15853        final boolean DEBUG_CLEAN_APKS = false;
15854        int [] users = userManager.getUserIdsLPr();
15855        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15856        while (psit.hasNext()) {
15857            PackageSetting ps = psit.next();
15858            if (ps.pkg == null) {
15859                continue;
15860            }
15861            final String packageName = ps.pkg.packageName;
15862            // Skip over if system app
15863            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15864                continue;
15865            }
15866            if (DEBUG_CLEAN_APKS) {
15867                Slog.i(TAG, "Checking package " + packageName);
15868            }
15869            boolean keep = false;
15870            for (int i = 0; i < users.length; i++) {
15871                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15872                    keep = true;
15873                    if (DEBUG_CLEAN_APKS) {
15874                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15875                                + users[i]);
15876                    }
15877                    break;
15878                }
15879            }
15880            if (!keep) {
15881                if (DEBUG_CLEAN_APKS) {
15882                    Slog.i(TAG, "  Removing package " + packageName);
15883                }
15884                mHandler.post(new Runnable() {
15885                    public void run() {
15886                        deletePackageX(packageName, userHandle, 0);
15887                    } //end run
15888                });
15889            }
15890        }
15891    }
15892
15893    /** Called by UserManagerService */
15894    void createNewUserLILPw(int userHandle) {
15895        if (mInstaller != null) {
15896            mInstaller.createUserConfig(userHandle);
15897            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15898            applyFactoryDefaultBrowserLPw(userHandle);
15899        }
15900    }
15901
15902    void newUserCreatedLILPw(final int userHandle) {
15903        // We cannot grant the default permissions with a lock held as
15904        // we query providers from other components for default handlers
15905        // such as enabled IMEs, etc.
15906        mHandler.post(new Runnable() {
15907            @Override
15908            public void run() {
15909                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15910            }
15911        });
15912    }
15913
15914    @Override
15915    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15916        mContext.enforceCallingOrSelfPermission(
15917                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15918                "Only package verification agents can read the verifier device identity");
15919
15920        synchronized (mPackages) {
15921            return mSettings.getVerifierDeviceIdentityLPw();
15922        }
15923    }
15924
15925    @Override
15926    public void setPermissionEnforced(String permission, boolean enforced) {
15927        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15928        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15929            synchronized (mPackages) {
15930                if (mSettings.mReadExternalStorageEnforced == null
15931                        || mSettings.mReadExternalStorageEnforced != enforced) {
15932                    mSettings.mReadExternalStorageEnforced = enforced;
15933                    mSettings.writeLPr();
15934                }
15935            }
15936            // kill any non-foreground processes so we restart them and
15937            // grant/revoke the GID.
15938            final IActivityManager am = ActivityManagerNative.getDefault();
15939            if (am != null) {
15940                final long token = Binder.clearCallingIdentity();
15941                try {
15942                    am.killProcessesBelowForeground("setPermissionEnforcement");
15943                } catch (RemoteException e) {
15944                } finally {
15945                    Binder.restoreCallingIdentity(token);
15946                }
15947            }
15948        } else {
15949            throw new IllegalArgumentException("No selective enforcement for " + permission);
15950        }
15951    }
15952
15953    @Override
15954    @Deprecated
15955    public boolean isPermissionEnforced(String permission) {
15956        return true;
15957    }
15958
15959    @Override
15960    public boolean isStorageLow() {
15961        final long token = Binder.clearCallingIdentity();
15962        try {
15963            final DeviceStorageMonitorInternal
15964                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15965            if (dsm != null) {
15966                return dsm.isMemoryLow();
15967            } else {
15968                return false;
15969            }
15970        } finally {
15971            Binder.restoreCallingIdentity(token);
15972        }
15973    }
15974
15975    @Override
15976    public IPackageInstaller getPackageInstaller() {
15977        return mInstallerService;
15978    }
15979
15980    private boolean userNeedsBadging(int userId) {
15981        int index = mUserNeedsBadging.indexOfKey(userId);
15982        if (index < 0) {
15983            final UserInfo userInfo;
15984            final long token = Binder.clearCallingIdentity();
15985            try {
15986                userInfo = sUserManager.getUserInfo(userId);
15987            } finally {
15988                Binder.restoreCallingIdentity(token);
15989            }
15990            final boolean b;
15991            if (userInfo != null && userInfo.isManagedProfile()) {
15992                b = true;
15993            } else {
15994                b = false;
15995            }
15996            mUserNeedsBadging.put(userId, b);
15997            return b;
15998        }
15999        return mUserNeedsBadging.valueAt(index);
16000    }
16001
16002    @Override
16003    public KeySet getKeySetByAlias(String packageName, String alias) {
16004        if (packageName == null || alias == null) {
16005            return null;
16006        }
16007        synchronized(mPackages) {
16008            final PackageParser.Package pkg = mPackages.get(packageName);
16009            if (pkg == null) {
16010                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16011                throw new IllegalArgumentException("Unknown package: " + packageName);
16012            }
16013            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16014            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16015        }
16016    }
16017
16018    @Override
16019    public KeySet getSigningKeySet(String packageName) {
16020        if (packageName == null) {
16021            return null;
16022        }
16023        synchronized(mPackages) {
16024            final PackageParser.Package pkg = mPackages.get(packageName);
16025            if (pkg == null) {
16026                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16027                throw new IllegalArgumentException("Unknown package: " + packageName);
16028            }
16029            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16030                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16031                throw new SecurityException("May not access signing KeySet of other apps.");
16032            }
16033            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16034            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16035        }
16036    }
16037
16038    @Override
16039    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16040        if (packageName == null || ks == null) {
16041            return false;
16042        }
16043        synchronized(mPackages) {
16044            final PackageParser.Package pkg = mPackages.get(packageName);
16045            if (pkg == null) {
16046                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16047                throw new IllegalArgumentException("Unknown package: " + packageName);
16048            }
16049            IBinder ksh = ks.getToken();
16050            if (ksh instanceof KeySetHandle) {
16051                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16052                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16053            }
16054            return false;
16055        }
16056    }
16057
16058    @Override
16059    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16060        if (packageName == null || ks == null) {
16061            return false;
16062        }
16063        synchronized(mPackages) {
16064            final PackageParser.Package pkg = mPackages.get(packageName);
16065            if (pkg == null) {
16066                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16067                throw new IllegalArgumentException("Unknown package: " + packageName);
16068            }
16069            IBinder ksh = ks.getToken();
16070            if (ksh instanceof KeySetHandle) {
16071                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16072                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16073            }
16074            return false;
16075        }
16076    }
16077
16078    public void getUsageStatsIfNoPackageUsageInfo() {
16079        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16080            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16081            if (usm == null) {
16082                throw new IllegalStateException("UsageStatsManager must be initialized");
16083            }
16084            long now = System.currentTimeMillis();
16085            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16086            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16087                String packageName = entry.getKey();
16088                PackageParser.Package pkg = mPackages.get(packageName);
16089                if (pkg == null) {
16090                    continue;
16091                }
16092                UsageStats usage = entry.getValue();
16093                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16094                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16095            }
16096        }
16097    }
16098
16099    /**
16100     * Check and throw if the given before/after packages would be considered a
16101     * downgrade.
16102     */
16103    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16104            throws PackageManagerException {
16105        if (after.versionCode < before.mVersionCode) {
16106            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16107                    "Update version code " + after.versionCode + " is older than current "
16108                    + before.mVersionCode);
16109        } else if (after.versionCode == before.mVersionCode) {
16110            if (after.baseRevisionCode < before.baseRevisionCode) {
16111                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16112                        "Update base revision code " + after.baseRevisionCode
16113                        + " is older than current " + before.baseRevisionCode);
16114            }
16115
16116            if (!ArrayUtils.isEmpty(after.splitNames)) {
16117                for (int i = 0; i < after.splitNames.length; i++) {
16118                    final String splitName = after.splitNames[i];
16119                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16120                    if (j != -1) {
16121                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16122                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16123                                    "Update split " + splitName + " revision code "
16124                                    + after.splitRevisionCodes[i] + " is older than current "
16125                                    + before.splitRevisionCodes[j]);
16126                        }
16127                    }
16128                }
16129            }
16130        }
16131    }
16132
16133    private static class MoveCallbacks extends Handler {
16134        private static final int MSG_CREATED = 1;
16135        private static final int MSG_STATUS_CHANGED = 2;
16136
16137        private final RemoteCallbackList<IPackageMoveObserver>
16138                mCallbacks = new RemoteCallbackList<>();
16139
16140        private final SparseIntArray mLastStatus = new SparseIntArray();
16141
16142        public MoveCallbacks(Looper looper) {
16143            super(looper);
16144        }
16145
16146        public void register(IPackageMoveObserver callback) {
16147            mCallbacks.register(callback);
16148        }
16149
16150        public void unregister(IPackageMoveObserver callback) {
16151            mCallbacks.unregister(callback);
16152        }
16153
16154        @Override
16155        public void handleMessage(Message msg) {
16156            final SomeArgs args = (SomeArgs) msg.obj;
16157            final int n = mCallbacks.beginBroadcast();
16158            for (int i = 0; i < n; i++) {
16159                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16160                try {
16161                    invokeCallback(callback, msg.what, args);
16162                } catch (RemoteException ignored) {
16163                }
16164            }
16165            mCallbacks.finishBroadcast();
16166            args.recycle();
16167        }
16168
16169        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16170                throws RemoteException {
16171            switch (what) {
16172                case MSG_CREATED: {
16173                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16174                    break;
16175                }
16176                case MSG_STATUS_CHANGED: {
16177                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16178                    break;
16179                }
16180            }
16181        }
16182
16183        private void notifyCreated(int moveId, Bundle extras) {
16184            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16185
16186            final SomeArgs args = SomeArgs.obtain();
16187            args.argi1 = moveId;
16188            args.arg2 = extras;
16189            obtainMessage(MSG_CREATED, args).sendToTarget();
16190        }
16191
16192        private void notifyStatusChanged(int moveId, int status) {
16193            notifyStatusChanged(moveId, status, -1);
16194        }
16195
16196        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16197            Slog.v(TAG, "Move " + moveId + " status " + status);
16198
16199            final SomeArgs args = SomeArgs.obtain();
16200            args.argi1 = moveId;
16201            args.argi2 = status;
16202            args.arg3 = estMillis;
16203            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16204
16205            synchronized (mLastStatus) {
16206                mLastStatus.put(moveId, status);
16207            }
16208        }
16209    }
16210
16211    private final class OnPermissionChangeListeners extends Handler {
16212        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16213
16214        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16215                new RemoteCallbackList<>();
16216
16217        public OnPermissionChangeListeners(Looper looper) {
16218            super(looper);
16219        }
16220
16221        @Override
16222        public void handleMessage(Message msg) {
16223            switch (msg.what) {
16224                case MSG_ON_PERMISSIONS_CHANGED: {
16225                    final int uid = msg.arg1;
16226                    handleOnPermissionsChanged(uid);
16227                } break;
16228            }
16229        }
16230
16231        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16232            mPermissionListeners.register(listener);
16233
16234        }
16235
16236        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16237            mPermissionListeners.unregister(listener);
16238        }
16239
16240        public void onPermissionsChanged(int uid) {
16241            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16242                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16243            }
16244        }
16245
16246        private void handleOnPermissionsChanged(int uid) {
16247            final int count = mPermissionListeners.beginBroadcast();
16248            try {
16249                for (int i = 0; i < count; i++) {
16250                    IOnPermissionsChangeListener callback = mPermissionListeners
16251                            .getBroadcastItem(i);
16252                    try {
16253                        callback.onPermissionsChanged(uid);
16254                    } catch (RemoteException e) {
16255                        Log.e(TAG, "Permission listener is dead", e);
16256                    }
16257                }
16258            } finally {
16259                mPermissionListeners.finishBroadcast();
16260            }
16261        }
16262    }
16263
16264    private class PackageManagerInternalImpl extends PackageManagerInternal {
16265        @Override
16266        public void setLocationPackagesProvider(PackagesProvider provider) {
16267            synchronized (mPackages) {
16268                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16269            }
16270        }
16271
16272        @Override
16273        public void setImePackagesProvider(PackagesProvider provider) {
16274            synchronized (mPackages) {
16275                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16276            }
16277        }
16278
16279        @Override
16280        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16281            synchronized (mPackages) {
16282                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16283            }
16284        }
16285
16286        @Override
16287        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16288            synchronized (mPackages) {
16289                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16290            }
16291        }
16292
16293        @Override
16294        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16295            synchronized (mPackages) {
16296                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16297            }
16298        }
16299
16300        @Override
16301        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16302            synchronized (mPackages) {
16303                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16304            }
16305        }
16306
16307        @Override
16308        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16309            synchronized (mPackages) {
16310                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16311                        packageName, userId);
16312            }
16313        }
16314
16315        @Override
16316        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16317            synchronized (mPackages) {
16318                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16319                        packageName, userId);
16320            }
16321        }
16322    }
16323
16324    @Override
16325    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16326        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16327        synchronized (mPackages) {
16328            final long identity = Binder.clearCallingIdentity();
16329            try {
16330                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16331                        packageNames, userId);
16332            } finally {
16333                Binder.restoreCallingIdentity(identity);
16334            }
16335        }
16336    }
16337
16338    private static void enforceSystemOrPhoneCaller(String tag) {
16339        int callingUid = Binder.getCallingUid();
16340        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16341            throw new SecurityException(
16342                    "Cannot call " + tag + " from UID " + callingUid);
16343        }
16344    }
16345}
16346