PackageManagerService.java revision 0fd2d2b124d2aa614131c7b9cedde9d18e830724
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    /**
481     * Tracks new system packages [receiving in an OTA] that we expect to
482     * find updated user-installed versions. Keys are package name, values
483     * are package location.
484     */
485    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
486
487    final Settings mSettings;
488    boolean mRestoredSettings;
489
490    // System configuration read by SystemConfig.
491    final int[] mGlobalGids;
492    final SparseArray<ArraySet<String>> mSystemPermissions;
493    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
494
495    // If mac_permissions.xml was found for seinfo labeling.
496    boolean mFoundPolicyFile;
497
498    // If a recursive restorecon of /data/data/<pkg> is needed.
499    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
500
501    public static final class SharedLibraryEntry {
502        public final String path;
503        public final String apk;
504
505        SharedLibraryEntry(String _path, String _apk) {
506            path = _path;
507            apk = _apk;
508        }
509    }
510
511    // Currently known shared libraries.
512    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
513            new ArrayMap<String, SharedLibraryEntry>();
514
515    // All available activities, for your resolving pleasure.
516    final ActivityIntentResolver mActivities =
517            new ActivityIntentResolver();
518
519    // All available receivers, for your resolving pleasure.
520    final ActivityIntentResolver mReceivers =
521            new ActivityIntentResolver();
522
523    // All available services, for your resolving pleasure.
524    final ServiceIntentResolver mServices = new ServiceIntentResolver();
525
526    // All available providers, for your resolving pleasure.
527    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
528
529    // Mapping from provider base names (first directory in content URI codePath)
530    // to the provider information.
531    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
532            new ArrayMap<String, PackageParser.Provider>();
533
534    // Mapping from instrumentation class names to info about them.
535    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
536            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
537
538    // Mapping from permission names to info about them.
539    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
540            new ArrayMap<String, PackageParser.PermissionGroup>();
541
542    // Packages whose data we have transfered into another package, thus
543    // should no longer exist.
544    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
545
546    // Broadcast actions that are only available to the system.
547    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
548
549    /** List of packages waiting for verification. */
550    final SparseArray<PackageVerificationState> mPendingVerification
551            = new SparseArray<PackageVerificationState>();
552
553    /** Set of packages associated with each app op permission. */
554    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
555
556    final PackageInstallerService mInstallerService;
557
558    private final PackageDexOptimizer mPackageDexOptimizer;
559
560    private AtomicInteger mNextMoveId = new AtomicInteger();
561    private final MoveCallbacks mMoveCallbacks;
562
563    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
564
565    // Cache of users who need badging.
566    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
567
568    /** Token for keys in mPendingVerification. */
569    private int mPendingVerificationToken = 0;
570
571    volatile boolean mSystemReady;
572    volatile boolean mSafeMode;
573    volatile boolean mHasSystemUidErrors;
574
575    ApplicationInfo mAndroidApplication;
576    final ActivityInfo mResolveActivity = new ActivityInfo();
577    final ResolveInfo mResolveInfo = new ResolveInfo();
578    ComponentName mResolveComponentName;
579    PackageParser.Package mPlatformPackage;
580    ComponentName mCustomResolverComponentName;
581
582    boolean mResolverReplaced = false;
583
584    private final ComponentName mIntentFilterVerifierComponent;
585    private int mIntentFilterVerificationToken = 0;
586
587    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
588            = new SparseArray<IntentFilterVerificationState>();
589
590    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
591            new DefaultPermissionGrantPolicy(this);
592
593    private static class IFVerificationParams {
594        PackageParser.Package pkg;
595        boolean replacing;
596        int userId;
597        int verifierUid;
598
599        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
600                int _userId, int _verifierUid) {
601            pkg = _pkg;
602            replacing = _replacing;
603            userId = _userId;
604            replacing = _replacing;
605            verifierUid = _verifierUid;
606        }
607    }
608
609    private interface IntentFilterVerifier<T extends IntentFilter> {
610        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
611                                               T filter, String packageName);
612        void startVerifications(int userId);
613        void receiveVerificationResponse(int verificationId);
614    }
615
616    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
617        private Context mContext;
618        private ComponentName mIntentFilterVerifierComponent;
619        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
620
621        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
622            mContext = context;
623            mIntentFilterVerifierComponent = verifierComponent;
624        }
625
626        private String getDefaultScheme() {
627            return IntentFilter.SCHEME_HTTPS;
628        }
629
630        @Override
631        public void startVerifications(int userId) {
632            // Launch verifications requests
633            int count = mCurrentIntentFilterVerifications.size();
634            for (int n=0; n<count; n++) {
635                int verificationId = mCurrentIntentFilterVerifications.get(n);
636                final IntentFilterVerificationState ivs =
637                        mIntentFilterVerificationStates.get(verificationId);
638
639                String packageName = ivs.getPackageName();
640
641                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
642                final int filterCount = filters.size();
643                ArraySet<String> domainsSet = new ArraySet<>();
644                for (int m=0; m<filterCount; m++) {
645                    PackageParser.ActivityIntentInfo filter = filters.get(m);
646                    domainsSet.addAll(filter.getHostsList());
647                }
648                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
649                synchronized (mPackages) {
650                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
651                            packageName, domainsList) != null) {
652                        scheduleWriteSettingsLocked();
653                    }
654                }
655                sendVerificationRequest(userId, verificationId, ivs);
656            }
657            mCurrentIntentFilterVerifications.clear();
658        }
659
660        private void sendVerificationRequest(int userId, int verificationId,
661                IntentFilterVerificationState ivs) {
662
663            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
664            verificationIntent.putExtra(
665                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
666                    verificationId);
667            verificationIntent.putExtra(
668                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
669                    getDefaultScheme());
670            verificationIntent.putExtra(
671                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
672                    ivs.getHostsString());
673            verificationIntent.putExtra(
674                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
675                    ivs.getPackageName());
676            verificationIntent.setComponent(mIntentFilterVerifierComponent);
677            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
678
679            UserHandle user = new UserHandle(userId);
680            mContext.sendBroadcastAsUser(verificationIntent, user);
681            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
682                    "Sending IntentFilter verification broadcast");
683        }
684
685        public void receiveVerificationResponse(int verificationId) {
686            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
687
688            final boolean verified = ivs.isVerified();
689
690            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
691            final int count = filters.size();
692            if (DEBUG_DOMAIN_VERIFICATION) {
693                Slog.i(TAG, "Received verification response " + verificationId
694                        + " for " + count + " filters, verified=" + verified);
695            }
696            for (int n=0; n<count; n++) {
697                PackageParser.ActivityIntentInfo filter = filters.get(n);
698                filter.setVerified(verified);
699
700                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
701                        + " verified with result:" + verified + " and hosts:"
702                        + ivs.getHostsString());
703            }
704
705            mIntentFilterVerificationStates.remove(verificationId);
706
707            final String packageName = ivs.getPackageName();
708            IntentFilterVerificationInfo ivi = null;
709
710            synchronized (mPackages) {
711                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
712            }
713            if (ivi == null) {
714                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
715                        + verificationId + " packageName:" + packageName);
716                return;
717            }
718            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
719                    "Updating IntentFilterVerificationInfo for package " + packageName
720                            +" verificationId:" + verificationId);
721
722            synchronized (mPackages) {
723                if (verified) {
724                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
725                } else {
726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
727                }
728                scheduleWriteSettingsLocked();
729
730                final int userId = ivs.getUserId();
731                if (userId != UserHandle.USER_ALL) {
732                    final int userStatus =
733                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
734
735                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
736                    boolean needUpdate = false;
737
738                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
739                    // already been set by the User thru the Disambiguation dialog
740                    switch (userStatus) {
741                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
742                            if (verified) {
743                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
744                            } else {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
746                            }
747                            needUpdate = true;
748                            break;
749
750                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
751                            if (verified) {
752                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
753                                needUpdate = true;
754                            }
755                            break;
756
757                        default:
758                            // Nothing to do
759                    }
760
761                    if (needUpdate) {
762                        mSettings.updateIntentFilterVerificationStatusLPw(
763                                packageName, updatedStatus, userId);
764                        scheduleWritePackageRestrictionsLocked(userId);
765                    }
766                }
767            }
768        }
769
770        @Override
771        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
772                    ActivityIntentInfo filter, String packageName) {
773            if (!hasValidDomains(filter)) {
774                return false;
775            }
776            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
777            if (ivs == null) {
778                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
779                        packageName);
780            }
781            if (DEBUG_DOMAIN_VERIFICATION) {
782                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
783            }
784            ivs.addFilter(filter);
785            return true;
786        }
787
788        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
789                int userId, int verificationId, String packageName) {
790            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
791                    verifierUid, userId, packageName);
792            ivs.setPendingState();
793            synchronized (mPackages) {
794                mIntentFilterVerificationStates.append(verificationId, ivs);
795                mCurrentIntentFilterVerifications.add(verificationId);
796            }
797            return ivs;
798        }
799    }
800
801    private static boolean hasValidDomains(ActivityIntentInfo filter) {
802        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
803                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
804        if (!hasHTTPorHTTPS) {
805            return false;
806        }
807        return true;
808    }
809
810    private IntentFilterVerifier mIntentFilterVerifier;
811
812    // Set of pending broadcasts for aggregating enable/disable of components.
813    static class PendingPackageBroadcasts {
814        // for each user id, a map of <package name -> components within that package>
815        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
816
817        public PendingPackageBroadcasts() {
818            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
819        }
820
821        public ArrayList<String> get(int userId, String packageName) {
822            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
823            return packages.get(packageName);
824        }
825
826        public void put(int userId, String packageName, ArrayList<String> components) {
827            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
828            packages.put(packageName, components);
829        }
830
831        public void remove(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
833            if (packages != null) {
834                packages.remove(packageName);
835            }
836        }
837
838        public void remove(int userId) {
839            mUidMap.remove(userId);
840        }
841
842        public int userIdCount() {
843            return mUidMap.size();
844        }
845
846        public int userIdAt(int n) {
847            return mUidMap.keyAt(n);
848        }
849
850        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
851            return mUidMap.get(userId);
852        }
853
854        public int size() {
855            // total number of pending broadcast entries across all userIds
856            int num = 0;
857            for (int i = 0; i< mUidMap.size(); i++) {
858                num += mUidMap.valueAt(i).size();
859            }
860            return num;
861        }
862
863        public void clear() {
864            mUidMap.clear();
865        }
866
867        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
868            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
869            if (map == null) {
870                map = new ArrayMap<String, ArrayList<String>>();
871                mUidMap.put(userId, map);
872            }
873            return map;
874        }
875    }
876    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
877
878    // Service Connection to remote media container service to copy
879    // package uri's from external media onto secure containers
880    // or internal storage.
881    private IMediaContainerService mContainerService = null;
882
883    static final int SEND_PENDING_BROADCAST = 1;
884    static final int MCS_BOUND = 3;
885    static final int END_COPY = 4;
886    static final int INIT_COPY = 5;
887    static final int MCS_UNBIND = 6;
888    static final int START_CLEANING_PACKAGE = 7;
889    static final int FIND_INSTALL_LOC = 8;
890    static final int POST_INSTALL = 9;
891    static final int MCS_RECONNECT = 10;
892    static final int MCS_GIVE_UP = 11;
893    static final int UPDATED_MEDIA_STATUS = 12;
894    static final int WRITE_SETTINGS = 13;
895    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
896    static final int PACKAGE_VERIFIED = 15;
897    static final int CHECK_PENDING_VERIFICATION = 16;
898    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
899    static final int INTENT_FILTER_VERIFIED = 18;
900
901    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
902
903    // Delay time in millisecs
904    static final int BROADCAST_DELAY = 10 * 1000;
905
906    static UserManagerService sUserManager;
907
908    // Stores a list of users whose package restrictions file needs to be updated
909    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
910
911    final private DefaultContainerConnection mDefContainerConn =
912            new DefaultContainerConnection();
913    class DefaultContainerConnection implements ServiceConnection {
914        public void onServiceConnected(ComponentName name, IBinder service) {
915            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
916            IMediaContainerService imcs =
917                IMediaContainerService.Stub.asInterface(service);
918            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
919        }
920
921        public void onServiceDisconnected(ComponentName name) {
922            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
923        }
924    }
925
926    // Recordkeeping of restore-after-install operations that are currently in flight
927    // between the Package Manager and the Backup Manager
928    class PostInstallData {
929        public InstallArgs args;
930        public PackageInstalledInfo res;
931
932        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
933            args = _a;
934            res = _r;
935        }
936    }
937
938    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
939    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
940
941    // XML tags for backup/restore of various bits of state
942    private static final String TAG_PREFERRED_BACKUP = "pa";
943    private static final String TAG_DEFAULT_APPS = "da";
944    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
945
946    final String mRequiredVerifierPackage;
947    final String mRequiredInstallerPackage;
948
949    private final PackageUsage mPackageUsage = new PackageUsage();
950
951    private class PackageUsage {
952        private static final int WRITE_INTERVAL
953            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
954
955        private final Object mFileLock = new Object();
956        private final AtomicLong mLastWritten = new AtomicLong(0);
957        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
958
959        private boolean mIsHistoricalPackageUsageAvailable = true;
960
961        boolean isHistoricalPackageUsageAvailable() {
962            return mIsHistoricalPackageUsageAvailable;
963        }
964
965        void write(boolean force) {
966            if (force) {
967                writeInternal();
968                return;
969            }
970            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
971                && !DEBUG_DEXOPT) {
972                return;
973            }
974            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
975                new Thread("PackageUsage_DiskWriter") {
976                    @Override
977                    public void run() {
978                        try {
979                            writeInternal();
980                        } finally {
981                            mBackgroundWriteRunning.set(false);
982                        }
983                    }
984                }.start();
985            }
986        }
987
988        private void writeInternal() {
989            synchronized (mPackages) {
990                synchronized (mFileLock) {
991                    AtomicFile file = getFile();
992                    FileOutputStream f = null;
993                    try {
994                        f = file.startWrite();
995                        BufferedOutputStream out = new BufferedOutputStream(f);
996                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
997                        StringBuilder sb = new StringBuilder();
998                        for (PackageParser.Package pkg : mPackages.values()) {
999                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1000                                continue;
1001                            }
1002                            sb.setLength(0);
1003                            sb.append(pkg.packageName);
1004                            sb.append(' ');
1005                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1006                            sb.append('\n');
1007                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1008                        }
1009                        out.flush();
1010                        file.finishWrite(f);
1011                    } catch (IOException e) {
1012                        if (f != null) {
1013                            file.failWrite(f);
1014                        }
1015                        Log.e(TAG, "Failed to write package usage times", e);
1016                    }
1017                }
1018            }
1019            mLastWritten.set(SystemClock.elapsedRealtime());
1020        }
1021
1022        void readLP() {
1023            synchronized (mFileLock) {
1024                AtomicFile file = getFile();
1025                BufferedInputStream in = null;
1026                try {
1027                    in = new BufferedInputStream(file.openRead());
1028                    StringBuffer sb = new StringBuffer();
1029                    while (true) {
1030                        String packageName = readToken(in, sb, ' ');
1031                        if (packageName == null) {
1032                            break;
1033                        }
1034                        String timeInMillisString = readToken(in, sb, '\n');
1035                        if (timeInMillisString == null) {
1036                            throw new IOException("Failed to find last usage time for package "
1037                                                  + packageName);
1038                        }
1039                        PackageParser.Package pkg = mPackages.get(packageName);
1040                        if (pkg == null) {
1041                            continue;
1042                        }
1043                        long timeInMillis;
1044                        try {
1045                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1046                        } catch (NumberFormatException e) {
1047                            throw new IOException("Failed to parse " + timeInMillisString
1048                                                  + " as a long.", e);
1049                        }
1050                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1051                    }
1052                } catch (FileNotFoundException expected) {
1053                    mIsHistoricalPackageUsageAvailable = false;
1054                } catch (IOException e) {
1055                    Log.w(TAG, "Failed to read package usage times", e);
1056                } finally {
1057                    IoUtils.closeQuietly(in);
1058                }
1059            }
1060            mLastWritten.set(SystemClock.elapsedRealtime());
1061        }
1062
1063        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1064                throws IOException {
1065            sb.setLength(0);
1066            while (true) {
1067                int ch = in.read();
1068                if (ch == -1) {
1069                    if (sb.length() == 0) {
1070                        return null;
1071                    }
1072                    throw new IOException("Unexpected EOF");
1073                }
1074                if (ch == endOfToken) {
1075                    return sb.toString();
1076                }
1077                sb.append((char)ch);
1078            }
1079        }
1080
1081        private AtomicFile getFile() {
1082            File dataDir = Environment.getDataDirectory();
1083            File systemDir = new File(dataDir, "system");
1084            File fname = new File(systemDir, "package-usage.list");
1085            return new AtomicFile(fname);
1086        }
1087    }
1088
1089    class PackageHandler extends Handler {
1090        private boolean mBound = false;
1091        final ArrayList<HandlerParams> mPendingInstalls =
1092            new ArrayList<HandlerParams>();
1093
1094        private boolean connectToService() {
1095            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1096                    " DefaultContainerService");
1097            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1098            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1099            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1100                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1101                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1102                mBound = true;
1103                return true;
1104            }
1105            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1106            return false;
1107        }
1108
1109        private void disconnectService() {
1110            mContainerService = null;
1111            mBound = false;
1112            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1113            mContext.unbindService(mDefContainerConn);
1114            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1115        }
1116
1117        PackageHandler(Looper looper) {
1118            super(looper);
1119        }
1120
1121        public void handleMessage(Message msg) {
1122            try {
1123                doHandleMessage(msg);
1124            } finally {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126            }
1127        }
1128
1129        void doHandleMessage(Message msg) {
1130            switch (msg.what) {
1131                case INIT_COPY: {
1132                    HandlerParams params = (HandlerParams) msg.obj;
1133                    int idx = mPendingInstalls.size();
1134                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1135                    // If a bind was already initiated we dont really
1136                    // need to do anything. The pending install
1137                    // will be processed later on.
1138                    if (!mBound) {
1139                        // If this is the only one pending we might
1140                        // have to bind to the service again.
1141                        if (!connectToService()) {
1142                            Slog.e(TAG, "Failed to bind to media container service");
1143                            params.serviceError();
1144                            return;
1145                        } else {
1146                            // Once we bind to the service, the first
1147                            // pending request will be processed.
1148                            mPendingInstalls.add(idx, params);
1149                        }
1150                    } else {
1151                        mPendingInstalls.add(idx, params);
1152                        // Already bound to the service. Just make
1153                        // sure we trigger off processing the first request.
1154                        if (idx == 0) {
1155                            mHandler.sendEmptyMessage(MCS_BOUND);
1156                        }
1157                    }
1158                    break;
1159                }
1160                case MCS_BOUND: {
1161                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1162                    if (msg.obj != null) {
1163                        mContainerService = (IMediaContainerService) msg.obj;
1164                    }
1165                    if (mContainerService == null) {
1166                        if (!mBound) {
1167                            // Something seriously wrong since we are not bound and we are not
1168                            // waiting for connection. Bail out.
1169                            Slog.e(TAG, "Cannot bind to media container service");
1170                            for (HandlerParams params : mPendingInstalls) {
1171                                // Indicate service bind error
1172                                params.serviceError();
1173                            }
1174                            mPendingInstalls.clear();
1175                        } else {
1176                            Slog.w(TAG, "Waiting to connect to media container service");
1177                        }
1178                    } else if (mPendingInstalls.size() > 0) {
1179                        HandlerParams params = mPendingInstalls.get(0);
1180                        if (params != null) {
1181                            if (params.startCopy()) {
1182                                // We are done...  look for more work or to
1183                                // go idle.
1184                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1185                                        "Checking for more work or unbind...");
1186                                // Delete pending install
1187                                if (mPendingInstalls.size() > 0) {
1188                                    mPendingInstalls.remove(0);
1189                                }
1190                                if (mPendingInstalls.size() == 0) {
1191                                    if (mBound) {
1192                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1193                                                "Posting delayed MCS_UNBIND");
1194                                        removeMessages(MCS_UNBIND);
1195                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1196                                        // Unbind after a little delay, to avoid
1197                                        // continual thrashing.
1198                                        sendMessageDelayed(ubmsg, 10000);
1199                                    }
1200                                } else {
1201                                    // There are more pending requests in queue.
1202                                    // Just post MCS_BOUND message to trigger processing
1203                                    // of next pending install.
1204                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1205                                            "Posting MCS_BOUND for next work");
1206                                    mHandler.sendEmptyMessage(MCS_BOUND);
1207                                }
1208                            }
1209                        }
1210                    } else {
1211                        // Should never happen ideally.
1212                        Slog.w(TAG, "Empty queue");
1213                    }
1214                    break;
1215                }
1216                case MCS_RECONNECT: {
1217                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1218                    if (mPendingInstalls.size() > 0) {
1219                        if (mBound) {
1220                            disconnectService();
1221                        }
1222                        if (!connectToService()) {
1223                            Slog.e(TAG, "Failed to bind to media container service");
1224                            for (HandlerParams params : mPendingInstalls) {
1225                                // Indicate service bind error
1226                                params.serviceError();
1227                            }
1228                            mPendingInstalls.clear();
1229                        }
1230                    }
1231                    break;
1232                }
1233                case MCS_UNBIND: {
1234                    // If there is no actual work left, then time to unbind.
1235                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1236
1237                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1238                        if (mBound) {
1239                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1240
1241                            disconnectService();
1242                        }
1243                    } else if (mPendingInstalls.size() > 0) {
1244                        // There are more pending requests in queue.
1245                        // Just post MCS_BOUND message to trigger processing
1246                        // of next pending install.
1247                        mHandler.sendEmptyMessage(MCS_BOUND);
1248                    }
1249
1250                    break;
1251                }
1252                case MCS_GIVE_UP: {
1253                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1254                    mPendingInstalls.remove(0);
1255                    break;
1256                }
1257                case SEND_PENDING_BROADCAST: {
1258                    String packages[];
1259                    ArrayList<String> components[];
1260                    int size = 0;
1261                    int uids[];
1262                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1263                    synchronized (mPackages) {
1264                        if (mPendingBroadcasts == null) {
1265                            return;
1266                        }
1267                        size = mPendingBroadcasts.size();
1268                        if (size <= 0) {
1269                            // Nothing to be done. Just return
1270                            return;
1271                        }
1272                        packages = new String[size];
1273                        components = new ArrayList[size];
1274                        uids = new int[size];
1275                        int i = 0;  // filling out the above arrays
1276
1277                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1278                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1279                            Iterator<Map.Entry<String, ArrayList<String>>> it
1280                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1281                                            .entrySet().iterator();
1282                            while (it.hasNext() && i < size) {
1283                                Map.Entry<String, ArrayList<String>> ent = it.next();
1284                                packages[i] = ent.getKey();
1285                                components[i] = ent.getValue();
1286                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1287                                uids[i] = (ps != null)
1288                                        ? UserHandle.getUid(packageUserId, ps.appId)
1289                                        : -1;
1290                                i++;
1291                            }
1292                        }
1293                        size = i;
1294                        mPendingBroadcasts.clear();
1295                    }
1296                    // Send broadcasts
1297                    for (int i = 0; i < size; i++) {
1298                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1299                    }
1300                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1301                    break;
1302                }
1303                case START_CLEANING_PACKAGE: {
1304                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1305                    final String packageName = (String)msg.obj;
1306                    final int userId = msg.arg1;
1307                    final boolean andCode = msg.arg2 != 0;
1308                    synchronized (mPackages) {
1309                        if (userId == UserHandle.USER_ALL) {
1310                            int[] users = sUserManager.getUserIds();
1311                            for (int user : users) {
1312                                mSettings.addPackageToCleanLPw(
1313                                        new PackageCleanItem(user, packageName, andCode));
1314                            }
1315                        } else {
1316                            mSettings.addPackageToCleanLPw(
1317                                    new PackageCleanItem(userId, packageName, andCode));
1318                        }
1319                    }
1320                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1321                    startCleaningPackages();
1322                } break;
1323                case POST_INSTALL: {
1324                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1325                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1326                    mRunningInstalls.delete(msg.arg1);
1327                    boolean deleteOld = false;
1328
1329                    if (data != null) {
1330                        InstallArgs args = data.args;
1331                        PackageInstalledInfo res = data.res;
1332
1333                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1334                            final String packageName = res.pkg.applicationInfo.packageName;
1335                            res.removedInfo.sendBroadcast(false, true, false);
1336                            Bundle extras = new Bundle(1);
1337                            extras.putInt(Intent.EXTRA_UID, res.uid);
1338
1339                            // Now that we successfully installed the package, grant runtime
1340                            // permissions if requested before broadcasting the install.
1341                            if ((args.installFlags
1342                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1343                                grantRequestedRuntimePermissions(res.pkg,
1344                                        args.user.getIdentifier());
1345                            }
1346
1347                            // Determine the set of users who are adding this
1348                            // package for the first time vs. those who are seeing
1349                            // an update.
1350                            int[] firstUsers;
1351                            int[] updateUsers = new int[0];
1352                            if (res.origUsers == null || res.origUsers.length == 0) {
1353                                firstUsers = res.newUsers;
1354                            } else {
1355                                firstUsers = new int[0];
1356                                for (int i=0; i<res.newUsers.length; i++) {
1357                                    int user = res.newUsers[i];
1358                                    boolean isNew = true;
1359                                    for (int j=0; j<res.origUsers.length; j++) {
1360                                        if (res.origUsers[j] == user) {
1361                                            isNew = false;
1362                                            break;
1363                                        }
1364                                    }
1365                                    if (isNew) {
1366                                        int[] newFirst = new int[firstUsers.length+1];
1367                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1368                                                firstUsers.length);
1369                                        newFirst[firstUsers.length] = user;
1370                                        firstUsers = newFirst;
1371                                    } else {
1372                                        int[] newUpdate = new int[updateUsers.length+1];
1373                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1374                                                updateUsers.length);
1375                                        newUpdate[updateUsers.length] = user;
1376                                        updateUsers = newUpdate;
1377                                    }
1378                                }
1379                            }
1380                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1381                                    packageName, extras, null, null, firstUsers);
1382                            final boolean update = res.removedInfo.removedPackage != null;
1383                            if (update) {
1384                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1385                            }
1386                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1387                                    packageName, extras, null, null, updateUsers);
1388                            if (update) {
1389                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1390                                        packageName, extras, null, null, updateUsers);
1391                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1392                                        null, null, packageName, null, updateUsers);
1393
1394                                // treat asec-hosted packages like removable media on upgrade
1395                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1396                                    if (DEBUG_INSTALL) {
1397                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1398                                                + " is ASEC-hosted -> AVAILABLE");
1399                                    }
1400                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1401                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1402                                    pkgList.add(packageName);
1403                                    sendResourcesChangedBroadcast(true, true,
1404                                            pkgList,uidArray, null);
1405                                }
1406                            }
1407                            if (res.removedInfo.args != null) {
1408                                // Remove the replaced package's older resources safely now
1409                                deleteOld = true;
1410                            }
1411
1412                            // If this app is a browser and it's newly-installed for some
1413                            // users, clear any default-browser state in those users
1414                            if (firstUsers.length > 0) {
1415                                // the app's nature doesn't depend on the user, so we can just
1416                                // check its browser nature in any user and generalize.
1417                                if (packageIsBrowser(packageName, firstUsers[0])) {
1418                                    synchronized (mPackages) {
1419                                        for (int userId : firstUsers) {
1420                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1421                                        }
1422                                    }
1423                                }
1424                            }
1425                            // Log current value of "unknown sources" setting
1426                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1427                                getUnknownSourcesSettings());
1428                        }
1429                        // Force a gc to clear up things
1430                        Runtime.getRuntime().gc();
1431                        // We delete after a gc for applications  on sdcard.
1432                        if (deleteOld) {
1433                            synchronized (mInstallLock) {
1434                                res.removedInfo.args.doPostDeleteLI(true);
1435                            }
1436                        }
1437                        if (args.observer != null) {
1438                            try {
1439                                Bundle extras = extrasForInstallResult(res);
1440                                args.observer.onPackageInstalled(res.name, res.returnCode,
1441                                        res.returnMsg, extras);
1442                            } catch (RemoteException e) {
1443                                Slog.i(TAG, "Observer no longer exists.");
1444                            }
1445                        }
1446                    } else {
1447                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1448                    }
1449                } break;
1450                case UPDATED_MEDIA_STATUS: {
1451                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1452                    boolean reportStatus = msg.arg1 == 1;
1453                    boolean doGc = msg.arg2 == 1;
1454                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1455                    if (doGc) {
1456                        // Force a gc to clear up stale containers.
1457                        Runtime.getRuntime().gc();
1458                    }
1459                    if (msg.obj != null) {
1460                        @SuppressWarnings("unchecked")
1461                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1462                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1463                        // Unload containers
1464                        unloadAllContainers(args);
1465                    }
1466                    if (reportStatus) {
1467                        try {
1468                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1469                            PackageHelper.getMountService().finishMediaUpdate();
1470                        } catch (RemoteException e) {
1471                            Log.e(TAG, "MountService not running?");
1472                        }
1473                    }
1474                } break;
1475                case WRITE_SETTINGS: {
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1477                    synchronized (mPackages) {
1478                        removeMessages(WRITE_SETTINGS);
1479                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1480                        mSettings.writeLPr();
1481                        mDirtyUsers.clear();
1482                    }
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1484                } break;
1485                case WRITE_PACKAGE_RESTRICTIONS: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    synchronized (mPackages) {
1488                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1489                        for (int userId : mDirtyUsers) {
1490                            mSettings.writePackageRestrictionsLPr(userId);
1491                        }
1492                        mDirtyUsers.clear();
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                } break;
1496                case CHECK_PENDING_VERIFICATION: {
1497                    final int verificationId = msg.arg1;
1498                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1499
1500                    if ((state != null) && !state.timeoutExtended()) {
1501                        final InstallArgs args = state.getInstallArgs();
1502                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1503
1504                        Slog.i(TAG, "Verification timed out for " + originUri);
1505                        mPendingVerification.remove(verificationId);
1506
1507                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1508
1509                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1510                            Slog.i(TAG, "Continuing with installation of " + originUri);
1511                            state.setVerifierResponse(Binder.getCallingUid(),
1512                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    PackageManager.VERIFICATION_ALLOW,
1515                                    state.getInstallArgs().getUser());
1516                            try {
1517                                ret = args.copyApk(mContainerService, true);
1518                            } catch (RemoteException e) {
1519                                Slog.e(TAG, "Could not contact the ContainerService");
1520                            }
1521                        } else {
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_REJECT,
1524                                    state.getInstallArgs().getUser());
1525                        }
1526
1527                        processPendingInstall(args, ret);
1528                        mHandler.sendEmptyMessage(MCS_UNBIND);
1529                    }
1530                    break;
1531                }
1532                case PACKAGE_VERIFIED: {
1533                    final int verificationId = msg.arg1;
1534
1535                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1536                    if (state == null) {
1537                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1538                        break;
1539                    }
1540
1541                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1542
1543                    state.setVerifierResponse(response.callerUid, response.code);
1544
1545                    if (state.isVerificationComplete()) {
1546                        mPendingVerification.remove(verificationId);
1547
1548                        final InstallArgs args = state.getInstallArgs();
1549                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1550
1551                        int ret;
1552                        if (state.isInstallAllowed()) {
1553                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1554                            broadcastPackageVerified(verificationId, originUri,
1555                                    response.code, state.getInstallArgs().getUser());
1556                            try {
1557                                ret = args.copyApk(mContainerService, true);
1558                            } catch (RemoteException e) {
1559                                Slog.e(TAG, "Could not contact the ContainerService");
1560                            }
1561                        } else {
1562                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1563                        }
1564
1565                        processPendingInstall(args, ret);
1566
1567                        mHandler.sendEmptyMessage(MCS_UNBIND);
1568                    }
1569
1570                    break;
1571                }
1572                case START_INTENT_FILTER_VERIFICATIONS: {
1573                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1574                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1575                            params.replacing, params.pkg);
1576                    break;
1577                }
1578                case INTENT_FILTER_VERIFIED: {
1579                    final int verificationId = msg.arg1;
1580
1581                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1582                            verificationId);
1583                    if (state == null) {
1584                        Slog.w(TAG, "Invalid IntentFilter verification token "
1585                                + verificationId + " received");
1586                        break;
1587                    }
1588
1589                    final int userId = state.getUserId();
1590
1591                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1592                            "Processing IntentFilter verification with token:"
1593                            + verificationId + " and userId:" + userId);
1594
1595                    final IntentFilterVerificationResponse response =
1596                            (IntentFilterVerificationResponse) msg.obj;
1597
1598                    state.setVerifierResponse(response.callerUid, response.code);
1599
1600                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1601                            "IntentFilter verification with token:" + verificationId
1602                            + " and userId:" + userId
1603                            + " is settings verifier response with response code:"
1604                            + response.code);
1605
1606                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1607                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1608                                + response.getFailedDomainsString());
1609                    }
1610
1611                    if (state.isVerificationComplete()) {
1612                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1613                    } else {
1614                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                                "IntentFilter verification with token:" + verificationId
1616                                + " was not said to be complete");
1617                    }
1618
1619                    break;
1620                }
1621            }
1622        }
1623    }
1624
1625    private StorageEventListener mStorageListener = new StorageEventListener() {
1626        @Override
1627        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1628            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1629                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1630                    final String volumeUuid = vol.getFsUuid();
1631
1632                    // Clean up any users or apps that were removed or recreated
1633                    // while this volume was missing
1634                    reconcileUsers(volumeUuid);
1635                    reconcileApps(volumeUuid);
1636
1637                    // Clean up any install sessions that expired or were
1638                    // cancelled while this volume was missing
1639                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1640
1641                    loadPrivatePackages(vol);
1642
1643                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1644                    unloadPrivatePackages(vol);
1645                }
1646            }
1647
1648            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1649                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1650                    updateExternalMediaStatus(true, false);
1651                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1652                    updateExternalMediaStatus(false, false);
1653                }
1654            }
1655        }
1656
1657        @Override
1658        public void onVolumeForgotten(String fsUuid) {
1659            // Remove any apps installed on the forgotten volume
1660            synchronized (mPackages) {
1661                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1662                for (PackageSetting ps : packages) {
1663                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1664                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1665                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1666                }
1667
1668                mSettings.writeLPr();
1669            }
1670        }
1671    };
1672
1673    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1674        if (userId >= UserHandle.USER_OWNER) {
1675            grantRequestedRuntimePermissionsForUser(pkg, userId);
1676        } else if (userId == UserHandle.USER_ALL) {
1677            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1678                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1679            }
1680        }
1681
1682        // We could have touched GID membership, so flush out packages.list
1683        synchronized (mPackages) {
1684            mSettings.writePackageListLPr();
1685        }
1686    }
1687
1688    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1689        SettingBase sb = (SettingBase) pkg.mExtras;
1690        if (sb == null) {
1691            return;
1692        }
1693
1694        PermissionsState permissionsState = sb.getPermissionsState();
1695
1696        for (String permission : pkg.requestedPermissions) {
1697            BasePermission bp = mSettings.mPermissions.get(permission);
1698            if (bp != null && bp.isRuntime()) {
1699                permissionsState.grantRuntimePermission(bp, userId);
1700            }
1701        }
1702    }
1703
1704    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1705        Bundle extras = null;
1706        switch (res.returnCode) {
1707            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1708                extras = new Bundle();
1709                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1710                        res.origPermission);
1711                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1712                        res.origPackage);
1713                break;
1714            }
1715            case PackageManager.INSTALL_SUCCEEDED: {
1716                extras = new Bundle();
1717                extras.putBoolean(Intent.EXTRA_REPLACING,
1718                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1719                break;
1720            }
1721        }
1722        return extras;
1723    }
1724
1725    void scheduleWriteSettingsLocked() {
1726        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1727            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1728        }
1729    }
1730
1731    void scheduleWritePackageRestrictionsLocked(int userId) {
1732        if (!sUserManager.exists(userId)) return;
1733        mDirtyUsers.add(userId);
1734        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1735            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1736        }
1737    }
1738
1739    public static PackageManagerService main(Context context, Installer installer,
1740            boolean factoryTest, boolean onlyCore) {
1741        PackageManagerService m = new PackageManagerService(context, installer,
1742                factoryTest, onlyCore);
1743        ServiceManager.addService("package", m);
1744        return m;
1745    }
1746
1747    static String[] splitString(String str, char sep) {
1748        int count = 1;
1749        int i = 0;
1750        while ((i=str.indexOf(sep, i)) >= 0) {
1751            count++;
1752            i++;
1753        }
1754
1755        String[] res = new String[count];
1756        i=0;
1757        count = 0;
1758        int lastI=0;
1759        while ((i=str.indexOf(sep, i)) >= 0) {
1760            res[count] = str.substring(lastI, i);
1761            count++;
1762            i++;
1763            lastI = i;
1764        }
1765        res[count] = str.substring(lastI, str.length());
1766        return res;
1767    }
1768
1769    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1770        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1771                Context.DISPLAY_SERVICE);
1772        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1773    }
1774
1775    public PackageManagerService(Context context, Installer installer,
1776            boolean factoryTest, boolean onlyCore) {
1777        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1778                SystemClock.uptimeMillis());
1779
1780        if (mSdkVersion <= 0) {
1781            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1782        }
1783
1784        mContext = context;
1785        mFactoryTest = factoryTest;
1786        mOnlyCore = onlyCore;
1787        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1788        mMetrics = new DisplayMetrics();
1789        mSettings = new Settings(mPackages);
1790        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1791                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1792        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1793                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1794        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1795                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1796        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1797                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1798        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1799                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1800        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1801                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1802
1803        // TODO: add a property to control this?
1804        long dexOptLRUThresholdInMinutes;
1805        if (mLazyDexOpt) {
1806            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1807        } else {
1808            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1809        }
1810        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1811
1812        String separateProcesses = SystemProperties.get("debug.separate_processes");
1813        if (separateProcesses != null && separateProcesses.length() > 0) {
1814            if ("*".equals(separateProcesses)) {
1815                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1816                mSeparateProcesses = null;
1817                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1818            } else {
1819                mDefParseFlags = 0;
1820                mSeparateProcesses = separateProcesses.split(",");
1821                Slog.w(TAG, "Running with debug.separate_processes: "
1822                        + separateProcesses);
1823            }
1824        } else {
1825            mDefParseFlags = 0;
1826            mSeparateProcesses = null;
1827        }
1828
1829        mInstaller = installer;
1830        mPackageDexOptimizer = new PackageDexOptimizer(this);
1831        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1832
1833        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1834                FgThread.get().getLooper());
1835
1836        getDefaultDisplayMetrics(context, mMetrics);
1837
1838        SystemConfig systemConfig = SystemConfig.getInstance();
1839        mGlobalGids = systemConfig.getGlobalGids();
1840        mSystemPermissions = systemConfig.getSystemPermissions();
1841        mAvailableFeatures = systemConfig.getAvailableFeatures();
1842
1843        synchronized (mInstallLock) {
1844        // writer
1845        synchronized (mPackages) {
1846            mHandlerThread = new ServiceThread(TAG,
1847                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1848            mHandlerThread.start();
1849            mHandler = new PackageHandler(mHandlerThread.getLooper());
1850            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1851
1852            File dataDir = Environment.getDataDirectory();
1853            mAppDataDir = new File(dataDir, "data");
1854            mAppInstallDir = new File(dataDir, "app");
1855            mAppLib32InstallDir = new File(dataDir, "app-lib");
1856            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1857            mUserAppDataDir = new File(dataDir, "user");
1858            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1859
1860            sUserManager = new UserManagerService(context, this,
1861                    mInstallLock, mPackages);
1862
1863            // Propagate permission configuration in to package manager.
1864            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1865                    = systemConfig.getPermissions();
1866            for (int i=0; i<permConfig.size(); i++) {
1867                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1868                BasePermission bp = mSettings.mPermissions.get(perm.name);
1869                if (bp == null) {
1870                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1871                    mSettings.mPermissions.put(perm.name, bp);
1872                }
1873                if (perm.gids != null) {
1874                    bp.setGids(perm.gids, perm.perUser);
1875                }
1876            }
1877
1878            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1879            for (int i=0; i<libConfig.size(); i++) {
1880                mSharedLibraries.put(libConfig.keyAt(i),
1881                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1882            }
1883
1884            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1885
1886            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1887                    mSdkVersion, mOnlyCore);
1888
1889            String customResolverActivity = Resources.getSystem().getString(
1890                    R.string.config_customResolverActivity);
1891            if (TextUtils.isEmpty(customResolverActivity)) {
1892                customResolverActivity = null;
1893            } else {
1894                mCustomResolverComponentName = ComponentName.unflattenFromString(
1895                        customResolverActivity);
1896            }
1897
1898            long startTime = SystemClock.uptimeMillis();
1899
1900            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1901                    startTime);
1902
1903            // Set flag to monitor and not change apk file paths when
1904            // scanning install directories.
1905            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1906
1907            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1908
1909            /**
1910             * Add everything in the in the boot class path to the
1911             * list of process files because dexopt will have been run
1912             * if necessary during zygote startup.
1913             */
1914            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1915            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1916
1917            if (bootClassPath != null) {
1918                String[] bootClassPathElements = splitString(bootClassPath, ':');
1919                for (String element : bootClassPathElements) {
1920                    alreadyDexOpted.add(element);
1921                }
1922            } else {
1923                Slog.w(TAG, "No BOOTCLASSPATH found!");
1924            }
1925
1926            if (systemServerClassPath != null) {
1927                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1928                for (String element : systemServerClassPathElements) {
1929                    alreadyDexOpted.add(element);
1930                }
1931            } else {
1932                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1933            }
1934
1935            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1936            final String[] dexCodeInstructionSets =
1937                    getDexCodeInstructionSets(
1938                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1939
1940            /**
1941             * Ensure all external libraries have had dexopt run on them.
1942             */
1943            if (mSharedLibraries.size() > 0) {
1944                // NOTE: For now, we're compiling these system "shared libraries"
1945                // (and framework jars) into all available architectures. It's possible
1946                // to compile them only when we come across an app that uses them (there's
1947                // already logic for that in scanPackageLI) but that adds some complexity.
1948                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1949                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1950                        final String lib = libEntry.path;
1951                        if (lib == null) {
1952                            continue;
1953                        }
1954
1955                        try {
1956                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1957                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1958                                alreadyDexOpted.add(lib);
1959                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1960                            }
1961                        } catch (FileNotFoundException e) {
1962                            Slog.w(TAG, "Library not found: " + lib);
1963                        } catch (IOException e) {
1964                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1965                                    + e.getMessage());
1966                        }
1967                    }
1968                }
1969            }
1970
1971            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1972
1973            // Gross hack for now: we know this file doesn't contain any
1974            // code, so don't dexopt it to avoid the resulting log spew.
1975            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1976
1977            // Gross hack for now: we know this file is only part of
1978            // the boot class path for art, so don't dexopt it to
1979            // avoid the resulting log spew.
1980            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1981
1982            /**
1983             * There are a number of commands implemented in Java, which
1984             * we currently need to do the dexopt on so that they can be
1985             * run from a non-root shell.
1986             */
1987            String[] frameworkFiles = frameworkDir.list();
1988            if (frameworkFiles != null) {
1989                // TODO: We could compile these only for the most preferred ABI. We should
1990                // first double check that the dex files for these commands are not referenced
1991                // by other system apps.
1992                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1993                    for (int i=0; i<frameworkFiles.length; i++) {
1994                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1995                        String path = libPath.getPath();
1996                        // Skip the file if we already did it.
1997                        if (alreadyDexOpted.contains(path)) {
1998                            continue;
1999                        }
2000                        // Skip the file if it is not a type we want to dexopt.
2001                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2002                            continue;
2003                        }
2004                        try {
2005                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2006                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2007                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2008                            }
2009                        } catch (FileNotFoundException e) {
2010                            Slog.w(TAG, "Jar not found: " + path);
2011                        } catch (IOException e) {
2012                            Slog.w(TAG, "Exception reading jar: " + path, e);
2013                        }
2014                    }
2015                }
2016            }
2017
2018            // Collect vendor overlay packages.
2019            // (Do this before scanning any apps.)
2020            // For security and version matching reason, only consider
2021            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2022            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2023            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2024                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2025
2026            // Find base frameworks (resource packages without code).
2027            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2028                    | PackageParser.PARSE_IS_SYSTEM_DIR
2029                    | PackageParser.PARSE_IS_PRIVILEGED,
2030                    scanFlags | SCAN_NO_DEX, 0);
2031
2032            // Collected privileged system packages.
2033            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2034            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2035                    | PackageParser.PARSE_IS_SYSTEM_DIR
2036                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2037
2038            // Collect ordinary system packages.
2039            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2040            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2041                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2042
2043            // Collect all vendor packages.
2044            File vendorAppDir = new File("/vendor/app");
2045            try {
2046                vendorAppDir = vendorAppDir.getCanonicalFile();
2047            } catch (IOException e) {
2048                // failed to look up canonical path, continue with original one
2049            }
2050            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2051                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2052
2053            // Collect all OEM packages.
2054            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2055            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2056                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2057
2058            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2059            mInstaller.moveFiles();
2060
2061            // Prune any system packages that no longer exist.
2062            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2063            if (!mOnlyCore) {
2064                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2065                while (psit.hasNext()) {
2066                    PackageSetting ps = psit.next();
2067
2068                    /*
2069                     * If this is not a system app, it can't be a
2070                     * disable system app.
2071                     */
2072                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2073                        continue;
2074                    }
2075
2076                    /*
2077                     * If the package is scanned, it's not erased.
2078                     */
2079                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2080                    if (scannedPkg != null) {
2081                        /*
2082                         * If the system app is both scanned and in the
2083                         * disabled packages list, then it must have been
2084                         * added via OTA. Remove it from the currently
2085                         * scanned package so the previously user-installed
2086                         * application can be scanned.
2087                         */
2088                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2089                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2090                                    + ps.name + "; removing system app.  Last known codePath="
2091                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2092                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2093                                    + scannedPkg.mVersionCode);
2094                            removePackageLI(ps, true);
2095                            mExpectingBetter.put(ps.name, ps.codePath);
2096                        }
2097
2098                        continue;
2099                    }
2100
2101                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2102                        psit.remove();
2103                        logCriticalInfo(Log.WARN, "System package " + ps.name
2104                                + " no longer exists; wiping its data");
2105                        removeDataDirsLI(null, ps.name);
2106                    } else {
2107                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2108                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2109                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2110                        }
2111                    }
2112                }
2113            }
2114
2115            //look for any incomplete package installations
2116            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2117            //clean up list
2118            for(int i = 0; i < deletePkgsList.size(); i++) {
2119                //clean up here
2120                cleanupInstallFailedPackage(deletePkgsList.get(i));
2121            }
2122            //delete tmp files
2123            deleteTempPackageFiles();
2124
2125            // Remove any shared userIDs that have no associated packages
2126            mSettings.pruneSharedUsersLPw();
2127
2128            if (!mOnlyCore) {
2129                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2130                        SystemClock.uptimeMillis());
2131                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2132
2133                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2134                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2135
2136                /**
2137                 * Remove disable package settings for any updated system
2138                 * apps that were removed via an OTA. If they're not a
2139                 * previously-updated app, remove them completely.
2140                 * Otherwise, just revoke their system-level permissions.
2141                 */
2142                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2143                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2144                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2145
2146                    String msg;
2147                    if (deletedPkg == null) {
2148                        msg = "Updated system package " + deletedAppName
2149                                + " no longer exists; wiping its data";
2150                        removeDataDirsLI(null, deletedAppName);
2151                    } else {
2152                        msg = "Updated system app + " + deletedAppName
2153                                + " no longer present; removing system privileges for "
2154                                + deletedAppName;
2155
2156                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2157
2158                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2159                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2160                    }
2161                    logCriticalInfo(Log.WARN, msg);
2162                }
2163
2164                /**
2165                 * Make sure all system apps that we expected to appear on
2166                 * the userdata partition actually showed up. If they never
2167                 * appeared, crawl back and revive the system version.
2168                 */
2169                for (int i = 0; i < mExpectingBetter.size(); i++) {
2170                    final String packageName = mExpectingBetter.keyAt(i);
2171                    if (!mPackages.containsKey(packageName)) {
2172                        final File scanFile = mExpectingBetter.valueAt(i);
2173
2174                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2175                                + " but never showed up; reverting to system");
2176
2177                        final int reparseFlags;
2178                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2179                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2180                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2181                                    | PackageParser.PARSE_IS_PRIVILEGED;
2182                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2183                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2184                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2185                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2186                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2187                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2188                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2189                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2190                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2191                        } else {
2192                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2193                            continue;
2194                        }
2195
2196                        mSettings.enableSystemPackageLPw(packageName);
2197
2198                        try {
2199                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2200                        } catch (PackageManagerException e) {
2201                            Slog.e(TAG, "Failed to parse original system package: "
2202                                    + e.getMessage());
2203                        }
2204                    }
2205                }
2206            }
2207            mExpectingBetter.clear();
2208
2209            // Now that we know all of the shared libraries, update all clients to have
2210            // the correct library paths.
2211            updateAllSharedLibrariesLPw();
2212
2213            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2214                // NOTE: We ignore potential failures here during a system scan (like
2215                // the rest of the commands above) because there's precious little we
2216                // can do about it. A settings error is reported, though.
2217                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2218                        false /* force dexopt */, false /* defer dexopt */);
2219            }
2220
2221            // Now that we know all the packages we are keeping,
2222            // read and update their last usage times.
2223            mPackageUsage.readLP();
2224
2225            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2226                    SystemClock.uptimeMillis());
2227            Slog.i(TAG, "Time to scan packages: "
2228                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2229                    + " seconds");
2230
2231            // If the platform SDK has changed since the last time we booted,
2232            // we need to re-grant app permission to catch any new ones that
2233            // appear.  This is really a hack, and means that apps can in some
2234            // cases get permissions that the user didn't initially explicitly
2235            // allow...  it would be nice to have some better way to handle
2236            // this situation.
2237            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2238                    != mSdkVersion;
2239            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2240                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2241                    + "; regranting permissions for internal storage");
2242            mSettings.mInternalSdkPlatform = mSdkVersion;
2243
2244            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2245                    | (regrantPermissions
2246                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2247                            : 0));
2248
2249            // If this is the first boot, and it is a normal boot, then
2250            // we need to initialize the default preferred apps.
2251            if (!mRestoredSettings && !onlyCore) {
2252                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2253                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2254                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2255            }
2256
2257            // If this is first boot after an OTA, and a normal boot, then
2258            // we need to clear code cache directories.
2259            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2260            if (mIsUpgrade && !onlyCore) {
2261                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2262                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2263                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2264                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2265                }
2266                mSettings.mFingerprint = Build.FINGERPRINT;
2267            }
2268
2269            checkDefaultBrowser();
2270
2271            // All the changes are done during package scanning.
2272            mSettings.updateInternalDatabaseVersion();
2273
2274            // can downgrade to reader
2275            mSettings.writeLPr();
2276
2277            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2278                    SystemClock.uptimeMillis());
2279
2280            mRequiredVerifierPackage = getRequiredVerifierLPr();
2281            mRequiredInstallerPackage = getRequiredInstallerLPr();
2282
2283            mInstallerService = new PackageInstallerService(context, this);
2284
2285            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2286            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2287                    mIntentFilterVerifierComponent);
2288
2289        } // synchronized (mPackages)
2290        } // synchronized (mInstallLock)
2291
2292        // Now after opening every single application zip, make sure they
2293        // are all flushed.  Not really needed, but keeps things nice and
2294        // tidy.
2295        Runtime.getRuntime().gc();
2296
2297        // Expose private service for system components to use.
2298        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2299    }
2300
2301    @Override
2302    public boolean isFirstBoot() {
2303        return !mRestoredSettings;
2304    }
2305
2306    @Override
2307    public boolean isOnlyCoreApps() {
2308        return mOnlyCore;
2309    }
2310
2311    @Override
2312    public boolean isUpgrade() {
2313        return mIsUpgrade;
2314    }
2315
2316    private String getRequiredVerifierLPr() {
2317        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2318        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2319                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2320
2321        String requiredVerifier = null;
2322
2323        final int N = receivers.size();
2324        for (int i = 0; i < N; i++) {
2325            final ResolveInfo info = receivers.get(i);
2326
2327            if (info.activityInfo == null) {
2328                continue;
2329            }
2330
2331            final String packageName = info.activityInfo.packageName;
2332
2333            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2334                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2335                continue;
2336            }
2337
2338            if (requiredVerifier != null) {
2339                throw new RuntimeException("There can be only one required verifier");
2340            }
2341
2342            requiredVerifier = packageName;
2343        }
2344
2345        return requiredVerifier;
2346    }
2347
2348    private String getRequiredInstallerLPr() {
2349        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2350        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2351        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2352
2353        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2354                PACKAGE_MIME_TYPE, 0, 0);
2355
2356        String requiredInstaller = null;
2357
2358        final int N = installers.size();
2359        for (int i = 0; i < N; i++) {
2360            final ResolveInfo info = installers.get(i);
2361            final String packageName = info.activityInfo.packageName;
2362
2363            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2364                continue;
2365            }
2366
2367            if (requiredInstaller != null) {
2368                throw new RuntimeException("There must be one required installer");
2369            }
2370
2371            requiredInstaller = packageName;
2372        }
2373
2374        if (requiredInstaller == null) {
2375            throw new RuntimeException("There must be one required installer");
2376        }
2377
2378        return requiredInstaller;
2379    }
2380
2381    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2382        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2383        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2384                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2385
2386        ComponentName verifierComponentName = null;
2387
2388        int priority = -1000;
2389        final int N = receivers.size();
2390        for (int i = 0; i < N; i++) {
2391            final ResolveInfo info = receivers.get(i);
2392
2393            if (info.activityInfo == null) {
2394                continue;
2395            }
2396
2397            final String packageName = info.activityInfo.packageName;
2398
2399            final PackageSetting ps = mSettings.mPackages.get(packageName);
2400            if (ps == null) {
2401                continue;
2402            }
2403
2404            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2405                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2406                continue;
2407            }
2408
2409            // Select the IntentFilterVerifier with the highest priority
2410            if (priority < info.priority) {
2411                priority = info.priority;
2412                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2413                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2414                        + verifierComponentName + " with priority: " + info.priority);
2415            }
2416        }
2417
2418        return verifierComponentName;
2419    }
2420
2421    private void primeDomainVerificationsLPw(int userId) {
2422        if (DEBUG_DOMAIN_VERIFICATION) {
2423            Slog.d(TAG, "Priming domain verifications in user " + userId);
2424        }
2425
2426        SystemConfig systemConfig = SystemConfig.getInstance();
2427        ArraySet<String> packages = systemConfig.getLinkedApps();
2428        ArraySet<String> domains = new ArraySet<String>();
2429
2430        for (String packageName : packages) {
2431            PackageParser.Package pkg = mPackages.get(packageName);
2432            if (pkg != null) {
2433                if (!pkg.isSystemApp()) {
2434                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2435                    continue;
2436                }
2437
2438                domains.clear();
2439                for (PackageParser.Activity a : pkg.activities) {
2440                    for (ActivityIntentInfo filter : a.intents) {
2441                        if (hasValidDomains(filter)) {
2442                            domains.addAll(filter.getHostsList());
2443                        }
2444                    }
2445                }
2446
2447                if (domains.size() > 0) {
2448                    if (DEBUG_DOMAIN_VERIFICATION) {
2449                        Slog.v(TAG, "      + " + packageName);
2450                    }
2451                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2452                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2453                    // and then 'always' in the per-user state actually used for intent resolution.
2454                    final IntentFilterVerificationInfo ivi;
2455                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2456                            new ArrayList<String>(domains));
2457                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2458                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2459                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2460                } else {
2461                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2462                            + "' does not handle web links");
2463                }
2464            } else {
2465                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2466            }
2467        }
2468
2469        scheduleWritePackageRestrictionsLocked(userId);
2470        scheduleWriteSettingsLocked();
2471    }
2472
2473    private void applyFactoryDefaultBrowserLPw(int userId) {
2474        // The default browser app's package name is stored in a string resource,
2475        // with a product-specific overlay used for vendor customization.
2476        String browserPkg = mContext.getResources().getString(
2477                com.android.internal.R.string.default_browser);
2478        if (!TextUtils.isEmpty(browserPkg)) {
2479            // non-empty string => required to be a known package
2480            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2481            if (ps == null) {
2482                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2483                browserPkg = null;
2484            } else {
2485                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2486            }
2487        }
2488
2489        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2490        // default.  If there's more than one, just leave everything alone.
2491        if (browserPkg == null) {
2492            calculateDefaultBrowserLPw(userId);
2493        }
2494    }
2495
2496    private void calculateDefaultBrowserLPw(int userId) {
2497        List<String> allBrowsers = resolveAllBrowserApps(userId);
2498        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2499        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2500    }
2501
2502    private List<String> resolveAllBrowserApps(int userId) {
2503        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2504        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2505                PackageManager.MATCH_ALL, userId);
2506
2507        final int count = list.size();
2508        List<String> result = new ArrayList<String>(count);
2509        for (int i=0; i<count; i++) {
2510            ResolveInfo info = list.get(i);
2511            if (info.activityInfo == null
2512                    || !info.handleAllWebDataURI
2513                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2514                    || result.contains(info.activityInfo.packageName)) {
2515                continue;
2516            }
2517            result.add(info.activityInfo.packageName);
2518        }
2519
2520        return result;
2521    }
2522
2523    private boolean packageIsBrowser(String packageName, int userId) {
2524        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2525                PackageManager.MATCH_ALL, userId);
2526        final int N = list.size();
2527        for (int i = 0; i < N; i++) {
2528            ResolveInfo info = list.get(i);
2529            if (packageName.equals(info.activityInfo.packageName)) {
2530                return true;
2531            }
2532        }
2533        return false;
2534    }
2535
2536    private void checkDefaultBrowser() {
2537        final int myUserId = UserHandle.myUserId();
2538        final String packageName = getDefaultBrowserPackageName(myUserId);
2539        if (packageName != null) {
2540            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2541            if (info == null) {
2542                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2543                synchronized (mPackages) {
2544                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2545                }
2546            }
2547        }
2548    }
2549
2550    @Override
2551    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2552            throws RemoteException {
2553        try {
2554            return super.onTransact(code, data, reply, flags);
2555        } catch (RuntimeException e) {
2556            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2557                Slog.wtf(TAG, "Package Manager Crash", e);
2558            }
2559            throw e;
2560        }
2561    }
2562
2563    void cleanupInstallFailedPackage(PackageSetting ps) {
2564        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2565
2566        removeDataDirsLI(ps.volumeUuid, ps.name);
2567        if (ps.codePath != null) {
2568            if (ps.codePath.isDirectory()) {
2569                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2570            } else {
2571                ps.codePath.delete();
2572            }
2573        }
2574        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2575            if (ps.resourcePath.isDirectory()) {
2576                FileUtils.deleteContents(ps.resourcePath);
2577            }
2578            ps.resourcePath.delete();
2579        }
2580        mSettings.removePackageLPw(ps.name);
2581    }
2582
2583    static int[] appendInts(int[] cur, int[] add) {
2584        if (add == null) return cur;
2585        if (cur == null) return add;
2586        final int N = add.length;
2587        for (int i=0; i<N; i++) {
2588            cur = appendInt(cur, add[i]);
2589        }
2590        return cur;
2591    }
2592
2593    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2594        if (!sUserManager.exists(userId)) return null;
2595        final PackageSetting ps = (PackageSetting) p.mExtras;
2596        if (ps == null) {
2597            return null;
2598        }
2599
2600        final PermissionsState permissionsState = ps.getPermissionsState();
2601
2602        final int[] gids = permissionsState.computeGids(userId);
2603        final Set<String> permissions = permissionsState.getPermissions(userId);
2604        final PackageUserState state = ps.readUserState(userId);
2605
2606        return PackageParser.generatePackageInfo(p, gids, flags,
2607                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2608    }
2609
2610    @Override
2611    public boolean isPackageFrozen(String packageName) {
2612        synchronized (mPackages) {
2613            final PackageSetting ps = mSettings.mPackages.get(packageName);
2614            if (ps != null) {
2615                return ps.frozen;
2616            }
2617        }
2618        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2619        return true;
2620    }
2621
2622    @Override
2623    public boolean isPackageAvailable(String packageName, int userId) {
2624        if (!sUserManager.exists(userId)) return false;
2625        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2626        synchronized (mPackages) {
2627            PackageParser.Package p = mPackages.get(packageName);
2628            if (p != null) {
2629                final PackageSetting ps = (PackageSetting) p.mExtras;
2630                if (ps != null) {
2631                    final PackageUserState state = ps.readUserState(userId);
2632                    if (state != null) {
2633                        return PackageParser.isAvailable(state);
2634                    }
2635                }
2636            }
2637        }
2638        return false;
2639    }
2640
2641    @Override
2642    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2643        if (!sUserManager.exists(userId)) return null;
2644        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2645        // reader
2646        synchronized (mPackages) {
2647            PackageParser.Package p = mPackages.get(packageName);
2648            if (DEBUG_PACKAGE_INFO)
2649                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2650            if (p != null) {
2651                return generatePackageInfo(p, flags, userId);
2652            }
2653            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2654                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2655            }
2656        }
2657        return null;
2658    }
2659
2660    @Override
2661    public String[] currentToCanonicalPackageNames(String[] names) {
2662        String[] out = new String[names.length];
2663        // reader
2664        synchronized (mPackages) {
2665            for (int i=names.length-1; i>=0; i--) {
2666                PackageSetting ps = mSettings.mPackages.get(names[i]);
2667                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2668            }
2669        }
2670        return out;
2671    }
2672
2673    @Override
2674    public String[] canonicalToCurrentPackageNames(String[] names) {
2675        String[] out = new String[names.length];
2676        // reader
2677        synchronized (mPackages) {
2678            for (int i=names.length-1; i>=0; i--) {
2679                String cur = mSettings.mRenamedPackages.get(names[i]);
2680                out[i] = cur != null ? cur : names[i];
2681            }
2682        }
2683        return out;
2684    }
2685
2686    @Override
2687    public int getPackageUid(String packageName, int userId) {
2688        if (!sUserManager.exists(userId)) return -1;
2689        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2690
2691        // reader
2692        synchronized (mPackages) {
2693            PackageParser.Package p = mPackages.get(packageName);
2694            if(p != null) {
2695                return UserHandle.getUid(userId, p.applicationInfo.uid);
2696            }
2697            PackageSetting ps = mSettings.mPackages.get(packageName);
2698            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2699                return -1;
2700            }
2701            p = ps.pkg;
2702            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2703        }
2704    }
2705
2706    @Override
2707    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2708        if (!sUserManager.exists(userId)) {
2709            return null;
2710        }
2711
2712        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2713                "getPackageGids");
2714
2715        // reader
2716        synchronized (mPackages) {
2717            PackageParser.Package p = mPackages.get(packageName);
2718            if (DEBUG_PACKAGE_INFO) {
2719                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2720            }
2721            if (p != null) {
2722                PackageSetting ps = (PackageSetting) p.mExtras;
2723                return ps.getPermissionsState().computeGids(userId);
2724            }
2725        }
2726
2727        return null;
2728    }
2729
2730    @Override
2731    public int getMountExternalMode(int uid) {
2732        if (Process.isIsolated(uid)) {
2733            return Zygote.MOUNT_EXTERNAL_NONE;
2734        } else {
2735            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2736                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2737            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2738                return Zygote.MOUNT_EXTERNAL_WRITE;
2739            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2740                return Zygote.MOUNT_EXTERNAL_READ;
2741            } else {
2742                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2743            }
2744        }
2745    }
2746
2747    static PermissionInfo generatePermissionInfo(
2748            BasePermission bp, int flags) {
2749        if (bp.perm != null) {
2750            return PackageParser.generatePermissionInfo(bp.perm, flags);
2751        }
2752        PermissionInfo pi = new PermissionInfo();
2753        pi.name = bp.name;
2754        pi.packageName = bp.sourcePackage;
2755        pi.nonLocalizedLabel = bp.name;
2756        pi.protectionLevel = bp.protectionLevel;
2757        return pi;
2758    }
2759
2760    @Override
2761    public PermissionInfo getPermissionInfo(String name, int flags) {
2762        // reader
2763        synchronized (mPackages) {
2764            final BasePermission p = mSettings.mPermissions.get(name);
2765            if (p != null) {
2766                return generatePermissionInfo(p, flags);
2767            }
2768            return null;
2769        }
2770    }
2771
2772    @Override
2773    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2774        // reader
2775        synchronized (mPackages) {
2776            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2777            for (BasePermission p : mSettings.mPermissions.values()) {
2778                if (group == null) {
2779                    if (p.perm == null || p.perm.info.group == null) {
2780                        out.add(generatePermissionInfo(p, flags));
2781                    }
2782                } else {
2783                    if (p.perm != null && group.equals(p.perm.info.group)) {
2784                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2785                    }
2786                }
2787            }
2788
2789            if (out.size() > 0) {
2790                return out;
2791            }
2792            return mPermissionGroups.containsKey(group) ? out : null;
2793        }
2794    }
2795
2796    @Override
2797    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2798        // reader
2799        synchronized (mPackages) {
2800            return PackageParser.generatePermissionGroupInfo(
2801                    mPermissionGroups.get(name), flags);
2802        }
2803    }
2804
2805    @Override
2806    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2807        // reader
2808        synchronized (mPackages) {
2809            final int N = mPermissionGroups.size();
2810            ArrayList<PermissionGroupInfo> out
2811                    = new ArrayList<PermissionGroupInfo>(N);
2812            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2813                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2814            }
2815            return out;
2816        }
2817    }
2818
2819    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2820            int userId) {
2821        if (!sUserManager.exists(userId)) return null;
2822        PackageSetting ps = mSettings.mPackages.get(packageName);
2823        if (ps != null) {
2824            if (ps.pkg == null) {
2825                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2826                        flags, userId);
2827                if (pInfo != null) {
2828                    return pInfo.applicationInfo;
2829                }
2830                return null;
2831            }
2832            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2833                    ps.readUserState(userId), userId);
2834        }
2835        return null;
2836    }
2837
2838    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2839            int userId) {
2840        if (!sUserManager.exists(userId)) return null;
2841        PackageSetting ps = mSettings.mPackages.get(packageName);
2842        if (ps != null) {
2843            PackageParser.Package pkg = ps.pkg;
2844            if (pkg == null) {
2845                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2846                    return null;
2847                }
2848                // Only data remains, so we aren't worried about code paths
2849                pkg = new PackageParser.Package(packageName);
2850                pkg.applicationInfo.packageName = packageName;
2851                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2852                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2853                pkg.applicationInfo.dataDir = Environment
2854                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2855                        .getAbsolutePath();
2856                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2857                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2858            }
2859            return generatePackageInfo(pkg, flags, userId);
2860        }
2861        return null;
2862    }
2863
2864    @Override
2865    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2866        if (!sUserManager.exists(userId)) return null;
2867        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2868        // writer
2869        synchronized (mPackages) {
2870            PackageParser.Package p = mPackages.get(packageName);
2871            if (DEBUG_PACKAGE_INFO) Log.v(
2872                    TAG, "getApplicationInfo " + packageName
2873                    + ": " + p);
2874            if (p != null) {
2875                PackageSetting ps = mSettings.mPackages.get(packageName);
2876                if (ps == null) return null;
2877                // Note: isEnabledLP() does not apply here - always return info
2878                return PackageParser.generateApplicationInfo(
2879                        p, flags, ps.readUserState(userId), userId);
2880            }
2881            if ("android".equals(packageName)||"system".equals(packageName)) {
2882                return mAndroidApplication;
2883            }
2884            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2885                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2886            }
2887        }
2888        return null;
2889    }
2890
2891    @Override
2892    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2893            final IPackageDataObserver observer) {
2894        mContext.enforceCallingOrSelfPermission(
2895                android.Manifest.permission.CLEAR_APP_CACHE, null);
2896        // Queue up an async operation since clearing cache may take a little while.
2897        mHandler.post(new Runnable() {
2898            public void run() {
2899                mHandler.removeCallbacks(this);
2900                int retCode = -1;
2901                synchronized (mInstallLock) {
2902                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2903                    if (retCode < 0) {
2904                        Slog.w(TAG, "Couldn't clear application caches");
2905                    }
2906                }
2907                if (observer != null) {
2908                    try {
2909                        observer.onRemoveCompleted(null, (retCode >= 0));
2910                    } catch (RemoteException e) {
2911                        Slog.w(TAG, "RemoveException when invoking call back");
2912                    }
2913                }
2914            }
2915        });
2916    }
2917
2918    @Override
2919    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2920            final IntentSender pi) {
2921        mContext.enforceCallingOrSelfPermission(
2922                android.Manifest.permission.CLEAR_APP_CACHE, null);
2923        // Queue up an async operation since clearing cache may take a little while.
2924        mHandler.post(new Runnable() {
2925            public void run() {
2926                mHandler.removeCallbacks(this);
2927                int retCode = -1;
2928                synchronized (mInstallLock) {
2929                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2930                    if (retCode < 0) {
2931                        Slog.w(TAG, "Couldn't clear application caches");
2932                    }
2933                }
2934                if(pi != null) {
2935                    try {
2936                        // Callback via pending intent
2937                        int code = (retCode >= 0) ? 1 : 0;
2938                        pi.sendIntent(null, code, null,
2939                                null, null);
2940                    } catch (SendIntentException e1) {
2941                        Slog.i(TAG, "Failed to send pending intent");
2942                    }
2943                }
2944            }
2945        });
2946    }
2947
2948    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2949        synchronized (mInstallLock) {
2950            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2951                throw new IOException("Failed to free enough space");
2952            }
2953        }
2954    }
2955
2956    @Override
2957    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2958        if (!sUserManager.exists(userId)) return null;
2959        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2960        synchronized (mPackages) {
2961            PackageParser.Activity a = mActivities.mActivities.get(component);
2962
2963            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2964            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2965                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2966                if (ps == null) return null;
2967                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2968                        userId);
2969            }
2970            if (mResolveComponentName.equals(component)) {
2971                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2972                        new PackageUserState(), userId);
2973            }
2974        }
2975        return null;
2976    }
2977
2978    @Override
2979    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2980            String resolvedType) {
2981        synchronized (mPackages) {
2982            PackageParser.Activity a = mActivities.mActivities.get(component);
2983            if (a == null) {
2984                return false;
2985            }
2986            for (int i=0; i<a.intents.size(); i++) {
2987                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2988                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2989                    return true;
2990                }
2991            }
2992            return false;
2993        }
2994    }
2995
2996    @Override
2997    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2998        if (!sUserManager.exists(userId)) return null;
2999        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3000        synchronized (mPackages) {
3001            PackageParser.Activity a = mReceivers.mActivities.get(component);
3002            if (DEBUG_PACKAGE_INFO) Log.v(
3003                TAG, "getReceiverInfo " + component + ": " + a);
3004            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3005                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3006                if (ps == null) return null;
3007                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3008                        userId);
3009            }
3010        }
3011        return null;
3012    }
3013
3014    @Override
3015    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3016        if (!sUserManager.exists(userId)) return null;
3017        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3018        synchronized (mPackages) {
3019            PackageParser.Service s = mServices.mServices.get(component);
3020            if (DEBUG_PACKAGE_INFO) Log.v(
3021                TAG, "getServiceInfo " + component + ": " + s);
3022            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3023                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3024                if (ps == null) return null;
3025                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3026                        userId);
3027            }
3028        }
3029        return null;
3030    }
3031
3032    @Override
3033    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3034        if (!sUserManager.exists(userId)) return null;
3035        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3036        synchronized (mPackages) {
3037            PackageParser.Provider p = mProviders.mProviders.get(component);
3038            if (DEBUG_PACKAGE_INFO) Log.v(
3039                TAG, "getProviderInfo " + component + ": " + p);
3040            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3041                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3042                if (ps == null) return null;
3043                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3044                        userId);
3045            }
3046        }
3047        return null;
3048    }
3049
3050    @Override
3051    public String[] getSystemSharedLibraryNames() {
3052        Set<String> libSet;
3053        synchronized (mPackages) {
3054            libSet = mSharedLibraries.keySet();
3055            int size = libSet.size();
3056            if (size > 0) {
3057                String[] libs = new String[size];
3058                libSet.toArray(libs);
3059                return libs;
3060            }
3061        }
3062        return null;
3063    }
3064
3065    /**
3066     * @hide
3067     */
3068    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3069        synchronized (mPackages) {
3070            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3071            if (lib != null && lib.apk != null) {
3072                return mPackages.get(lib.apk);
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public FeatureInfo[] getSystemAvailableFeatures() {
3080        Collection<FeatureInfo> featSet;
3081        synchronized (mPackages) {
3082            featSet = mAvailableFeatures.values();
3083            int size = featSet.size();
3084            if (size > 0) {
3085                FeatureInfo[] features = new FeatureInfo[size+1];
3086                featSet.toArray(features);
3087                FeatureInfo fi = new FeatureInfo();
3088                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3089                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3090                features[size] = fi;
3091                return features;
3092            }
3093        }
3094        return null;
3095    }
3096
3097    @Override
3098    public boolean hasSystemFeature(String name) {
3099        synchronized (mPackages) {
3100            return mAvailableFeatures.containsKey(name);
3101        }
3102    }
3103
3104    private void checkValidCaller(int uid, int userId) {
3105        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3106            return;
3107
3108        throw new SecurityException("Caller uid=" + uid
3109                + " is not privileged to communicate with user=" + userId);
3110    }
3111
3112    @Override
3113    public int checkPermission(String permName, String pkgName, int userId) {
3114        if (!sUserManager.exists(userId)) {
3115            return PackageManager.PERMISSION_DENIED;
3116        }
3117
3118        synchronized (mPackages) {
3119            final PackageParser.Package p = mPackages.get(pkgName);
3120            if (p != null && p.mExtras != null) {
3121                final PackageSetting ps = (PackageSetting) p.mExtras;
3122                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3123                    return PackageManager.PERMISSION_GRANTED;
3124                }
3125            }
3126        }
3127
3128        return PackageManager.PERMISSION_DENIED;
3129    }
3130
3131    @Override
3132    public int checkUidPermission(String permName, int uid) {
3133        final int userId = UserHandle.getUserId(uid);
3134
3135        if (!sUserManager.exists(userId)) {
3136            return PackageManager.PERMISSION_DENIED;
3137        }
3138
3139        synchronized (mPackages) {
3140            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3141            if (obj != null) {
3142                final SettingBase ps = (SettingBase) obj;
3143                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3144                    return PackageManager.PERMISSION_GRANTED;
3145                }
3146            } else {
3147                ArraySet<String> perms = mSystemPermissions.get(uid);
3148                if (perms != null && perms.contains(permName)) {
3149                    return PackageManager.PERMISSION_GRANTED;
3150                }
3151            }
3152        }
3153
3154        return PackageManager.PERMISSION_DENIED;
3155    }
3156
3157    @Override
3158    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3159        if (UserHandle.getCallingUserId() != userId) {
3160            mContext.enforceCallingPermission(
3161                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3162                    "isPermissionRevokedByPolicy for user " + userId);
3163        }
3164
3165        if (checkPermission(permission, packageName, userId)
3166                == PackageManager.PERMISSION_GRANTED) {
3167            return false;
3168        }
3169
3170        final long identity = Binder.clearCallingIdentity();
3171        try {
3172            final int flags = getPermissionFlags(permission, packageName, userId);
3173            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3174        } finally {
3175            Binder.restoreCallingIdentity(identity);
3176        }
3177    }
3178
3179    /**
3180     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3181     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3182     * @param checkShell TODO(yamasani):
3183     * @param message the message to log on security exception
3184     */
3185    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3186            boolean checkShell, String message) {
3187        if (userId < 0) {
3188            throw new IllegalArgumentException("Invalid userId " + userId);
3189        }
3190        if (checkShell) {
3191            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3192        }
3193        if (userId == UserHandle.getUserId(callingUid)) return;
3194        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3195            if (requireFullPermission) {
3196                mContext.enforceCallingOrSelfPermission(
3197                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3198            } else {
3199                try {
3200                    mContext.enforceCallingOrSelfPermission(
3201                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3202                } catch (SecurityException se) {
3203                    mContext.enforceCallingOrSelfPermission(
3204                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3205                }
3206            }
3207        }
3208    }
3209
3210    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3211        if (callingUid == Process.SHELL_UID) {
3212            if (userHandle >= 0
3213                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3214                throw new SecurityException("Shell does not have permission to access user "
3215                        + userHandle);
3216            } else if (userHandle < 0) {
3217                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3218                        + Debug.getCallers(3));
3219            }
3220        }
3221    }
3222
3223    private BasePermission findPermissionTreeLP(String permName) {
3224        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3225            if (permName.startsWith(bp.name) &&
3226                    permName.length() > bp.name.length() &&
3227                    permName.charAt(bp.name.length()) == '.') {
3228                return bp;
3229            }
3230        }
3231        return null;
3232    }
3233
3234    private BasePermission checkPermissionTreeLP(String permName) {
3235        if (permName != null) {
3236            BasePermission bp = findPermissionTreeLP(permName);
3237            if (bp != null) {
3238                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3239                    return bp;
3240                }
3241                throw new SecurityException("Calling uid "
3242                        + Binder.getCallingUid()
3243                        + " is not allowed to add to permission tree "
3244                        + bp.name + " owned by uid " + bp.uid);
3245            }
3246        }
3247        throw new SecurityException("No permission tree found for " + permName);
3248    }
3249
3250    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3251        if (s1 == null) {
3252            return s2 == null;
3253        }
3254        if (s2 == null) {
3255            return false;
3256        }
3257        if (s1.getClass() != s2.getClass()) {
3258            return false;
3259        }
3260        return s1.equals(s2);
3261    }
3262
3263    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3264        if (pi1.icon != pi2.icon) return false;
3265        if (pi1.logo != pi2.logo) return false;
3266        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3267        if (!compareStrings(pi1.name, pi2.name)) return false;
3268        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3269        // We'll take care of setting this one.
3270        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3271        // These are not currently stored in settings.
3272        //if (!compareStrings(pi1.group, pi2.group)) return false;
3273        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3274        //if (pi1.labelRes != pi2.labelRes) return false;
3275        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3276        return true;
3277    }
3278
3279    int permissionInfoFootprint(PermissionInfo info) {
3280        int size = info.name.length();
3281        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3282        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3283        return size;
3284    }
3285
3286    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3287        int size = 0;
3288        for (BasePermission perm : mSettings.mPermissions.values()) {
3289            if (perm.uid == tree.uid) {
3290                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3291            }
3292        }
3293        return size;
3294    }
3295
3296    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3297        // We calculate the max size of permissions defined by this uid and throw
3298        // if that plus the size of 'info' would exceed our stated maximum.
3299        if (tree.uid != Process.SYSTEM_UID) {
3300            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3301            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3302                throw new SecurityException("Permission tree size cap exceeded");
3303            }
3304        }
3305    }
3306
3307    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3308        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3309            throw new SecurityException("Label must be specified in permission");
3310        }
3311        BasePermission tree = checkPermissionTreeLP(info.name);
3312        BasePermission bp = mSettings.mPermissions.get(info.name);
3313        boolean added = bp == null;
3314        boolean changed = true;
3315        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3316        if (added) {
3317            enforcePermissionCapLocked(info, tree);
3318            bp = new BasePermission(info.name, tree.sourcePackage,
3319                    BasePermission.TYPE_DYNAMIC);
3320        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3321            throw new SecurityException(
3322                    "Not allowed to modify non-dynamic permission "
3323                    + info.name);
3324        } else {
3325            if (bp.protectionLevel == fixedLevel
3326                    && bp.perm.owner.equals(tree.perm.owner)
3327                    && bp.uid == tree.uid
3328                    && comparePermissionInfos(bp.perm.info, info)) {
3329                changed = false;
3330            }
3331        }
3332        bp.protectionLevel = fixedLevel;
3333        info = new PermissionInfo(info);
3334        info.protectionLevel = fixedLevel;
3335        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3336        bp.perm.info.packageName = tree.perm.info.packageName;
3337        bp.uid = tree.uid;
3338        if (added) {
3339            mSettings.mPermissions.put(info.name, bp);
3340        }
3341        if (changed) {
3342            if (!async) {
3343                mSettings.writeLPr();
3344            } else {
3345                scheduleWriteSettingsLocked();
3346            }
3347        }
3348        return added;
3349    }
3350
3351    @Override
3352    public boolean addPermission(PermissionInfo info) {
3353        synchronized (mPackages) {
3354            return addPermissionLocked(info, false);
3355        }
3356    }
3357
3358    @Override
3359    public boolean addPermissionAsync(PermissionInfo info) {
3360        synchronized (mPackages) {
3361            return addPermissionLocked(info, true);
3362        }
3363    }
3364
3365    @Override
3366    public void removePermission(String name) {
3367        synchronized (mPackages) {
3368            checkPermissionTreeLP(name);
3369            BasePermission bp = mSettings.mPermissions.get(name);
3370            if (bp != null) {
3371                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3372                    throw new SecurityException(
3373                            "Not allowed to modify non-dynamic permission "
3374                            + name);
3375                }
3376                mSettings.mPermissions.remove(name);
3377                mSettings.writeLPr();
3378            }
3379        }
3380    }
3381
3382    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3383            BasePermission bp) {
3384        int index = pkg.requestedPermissions.indexOf(bp.name);
3385        if (index == -1) {
3386            throw new SecurityException("Package " + pkg.packageName
3387                    + " has not requested permission " + bp.name);
3388        }
3389        if (!bp.isRuntime()) {
3390            throw new SecurityException("Permission " + bp.name
3391                    + " is not a changeable permission type");
3392        }
3393    }
3394
3395    @Override
3396    public void grantRuntimePermission(String packageName, String name, final int userId) {
3397        if (!sUserManager.exists(userId)) {
3398            Log.e(TAG, "No such user:" + userId);
3399            return;
3400        }
3401
3402        mContext.enforceCallingOrSelfPermission(
3403                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3404                "grantRuntimePermission");
3405
3406        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3407                "grantRuntimePermission");
3408
3409        final int uid;
3410        final SettingBase sb;
3411
3412        synchronized (mPackages) {
3413            final PackageParser.Package pkg = mPackages.get(packageName);
3414            if (pkg == null) {
3415                throw new IllegalArgumentException("Unknown package: " + packageName);
3416            }
3417
3418            final BasePermission bp = mSettings.mPermissions.get(name);
3419            if (bp == null) {
3420                throw new IllegalArgumentException("Unknown permission: " + name);
3421            }
3422
3423            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3424
3425            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3426            sb = (SettingBase) pkg.mExtras;
3427            if (sb == null) {
3428                throw new IllegalArgumentException("Unknown package: " + packageName);
3429            }
3430
3431            final PermissionsState permissionsState = sb.getPermissionsState();
3432
3433            final int flags = permissionsState.getPermissionFlags(name, userId);
3434            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3435                throw new SecurityException("Cannot grant system fixed permission: "
3436                        + name + " for package: " + packageName);
3437            }
3438
3439            final int result = permissionsState.grantRuntimePermission(bp, userId);
3440            switch (result) {
3441                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3442                    return;
3443                }
3444
3445                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3446                    mHandler.post(new Runnable() {
3447                        @Override
3448                        public void run() {
3449                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3450                        }
3451                    });
3452                } break;
3453            }
3454
3455            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3456
3457            // Not critical if that is lost - app has to request again.
3458            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3459        }
3460
3461        // Only need to do this if user is initialized. Otherwise it's a new user
3462        // and there are no processes running as the user yet and there's no need
3463        // to make an expensive call to remount processes for the changed permissions.
3464        if ((READ_EXTERNAL_STORAGE.equals(name)
3465                || WRITE_EXTERNAL_STORAGE.equals(name))
3466                && sUserManager.isInitialized(userId)) {
3467            final long token = Binder.clearCallingIdentity();
3468            try {
3469                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3470                storage.remountUid(uid);
3471            } finally {
3472                Binder.restoreCallingIdentity(token);
3473            }
3474        }
3475    }
3476
3477    @Override
3478    public void revokeRuntimePermission(String packageName, String name, int userId) {
3479        if (!sUserManager.exists(userId)) {
3480            Log.e(TAG, "No such user:" + userId);
3481            return;
3482        }
3483
3484        mContext.enforceCallingOrSelfPermission(
3485                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3486                "revokeRuntimePermission");
3487
3488        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3489                "revokeRuntimePermission");
3490
3491        final SettingBase sb;
3492
3493        synchronized (mPackages) {
3494            final PackageParser.Package pkg = mPackages.get(packageName);
3495            if (pkg == null) {
3496                throw new IllegalArgumentException("Unknown package: " + packageName);
3497            }
3498
3499            final BasePermission bp = mSettings.mPermissions.get(name);
3500            if (bp == null) {
3501                throw new IllegalArgumentException("Unknown permission: " + name);
3502            }
3503
3504            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3505
3506            sb = (SettingBase) pkg.mExtras;
3507            if (sb == null) {
3508                throw new IllegalArgumentException("Unknown package: " + packageName);
3509            }
3510
3511            final PermissionsState permissionsState = sb.getPermissionsState();
3512
3513            final int flags = permissionsState.getPermissionFlags(name, userId);
3514            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3515                throw new SecurityException("Cannot revoke system fixed permission: "
3516                        + name + " for package: " + packageName);
3517            }
3518
3519            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3520                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3521                return;
3522            }
3523
3524            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3525
3526            // Critical, after this call app should never have the permission.
3527            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3528        }
3529
3530        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3531    }
3532
3533    @Override
3534    public void resetRuntimePermissions() {
3535        mContext.enforceCallingOrSelfPermission(
3536                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3537                "revokeRuntimePermission");
3538
3539        int callingUid = Binder.getCallingUid();
3540        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3541            mContext.enforceCallingOrSelfPermission(
3542                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3543                    "resetRuntimePermissions");
3544        }
3545
3546        final int[] userIds;
3547
3548        synchronized (mPackages) {
3549            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3550            final int userCount = UserManagerService.getInstance().getUserIds().length;
3551            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3552        }
3553
3554        for (int userId : userIds) {
3555            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3556        }
3557    }
3558
3559    @Override
3560    public int getPermissionFlags(String name, String packageName, int userId) {
3561        if (!sUserManager.exists(userId)) {
3562            return 0;
3563        }
3564
3565        mContext.enforceCallingOrSelfPermission(
3566                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3567                "getPermissionFlags");
3568
3569        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3570                "getPermissionFlags");
3571
3572        synchronized (mPackages) {
3573            final PackageParser.Package pkg = mPackages.get(packageName);
3574            if (pkg == null) {
3575                throw new IllegalArgumentException("Unknown package: " + packageName);
3576            }
3577
3578            final BasePermission bp = mSettings.mPermissions.get(name);
3579            if (bp == null) {
3580                throw new IllegalArgumentException("Unknown permission: " + name);
3581            }
3582
3583            SettingBase sb = (SettingBase) pkg.mExtras;
3584            if (sb == null) {
3585                throw new IllegalArgumentException("Unknown package: " + packageName);
3586            }
3587
3588            PermissionsState permissionsState = sb.getPermissionsState();
3589            return permissionsState.getPermissionFlags(name, userId);
3590        }
3591    }
3592
3593    @Override
3594    public void updatePermissionFlags(String name, String packageName, int flagMask,
3595            int flagValues, int userId) {
3596        if (!sUserManager.exists(userId)) {
3597            return;
3598        }
3599
3600        mContext.enforceCallingOrSelfPermission(
3601                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3602                "updatePermissionFlags");
3603
3604        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3605                "updatePermissionFlags");
3606
3607        // Only the system can change system fixed flags.
3608        if (getCallingUid() != Process.SYSTEM_UID) {
3609            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3610            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3611        }
3612
3613        synchronized (mPackages) {
3614            final PackageParser.Package pkg = mPackages.get(packageName);
3615            if (pkg == null) {
3616                throw new IllegalArgumentException("Unknown package: " + packageName);
3617            }
3618
3619            final BasePermission bp = mSettings.mPermissions.get(name);
3620            if (bp == null) {
3621                throw new IllegalArgumentException("Unknown permission: " + name);
3622            }
3623
3624            SettingBase sb = (SettingBase) pkg.mExtras;
3625            if (sb == null) {
3626                throw new IllegalArgumentException("Unknown package: " + packageName);
3627            }
3628
3629            PermissionsState permissionsState = sb.getPermissionsState();
3630
3631            // Only the package manager can change flags for system component permissions.
3632            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3633            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3634                return;
3635            }
3636
3637            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3638
3639            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3640                // Install and runtime permissions are stored in different places,
3641                // so figure out what permission changed and persist the change.
3642                if (permissionsState.getInstallPermissionState(name) != null) {
3643                    scheduleWriteSettingsLocked();
3644                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3645                        || hadState) {
3646                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3647                }
3648            }
3649        }
3650    }
3651
3652    /**
3653     * Update the permission flags for all packages and runtime permissions of a user in order
3654     * to allow device or profile owner to remove POLICY_FIXED.
3655     */
3656    @Override
3657    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3658        if (!sUserManager.exists(userId)) {
3659            return;
3660        }
3661
3662        mContext.enforceCallingOrSelfPermission(
3663                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3664                "updatePermissionFlagsForAllApps");
3665
3666        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3667                "updatePermissionFlagsForAllApps");
3668
3669        // Only the system can change system fixed flags.
3670        if (getCallingUid() != Process.SYSTEM_UID) {
3671            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3672            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3673        }
3674
3675        synchronized (mPackages) {
3676            boolean changed = false;
3677            final int packageCount = mPackages.size();
3678            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3679                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3680                SettingBase sb = (SettingBase) pkg.mExtras;
3681                if (sb == null) {
3682                    continue;
3683                }
3684                PermissionsState permissionsState = sb.getPermissionsState();
3685                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3686                        userId, flagMask, flagValues);
3687            }
3688            if (changed) {
3689                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3690            }
3691        }
3692    }
3693
3694    @Override
3695    public boolean shouldShowRequestPermissionRationale(String permissionName,
3696            String packageName, int userId) {
3697        if (UserHandle.getCallingUserId() != userId) {
3698            mContext.enforceCallingPermission(
3699                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3700                    "canShowRequestPermissionRationale for user " + userId);
3701        }
3702
3703        final int uid = getPackageUid(packageName, userId);
3704        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3705            return false;
3706        }
3707
3708        if (checkPermission(permissionName, packageName, userId)
3709                == PackageManager.PERMISSION_GRANTED) {
3710            return false;
3711        }
3712
3713        final int flags;
3714
3715        final long identity = Binder.clearCallingIdentity();
3716        try {
3717            flags = getPermissionFlags(permissionName,
3718                    packageName, userId);
3719        } finally {
3720            Binder.restoreCallingIdentity(identity);
3721        }
3722
3723        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3724                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3725                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3726
3727        if ((flags & fixedFlags) != 0) {
3728            return false;
3729        }
3730
3731        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3732    }
3733
3734    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3735        BasePermission bp = mSettings.mPermissions.get(permission);
3736        if (bp == null) {
3737            throw new SecurityException("Missing " + permission + " permission");
3738        }
3739
3740        SettingBase sb = (SettingBase) pkg.mExtras;
3741        PermissionsState permissionsState = sb.getPermissionsState();
3742
3743        if (permissionsState.grantInstallPermission(bp) !=
3744                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3745            scheduleWriteSettingsLocked();
3746        }
3747    }
3748
3749    @Override
3750    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3751        mContext.enforceCallingOrSelfPermission(
3752                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3753                "addOnPermissionsChangeListener");
3754
3755        synchronized (mPackages) {
3756            mOnPermissionChangeListeners.addListenerLocked(listener);
3757        }
3758    }
3759
3760    @Override
3761    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3762        synchronized (mPackages) {
3763            mOnPermissionChangeListeners.removeListenerLocked(listener);
3764        }
3765    }
3766
3767    @Override
3768    public boolean isProtectedBroadcast(String actionName) {
3769        synchronized (mPackages) {
3770            return mProtectedBroadcasts.contains(actionName);
3771        }
3772    }
3773
3774    @Override
3775    public int checkSignatures(String pkg1, String pkg2) {
3776        synchronized (mPackages) {
3777            final PackageParser.Package p1 = mPackages.get(pkg1);
3778            final PackageParser.Package p2 = mPackages.get(pkg2);
3779            if (p1 == null || p1.mExtras == null
3780                    || p2 == null || p2.mExtras == null) {
3781                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3782            }
3783            return compareSignatures(p1.mSignatures, p2.mSignatures);
3784        }
3785    }
3786
3787    @Override
3788    public int checkUidSignatures(int uid1, int uid2) {
3789        // Map to base uids.
3790        uid1 = UserHandle.getAppId(uid1);
3791        uid2 = UserHandle.getAppId(uid2);
3792        // reader
3793        synchronized (mPackages) {
3794            Signature[] s1;
3795            Signature[] s2;
3796            Object obj = mSettings.getUserIdLPr(uid1);
3797            if (obj != null) {
3798                if (obj instanceof SharedUserSetting) {
3799                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3800                } else if (obj instanceof PackageSetting) {
3801                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3802                } else {
3803                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3804                }
3805            } else {
3806                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3807            }
3808            obj = mSettings.getUserIdLPr(uid2);
3809            if (obj != null) {
3810                if (obj instanceof SharedUserSetting) {
3811                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3812                } else if (obj instanceof PackageSetting) {
3813                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3814                } else {
3815                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3816                }
3817            } else {
3818                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3819            }
3820            return compareSignatures(s1, s2);
3821        }
3822    }
3823
3824    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3825        final long identity = Binder.clearCallingIdentity();
3826        try {
3827            if (sb instanceof SharedUserSetting) {
3828                SharedUserSetting sus = (SharedUserSetting) sb;
3829                final int packageCount = sus.packages.size();
3830                for (int i = 0; i < packageCount; i++) {
3831                    PackageSetting susPs = sus.packages.valueAt(i);
3832                    if (userId == UserHandle.USER_ALL) {
3833                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3834                    } else {
3835                        final int uid = UserHandle.getUid(userId, susPs.appId);
3836                        killUid(uid, reason);
3837                    }
3838                }
3839            } else if (sb instanceof PackageSetting) {
3840                PackageSetting ps = (PackageSetting) sb;
3841                if (userId == UserHandle.USER_ALL) {
3842                    killApplication(ps.pkg.packageName, ps.appId, reason);
3843                } else {
3844                    final int uid = UserHandle.getUid(userId, ps.appId);
3845                    killUid(uid, reason);
3846                }
3847            }
3848        } finally {
3849            Binder.restoreCallingIdentity(identity);
3850        }
3851    }
3852
3853    private static void killUid(int uid, String reason) {
3854        IActivityManager am = ActivityManagerNative.getDefault();
3855        if (am != null) {
3856            try {
3857                am.killUid(uid, reason);
3858            } catch (RemoteException e) {
3859                /* ignore - same process */
3860            }
3861        }
3862    }
3863
3864    /**
3865     * Compares two sets of signatures. Returns:
3866     * <br />
3867     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3868     * <br />
3869     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3870     * <br />
3871     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3872     * <br />
3873     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3874     * <br />
3875     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3876     */
3877    static int compareSignatures(Signature[] s1, Signature[] s2) {
3878        if (s1 == null) {
3879            return s2 == null
3880                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3881                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3882        }
3883
3884        if (s2 == null) {
3885            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3886        }
3887
3888        if (s1.length != s2.length) {
3889            return PackageManager.SIGNATURE_NO_MATCH;
3890        }
3891
3892        // Since both signature sets are of size 1, we can compare without HashSets.
3893        if (s1.length == 1) {
3894            return s1[0].equals(s2[0]) ?
3895                    PackageManager.SIGNATURE_MATCH :
3896                    PackageManager.SIGNATURE_NO_MATCH;
3897        }
3898
3899        ArraySet<Signature> set1 = new ArraySet<Signature>();
3900        for (Signature sig : s1) {
3901            set1.add(sig);
3902        }
3903        ArraySet<Signature> set2 = new ArraySet<Signature>();
3904        for (Signature sig : s2) {
3905            set2.add(sig);
3906        }
3907        // Make sure s2 contains all signatures in s1.
3908        if (set1.equals(set2)) {
3909            return PackageManager.SIGNATURE_MATCH;
3910        }
3911        return PackageManager.SIGNATURE_NO_MATCH;
3912    }
3913
3914    /**
3915     * If the database version for this type of package (internal storage or
3916     * external storage) is less than the version where package signatures
3917     * were updated, return true.
3918     */
3919    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3920        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3921                DatabaseVersion.SIGNATURE_END_ENTITY))
3922                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3923                        DatabaseVersion.SIGNATURE_END_ENTITY));
3924    }
3925
3926    /**
3927     * Used for backward compatibility to make sure any packages with
3928     * certificate chains get upgraded to the new style. {@code existingSigs}
3929     * will be in the old format (since they were stored on disk from before the
3930     * system upgrade) and {@code scannedSigs} will be in the newer format.
3931     */
3932    private int compareSignaturesCompat(PackageSignatures existingSigs,
3933            PackageParser.Package scannedPkg) {
3934        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3935            return PackageManager.SIGNATURE_NO_MATCH;
3936        }
3937
3938        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3939        for (Signature sig : existingSigs.mSignatures) {
3940            existingSet.add(sig);
3941        }
3942        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3943        for (Signature sig : scannedPkg.mSignatures) {
3944            try {
3945                Signature[] chainSignatures = sig.getChainSignatures();
3946                for (Signature chainSig : chainSignatures) {
3947                    scannedCompatSet.add(chainSig);
3948                }
3949            } catch (CertificateEncodingException e) {
3950                scannedCompatSet.add(sig);
3951            }
3952        }
3953        /*
3954         * Make sure the expanded scanned set contains all signatures in the
3955         * existing one.
3956         */
3957        if (scannedCompatSet.equals(existingSet)) {
3958            // Migrate the old signatures to the new scheme.
3959            existingSigs.assignSignatures(scannedPkg.mSignatures);
3960            // The new KeySets will be re-added later in the scanning process.
3961            synchronized (mPackages) {
3962                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3963            }
3964            return PackageManager.SIGNATURE_MATCH;
3965        }
3966        return PackageManager.SIGNATURE_NO_MATCH;
3967    }
3968
3969    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3970        if (isExternal(scannedPkg)) {
3971            return mSettings.isExternalDatabaseVersionOlderThan(
3972                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3973        } else {
3974            return mSettings.isInternalDatabaseVersionOlderThan(
3975                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3976        }
3977    }
3978
3979    private int compareSignaturesRecover(PackageSignatures existingSigs,
3980            PackageParser.Package scannedPkg) {
3981        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3982            return PackageManager.SIGNATURE_NO_MATCH;
3983        }
3984
3985        String msg = null;
3986        try {
3987            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3988                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3989                        + scannedPkg.packageName);
3990                return PackageManager.SIGNATURE_MATCH;
3991            }
3992        } catch (CertificateException e) {
3993            msg = e.getMessage();
3994        }
3995
3996        logCriticalInfo(Log.INFO,
3997                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3998        return PackageManager.SIGNATURE_NO_MATCH;
3999    }
4000
4001    @Override
4002    public String[] getPackagesForUid(int uid) {
4003        uid = UserHandle.getAppId(uid);
4004        // reader
4005        synchronized (mPackages) {
4006            Object obj = mSettings.getUserIdLPr(uid);
4007            if (obj instanceof SharedUserSetting) {
4008                final SharedUserSetting sus = (SharedUserSetting) obj;
4009                final int N = sus.packages.size();
4010                final String[] res = new String[N];
4011                final Iterator<PackageSetting> it = sus.packages.iterator();
4012                int i = 0;
4013                while (it.hasNext()) {
4014                    res[i++] = it.next().name;
4015                }
4016                return res;
4017            } else if (obj instanceof PackageSetting) {
4018                final PackageSetting ps = (PackageSetting) obj;
4019                return new String[] { ps.name };
4020            }
4021        }
4022        return null;
4023    }
4024
4025    @Override
4026    public String getNameForUid(int uid) {
4027        // reader
4028        synchronized (mPackages) {
4029            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4030            if (obj instanceof SharedUserSetting) {
4031                final SharedUserSetting sus = (SharedUserSetting) obj;
4032                return sus.name + ":" + sus.userId;
4033            } else if (obj instanceof PackageSetting) {
4034                final PackageSetting ps = (PackageSetting) obj;
4035                return ps.name;
4036            }
4037        }
4038        return null;
4039    }
4040
4041    @Override
4042    public int getUidForSharedUser(String sharedUserName) {
4043        if(sharedUserName == null) {
4044            return -1;
4045        }
4046        // reader
4047        synchronized (mPackages) {
4048            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4049            if (suid == null) {
4050                return -1;
4051            }
4052            return suid.userId;
4053        }
4054    }
4055
4056    @Override
4057    public int getFlagsForUid(int uid) {
4058        synchronized (mPackages) {
4059            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4060            if (obj instanceof SharedUserSetting) {
4061                final SharedUserSetting sus = (SharedUserSetting) obj;
4062                return sus.pkgFlags;
4063            } else if (obj instanceof PackageSetting) {
4064                final PackageSetting ps = (PackageSetting) obj;
4065                return ps.pkgFlags;
4066            }
4067        }
4068        return 0;
4069    }
4070
4071    @Override
4072    public int getPrivateFlagsForUid(int uid) {
4073        synchronized (mPackages) {
4074            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4075            if (obj instanceof SharedUserSetting) {
4076                final SharedUserSetting sus = (SharedUserSetting) obj;
4077                return sus.pkgPrivateFlags;
4078            } else if (obj instanceof PackageSetting) {
4079                final PackageSetting ps = (PackageSetting) obj;
4080                return ps.pkgPrivateFlags;
4081            }
4082        }
4083        return 0;
4084    }
4085
4086    @Override
4087    public boolean isUidPrivileged(int uid) {
4088        uid = UserHandle.getAppId(uid);
4089        // reader
4090        synchronized (mPackages) {
4091            Object obj = mSettings.getUserIdLPr(uid);
4092            if (obj instanceof SharedUserSetting) {
4093                final SharedUserSetting sus = (SharedUserSetting) obj;
4094                final Iterator<PackageSetting> it = sus.packages.iterator();
4095                while (it.hasNext()) {
4096                    if (it.next().isPrivileged()) {
4097                        return true;
4098                    }
4099                }
4100            } else if (obj instanceof PackageSetting) {
4101                final PackageSetting ps = (PackageSetting) obj;
4102                return ps.isPrivileged();
4103            }
4104        }
4105        return false;
4106    }
4107
4108    @Override
4109    public String[] getAppOpPermissionPackages(String permissionName) {
4110        synchronized (mPackages) {
4111            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4112            if (pkgs == null) {
4113                return null;
4114            }
4115            return pkgs.toArray(new String[pkgs.size()]);
4116        }
4117    }
4118
4119    @Override
4120    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4121            int flags, int userId) {
4122        if (!sUserManager.exists(userId)) return null;
4123        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4124        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4125        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4126    }
4127
4128    @Override
4129    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4130            IntentFilter filter, int match, ComponentName activity) {
4131        final int userId = UserHandle.getCallingUserId();
4132        if (DEBUG_PREFERRED) {
4133            Log.v(TAG, "setLastChosenActivity intent=" + intent
4134                + " resolvedType=" + resolvedType
4135                + " flags=" + flags
4136                + " filter=" + filter
4137                + " match=" + match
4138                + " activity=" + activity);
4139            filter.dump(new PrintStreamPrinter(System.out), "    ");
4140        }
4141        intent.setComponent(null);
4142        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4143        // Find any earlier preferred or last chosen entries and nuke them
4144        findPreferredActivity(intent, resolvedType,
4145                flags, query, 0, false, true, false, userId);
4146        // Add the new activity as the last chosen for this filter
4147        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4148                "Setting last chosen");
4149    }
4150
4151    @Override
4152    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4153        final int userId = UserHandle.getCallingUserId();
4154        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4155        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4156        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4157                false, false, false, userId);
4158    }
4159
4160    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4161            int flags, List<ResolveInfo> query, int userId) {
4162        if (query != null) {
4163            final int N = query.size();
4164            if (N == 1) {
4165                return query.get(0);
4166            } else if (N > 1) {
4167                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4168                // If there is more than one activity with the same priority,
4169                // then let the user decide between them.
4170                ResolveInfo r0 = query.get(0);
4171                ResolveInfo r1 = query.get(1);
4172                if (DEBUG_INTENT_MATCHING || debug) {
4173                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4174                            + r1.activityInfo.name + "=" + r1.priority);
4175                }
4176                // If the first activity has a higher priority, or a different
4177                // default, then it is always desireable to pick it.
4178                if (r0.priority != r1.priority
4179                        || r0.preferredOrder != r1.preferredOrder
4180                        || r0.isDefault != r1.isDefault) {
4181                    return query.get(0);
4182                }
4183                // If we have saved a preference for a preferred activity for
4184                // this Intent, use that.
4185                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4186                        flags, query, r0.priority, true, false, debug, userId);
4187                if (ri != null) {
4188                    return ri;
4189                }
4190                if (userId != 0) {
4191                    ri = new ResolveInfo(mResolveInfo);
4192                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4193                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4194                            ri.activityInfo.applicationInfo);
4195                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4196                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4197                    return ri;
4198                }
4199                return mResolveInfo;
4200            }
4201        }
4202        return null;
4203    }
4204
4205    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4206            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4207        final int N = query.size();
4208        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4209                .get(userId);
4210        // Get the list of persistent preferred activities that handle the intent
4211        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4212        List<PersistentPreferredActivity> pprefs = ppir != null
4213                ? ppir.queryIntent(intent, resolvedType,
4214                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4215                : null;
4216        if (pprefs != null && pprefs.size() > 0) {
4217            final int M = pprefs.size();
4218            for (int i=0; i<M; i++) {
4219                final PersistentPreferredActivity ppa = pprefs.get(i);
4220                if (DEBUG_PREFERRED || debug) {
4221                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4222                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4223                            + "\n  component=" + ppa.mComponent);
4224                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4225                }
4226                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4227                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4228                if (DEBUG_PREFERRED || debug) {
4229                    Slog.v(TAG, "Found persistent preferred activity:");
4230                    if (ai != null) {
4231                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4232                    } else {
4233                        Slog.v(TAG, "  null");
4234                    }
4235                }
4236                if (ai == null) {
4237                    // This previously registered persistent preferred activity
4238                    // component is no longer known. Ignore it and do NOT remove it.
4239                    continue;
4240                }
4241                for (int j=0; j<N; j++) {
4242                    final ResolveInfo ri = query.get(j);
4243                    if (!ri.activityInfo.applicationInfo.packageName
4244                            .equals(ai.applicationInfo.packageName)) {
4245                        continue;
4246                    }
4247                    if (!ri.activityInfo.name.equals(ai.name)) {
4248                        continue;
4249                    }
4250                    //  Found a persistent preference that can handle the intent.
4251                    if (DEBUG_PREFERRED || debug) {
4252                        Slog.v(TAG, "Returning persistent preferred activity: " +
4253                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4254                    }
4255                    return ri;
4256                }
4257            }
4258        }
4259        return null;
4260    }
4261
4262    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4263            List<ResolveInfo> query, int priority, boolean always,
4264            boolean removeMatches, boolean debug, int userId) {
4265        if (!sUserManager.exists(userId)) return null;
4266        // writer
4267        synchronized (mPackages) {
4268            if (intent.getSelector() != null) {
4269                intent = intent.getSelector();
4270            }
4271            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4272
4273            // Try to find a matching persistent preferred activity.
4274            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4275                    debug, userId);
4276
4277            // If a persistent preferred activity matched, use it.
4278            if (pri != null) {
4279                return pri;
4280            }
4281
4282            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4283            // Get the list of preferred activities that handle the intent
4284            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4285            List<PreferredActivity> prefs = pir != null
4286                    ? pir.queryIntent(intent, resolvedType,
4287                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4288                    : null;
4289            if (prefs != null && prefs.size() > 0) {
4290                boolean changed = false;
4291                try {
4292                    // First figure out how good the original match set is.
4293                    // We will only allow preferred activities that came
4294                    // from the same match quality.
4295                    int match = 0;
4296
4297                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4298
4299                    final int N = query.size();
4300                    for (int j=0; j<N; j++) {
4301                        final ResolveInfo ri = query.get(j);
4302                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4303                                + ": 0x" + Integer.toHexString(match));
4304                        if (ri.match > match) {
4305                            match = ri.match;
4306                        }
4307                    }
4308
4309                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4310                            + Integer.toHexString(match));
4311
4312                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4313                    final int M = prefs.size();
4314                    for (int i=0; i<M; i++) {
4315                        final PreferredActivity pa = prefs.get(i);
4316                        if (DEBUG_PREFERRED || debug) {
4317                            Slog.v(TAG, "Checking PreferredActivity ds="
4318                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4319                                    + "\n  component=" + pa.mPref.mComponent);
4320                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4321                        }
4322                        if (pa.mPref.mMatch != match) {
4323                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4324                                    + Integer.toHexString(pa.mPref.mMatch));
4325                            continue;
4326                        }
4327                        // If it's not an "always" type preferred activity and that's what we're
4328                        // looking for, skip it.
4329                        if (always && !pa.mPref.mAlways) {
4330                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4331                            continue;
4332                        }
4333                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4334                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4335                        if (DEBUG_PREFERRED || debug) {
4336                            Slog.v(TAG, "Found preferred activity:");
4337                            if (ai != null) {
4338                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4339                            } else {
4340                                Slog.v(TAG, "  null");
4341                            }
4342                        }
4343                        if (ai == null) {
4344                            // This previously registered preferred activity
4345                            // component is no longer known.  Most likely an update
4346                            // to the app was installed and in the new version this
4347                            // component no longer exists.  Clean it up by removing
4348                            // it from the preferred activities list, and skip it.
4349                            Slog.w(TAG, "Removing dangling preferred activity: "
4350                                    + pa.mPref.mComponent);
4351                            pir.removeFilter(pa);
4352                            changed = true;
4353                            continue;
4354                        }
4355                        for (int j=0; j<N; j++) {
4356                            final ResolveInfo ri = query.get(j);
4357                            if (!ri.activityInfo.applicationInfo.packageName
4358                                    .equals(ai.applicationInfo.packageName)) {
4359                                continue;
4360                            }
4361                            if (!ri.activityInfo.name.equals(ai.name)) {
4362                                continue;
4363                            }
4364
4365                            if (removeMatches) {
4366                                pir.removeFilter(pa);
4367                                changed = true;
4368                                if (DEBUG_PREFERRED) {
4369                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4370                                }
4371                                break;
4372                            }
4373
4374                            // Okay we found a previously set preferred or last chosen app.
4375                            // If the result set is different from when this
4376                            // was created, we need to clear it and re-ask the
4377                            // user their preference, if we're looking for an "always" type entry.
4378                            if (always && !pa.mPref.sameSet(query)) {
4379                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4380                                        + intent + " type " + resolvedType);
4381                                if (DEBUG_PREFERRED) {
4382                                    Slog.v(TAG, "Removing preferred activity since set changed "
4383                                            + pa.mPref.mComponent);
4384                                }
4385                                pir.removeFilter(pa);
4386                                // Re-add the filter as a "last chosen" entry (!always)
4387                                PreferredActivity lastChosen = new PreferredActivity(
4388                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4389                                pir.addFilter(lastChosen);
4390                                changed = true;
4391                                return null;
4392                            }
4393
4394                            // Yay! Either the set matched or we're looking for the last chosen
4395                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4396                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4397                            return ri;
4398                        }
4399                    }
4400                } finally {
4401                    if (changed) {
4402                        if (DEBUG_PREFERRED) {
4403                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4404                        }
4405                        scheduleWritePackageRestrictionsLocked(userId);
4406                    }
4407                }
4408            }
4409        }
4410        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4411        return null;
4412    }
4413
4414    /*
4415     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4416     */
4417    @Override
4418    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4419            int targetUserId) {
4420        mContext.enforceCallingOrSelfPermission(
4421                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4422        List<CrossProfileIntentFilter> matches =
4423                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4424        if (matches != null) {
4425            int size = matches.size();
4426            for (int i = 0; i < size; i++) {
4427                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4428            }
4429        }
4430        if (hasWebURI(intent)) {
4431            // cross-profile app linking works only towards the parent.
4432            final UserInfo parent = getProfileParent(sourceUserId);
4433            synchronized(mPackages) {
4434                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4435                        parent.id) != null;
4436            }
4437        }
4438        return false;
4439    }
4440
4441    private UserInfo getProfileParent(int userId) {
4442        final long identity = Binder.clearCallingIdentity();
4443        try {
4444            return sUserManager.getProfileParent(userId);
4445        } finally {
4446            Binder.restoreCallingIdentity(identity);
4447        }
4448    }
4449
4450    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4451            String resolvedType, int userId) {
4452        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4453        if (resolver != null) {
4454            return resolver.queryIntent(intent, resolvedType, false, userId);
4455        }
4456        return null;
4457    }
4458
4459    @Override
4460    public List<ResolveInfo> queryIntentActivities(Intent intent,
4461            String resolvedType, int flags, int userId) {
4462        if (!sUserManager.exists(userId)) return Collections.emptyList();
4463        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4464        ComponentName comp = intent.getComponent();
4465        if (comp == null) {
4466            if (intent.getSelector() != null) {
4467                intent = intent.getSelector();
4468                comp = intent.getComponent();
4469            }
4470        }
4471
4472        if (comp != null) {
4473            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4474            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4475            if (ai != null) {
4476                final ResolveInfo ri = new ResolveInfo();
4477                ri.activityInfo = ai;
4478                list.add(ri);
4479            }
4480            return list;
4481        }
4482
4483        // reader
4484        synchronized (mPackages) {
4485            final String pkgName = intent.getPackage();
4486            if (pkgName == null) {
4487                List<CrossProfileIntentFilter> matchingFilters =
4488                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4489                // Check for results that need to skip the current profile.
4490                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4491                        resolvedType, flags, userId);
4492                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4493                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4494                    result.add(xpResolveInfo);
4495                    return filterIfNotPrimaryUser(result, userId);
4496                }
4497
4498                // Check for results in the current profile.
4499                List<ResolveInfo> result = mActivities.queryIntent(
4500                        intent, resolvedType, flags, userId);
4501
4502                // Check for cross profile results.
4503                xpResolveInfo = queryCrossProfileIntents(
4504                        matchingFilters, intent, resolvedType, flags, userId);
4505                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4506                    result.add(xpResolveInfo);
4507                    Collections.sort(result, mResolvePrioritySorter);
4508                }
4509                result = filterIfNotPrimaryUser(result, userId);
4510                if (hasWebURI(intent)) {
4511                    CrossProfileDomainInfo xpDomainInfo = null;
4512                    final UserInfo parent = getProfileParent(userId);
4513                    if (parent != null) {
4514                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4515                                flags, userId, parent.id);
4516                    }
4517                    if (xpDomainInfo != null) {
4518                        if (xpResolveInfo != null) {
4519                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4520                            // in the result.
4521                            result.remove(xpResolveInfo);
4522                        }
4523                        if (result.size() == 0) {
4524                            result.add(xpDomainInfo.resolveInfo);
4525                            return result;
4526                        }
4527                    } else if (result.size() <= 1) {
4528                        return result;
4529                    }
4530                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4531                            xpDomainInfo);
4532                    Collections.sort(result, mResolvePrioritySorter);
4533                }
4534                return result;
4535            }
4536            final PackageParser.Package pkg = mPackages.get(pkgName);
4537            if (pkg != null) {
4538                return filterIfNotPrimaryUser(
4539                        mActivities.queryIntentForPackage(
4540                                intent, resolvedType, flags, pkg.activities, userId),
4541                        userId);
4542            }
4543            return new ArrayList<ResolveInfo>();
4544        }
4545    }
4546
4547    private static class CrossProfileDomainInfo {
4548        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4549        ResolveInfo resolveInfo;
4550        /* Best domain verification status of the activities found in the other profile */
4551        int bestDomainVerificationStatus;
4552    }
4553
4554    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4555            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4556        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4557                sourceUserId)) {
4558            return null;
4559        }
4560        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4561                resolvedType, flags, parentUserId);
4562
4563        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4564            return null;
4565        }
4566        CrossProfileDomainInfo result = null;
4567        int size = resultTargetUser.size();
4568        for (int i = 0; i < size; i++) {
4569            ResolveInfo riTargetUser = resultTargetUser.get(i);
4570            // Intent filter verification is only for filters that specify a host. So don't return
4571            // those that handle all web uris.
4572            if (riTargetUser.handleAllWebDataURI) {
4573                continue;
4574            }
4575            String packageName = riTargetUser.activityInfo.packageName;
4576            PackageSetting ps = mSettings.mPackages.get(packageName);
4577            if (ps == null) {
4578                continue;
4579            }
4580            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4581            if (result == null) {
4582                result = new CrossProfileDomainInfo();
4583                result.resolveInfo =
4584                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4585                result.bestDomainVerificationStatus = status;
4586            } else {
4587                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4588                        result.bestDomainVerificationStatus);
4589            }
4590        }
4591        return result;
4592    }
4593
4594    /**
4595     * Verification statuses are ordered from the worse to the best, except for
4596     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4597     */
4598    private int bestDomainVerificationStatus(int status1, int status2) {
4599        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4600            return status2;
4601        }
4602        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4603            return status1;
4604        }
4605        return (int) MathUtils.max(status1, status2);
4606    }
4607
4608    private boolean isUserEnabled(int userId) {
4609        long callingId = Binder.clearCallingIdentity();
4610        try {
4611            UserInfo userInfo = sUserManager.getUserInfo(userId);
4612            return userInfo != null && userInfo.isEnabled();
4613        } finally {
4614            Binder.restoreCallingIdentity(callingId);
4615        }
4616    }
4617
4618    /**
4619     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4620     *
4621     * @return filtered list
4622     */
4623    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4624        if (userId == UserHandle.USER_OWNER) {
4625            return resolveInfos;
4626        }
4627        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4628            ResolveInfo info = resolveInfos.get(i);
4629            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4630                resolveInfos.remove(i);
4631            }
4632        }
4633        return resolveInfos;
4634    }
4635
4636    private static boolean hasWebURI(Intent intent) {
4637        if (intent.getData() == null) {
4638            return false;
4639        }
4640        final String scheme = intent.getScheme();
4641        if (TextUtils.isEmpty(scheme)) {
4642            return false;
4643        }
4644        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4645    }
4646
4647    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4648            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4649        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4650            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4651                    candidates.size());
4652        }
4653
4654        final int userId = UserHandle.getCallingUserId();
4655        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4656        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4657        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4658        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4659        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4660
4661        synchronized (mPackages) {
4662            final int count = candidates.size();
4663            // First, try to use linked apps. Partition the candidates into four lists:
4664            // one for the final results, one for the "do not use ever", one for "undefined status"
4665            // and finally one for "browser app type".
4666            for (int n=0; n<count; n++) {
4667                ResolveInfo info = candidates.get(n);
4668                String packageName = info.activityInfo.packageName;
4669                PackageSetting ps = mSettings.mPackages.get(packageName);
4670                if (ps != null) {
4671                    // Add to the special match all list (Browser use case)
4672                    if (info.handleAllWebDataURI) {
4673                        matchAllList.add(info);
4674                        continue;
4675                    }
4676                    // Try to get the status from User settings first
4677                    int status = getDomainVerificationStatusLPr(ps, userId);
4678                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4679                        if (DEBUG_DOMAIN_VERIFICATION) {
4680                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4681                        }
4682                        alwaysList.add(info);
4683                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4684                        if (DEBUG_DOMAIN_VERIFICATION) {
4685                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4686                        }
4687                        neverList.add(info);
4688                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4689                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4690                        if (DEBUG_DOMAIN_VERIFICATION) {
4691                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4692                        }
4693                        undefinedList.add(info);
4694                    }
4695                }
4696            }
4697            // First try to add the "always" resolution for the current user if there is any
4698            if (alwaysList.size() > 0) {
4699                result.addAll(alwaysList);
4700            // if there is an "always" for the parent user, add it.
4701            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4702                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4703                result.add(xpDomainInfo.resolveInfo);
4704            } else {
4705                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4706                result.addAll(undefinedList);
4707                if (xpDomainInfo != null && (
4708                        xpDomainInfo.bestDomainVerificationStatus
4709                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4710                        || xpDomainInfo.bestDomainVerificationStatus
4711                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4712                    result.add(xpDomainInfo.resolveInfo);
4713                }
4714                // Also add Browsers (all of them or only the default one)
4715                if ((flags & MATCH_ALL) != 0) {
4716                    result.addAll(matchAllList);
4717                } else {
4718                    // Try to add the Default Browser if we can
4719                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4720                            UserHandle.myUserId());
4721                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4722                        boolean defaultBrowserFound = false;
4723                        final int browserCount = matchAllList.size();
4724                        for (int n=0; n<browserCount; n++) {
4725                            ResolveInfo browser = matchAllList.get(n);
4726                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4727                                result.add(browser);
4728                                defaultBrowserFound = true;
4729                                break;
4730                            }
4731                        }
4732                        if (!defaultBrowserFound) {
4733                            result.addAll(matchAllList);
4734                        }
4735                    } else {
4736                        result.addAll(matchAllList);
4737                    }
4738                }
4739
4740                // If there is nothing selected, add all candidates and remove the ones that the user
4741                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4742                if (result.size() == 0) {
4743                    result.addAll(candidates);
4744                    result.removeAll(neverList);
4745                }
4746            }
4747        }
4748        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4749            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4750                    result.size());
4751            for (ResolveInfo info : result) {
4752                Slog.v(TAG, "  + " + info.activityInfo);
4753            }
4754        }
4755        return result;
4756    }
4757
4758    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4759        int status = ps.getDomainVerificationStatusForUser(userId);
4760        // if none available, get the master status
4761        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4762            if (ps.getIntentFilterVerificationInfo() != null) {
4763                status = ps.getIntentFilterVerificationInfo().getStatus();
4764            }
4765        }
4766        return status;
4767    }
4768
4769    private ResolveInfo querySkipCurrentProfileIntents(
4770            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4771            int flags, int sourceUserId) {
4772        if (matchingFilters != null) {
4773            int size = matchingFilters.size();
4774            for (int i = 0; i < size; i ++) {
4775                CrossProfileIntentFilter filter = matchingFilters.get(i);
4776                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4777                    // Checking if there are activities in the target user that can handle the
4778                    // intent.
4779                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4780                            flags, sourceUserId);
4781                    if (resolveInfo != null) {
4782                        return resolveInfo;
4783                    }
4784                }
4785            }
4786        }
4787        return null;
4788    }
4789
4790    // Return matching ResolveInfo if any for skip current profile intent filters.
4791    private ResolveInfo queryCrossProfileIntents(
4792            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4793            int flags, int sourceUserId) {
4794        if (matchingFilters != null) {
4795            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4796            // match the same intent. For performance reasons, it is better not to
4797            // run queryIntent twice for the same userId
4798            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4799            int size = matchingFilters.size();
4800            for (int i = 0; i < size; i++) {
4801                CrossProfileIntentFilter filter = matchingFilters.get(i);
4802                int targetUserId = filter.getTargetUserId();
4803                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4804                        && !alreadyTriedUserIds.get(targetUserId)) {
4805                    // Checking if there are activities in the target user that can handle the
4806                    // intent.
4807                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4808                            flags, sourceUserId);
4809                    if (resolveInfo != null) return resolveInfo;
4810                    alreadyTriedUserIds.put(targetUserId, true);
4811                }
4812            }
4813        }
4814        return null;
4815    }
4816
4817    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4818            String resolvedType, int flags, int sourceUserId) {
4819        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4820                resolvedType, flags, filter.getTargetUserId());
4821        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4822            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4823        }
4824        return null;
4825    }
4826
4827    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4828            int sourceUserId, int targetUserId) {
4829        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4830        String className;
4831        if (targetUserId == UserHandle.USER_OWNER) {
4832            className = FORWARD_INTENT_TO_USER_OWNER;
4833        } else {
4834            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4835        }
4836        ComponentName forwardingActivityComponentName = new ComponentName(
4837                mAndroidApplication.packageName, className);
4838        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4839                sourceUserId);
4840        if (targetUserId == UserHandle.USER_OWNER) {
4841            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4842            forwardingResolveInfo.noResourceId = true;
4843        }
4844        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4845        forwardingResolveInfo.priority = 0;
4846        forwardingResolveInfo.preferredOrder = 0;
4847        forwardingResolveInfo.match = 0;
4848        forwardingResolveInfo.isDefault = true;
4849        forwardingResolveInfo.filter = filter;
4850        forwardingResolveInfo.targetUserId = targetUserId;
4851        return forwardingResolveInfo;
4852    }
4853
4854    @Override
4855    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4856            Intent[] specifics, String[] specificTypes, Intent intent,
4857            String resolvedType, int flags, int userId) {
4858        if (!sUserManager.exists(userId)) return Collections.emptyList();
4859        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4860                false, "query intent activity options");
4861        final String resultsAction = intent.getAction();
4862
4863        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4864                | PackageManager.GET_RESOLVED_FILTER, userId);
4865
4866        if (DEBUG_INTENT_MATCHING) {
4867            Log.v(TAG, "Query " + intent + ": " + results);
4868        }
4869
4870        int specificsPos = 0;
4871        int N;
4872
4873        // todo: note that the algorithm used here is O(N^2).  This
4874        // isn't a problem in our current environment, but if we start running
4875        // into situations where we have more than 5 or 10 matches then this
4876        // should probably be changed to something smarter...
4877
4878        // First we go through and resolve each of the specific items
4879        // that were supplied, taking care of removing any corresponding
4880        // duplicate items in the generic resolve list.
4881        if (specifics != null) {
4882            for (int i=0; i<specifics.length; i++) {
4883                final Intent sintent = specifics[i];
4884                if (sintent == null) {
4885                    continue;
4886                }
4887
4888                if (DEBUG_INTENT_MATCHING) {
4889                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4890                }
4891
4892                String action = sintent.getAction();
4893                if (resultsAction != null && resultsAction.equals(action)) {
4894                    // If this action was explicitly requested, then don't
4895                    // remove things that have it.
4896                    action = null;
4897                }
4898
4899                ResolveInfo ri = null;
4900                ActivityInfo ai = null;
4901
4902                ComponentName comp = sintent.getComponent();
4903                if (comp == null) {
4904                    ri = resolveIntent(
4905                        sintent,
4906                        specificTypes != null ? specificTypes[i] : null,
4907                            flags, userId);
4908                    if (ri == null) {
4909                        continue;
4910                    }
4911                    if (ri == mResolveInfo) {
4912                        // ACK!  Must do something better with this.
4913                    }
4914                    ai = ri.activityInfo;
4915                    comp = new ComponentName(ai.applicationInfo.packageName,
4916                            ai.name);
4917                } else {
4918                    ai = getActivityInfo(comp, flags, userId);
4919                    if (ai == null) {
4920                        continue;
4921                    }
4922                }
4923
4924                // Look for any generic query activities that are duplicates
4925                // of this specific one, and remove them from the results.
4926                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4927                N = results.size();
4928                int j;
4929                for (j=specificsPos; j<N; j++) {
4930                    ResolveInfo sri = results.get(j);
4931                    if ((sri.activityInfo.name.equals(comp.getClassName())
4932                            && sri.activityInfo.applicationInfo.packageName.equals(
4933                                    comp.getPackageName()))
4934                        || (action != null && sri.filter.matchAction(action))) {
4935                        results.remove(j);
4936                        if (DEBUG_INTENT_MATCHING) Log.v(
4937                            TAG, "Removing duplicate item from " + j
4938                            + " due to specific " + specificsPos);
4939                        if (ri == null) {
4940                            ri = sri;
4941                        }
4942                        j--;
4943                        N--;
4944                    }
4945                }
4946
4947                // Add this specific item to its proper place.
4948                if (ri == null) {
4949                    ri = new ResolveInfo();
4950                    ri.activityInfo = ai;
4951                }
4952                results.add(specificsPos, ri);
4953                ri.specificIndex = i;
4954                specificsPos++;
4955            }
4956        }
4957
4958        // Now we go through the remaining generic results and remove any
4959        // duplicate actions that are found here.
4960        N = results.size();
4961        for (int i=specificsPos; i<N-1; i++) {
4962            final ResolveInfo rii = results.get(i);
4963            if (rii.filter == null) {
4964                continue;
4965            }
4966
4967            // Iterate over all of the actions of this result's intent
4968            // filter...  typically this should be just one.
4969            final Iterator<String> it = rii.filter.actionsIterator();
4970            if (it == null) {
4971                continue;
4972            }
4973            while (it.hasNext()) {
4974                final String action = it.next();
4975                if (resultsAction != null && resultsAction.equals(action)) {
4976                    // If this action was explicitly requested, then don't
4977                    // remove things that have it.
4978                    continue;
4979                }
4980                for (int j=i+1; j<N; j++) {
4981                    final ResolveInfo rij = results.get(j);
4982                    if (rij.filter != null && rij.filter.hasAction(action)) {
4983                        results.remove(j);
4984                        if (DEBUG_INTENT_MATCHING) Log.v(
4985                            TAG, "Removing duplicate item from " + j
4986                            + " due to action " + action + " at " + i);
4987                        j--;
4988                        N--;
4989                    }
4990                }
4991            }
4992
4993            // If the caller didn't request filter information, drop it now
4994            // so we don't have to marshall/unmarshall it.
4995            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4996                rii.filter = null;
4997            }
4998        }
4999
5000        // Filter out the caller activity if so requested.
5001        if (caller != null) {
5002            N = results.size();
5003            for (int i=0; i<N; i++) {
5004                ActivityInfo ainfo = results.get(i).activityInfo;
5005                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5006                        && caller.getClassName().equals(ainfo.name)) {
5007                    results.remove(i);
5008                    break;
5009                }
5010            }
5011        }
5012
5013        // If the caller didn't request filter information,
5014        // drop them now so we don't have to
5015        // marshall/unmarshall it.
5016        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5017            N = results.size();
5018            for (int i=0; i<N; i++) {
5019                results.get(i).filter = null;
5020            }
5021        }
5022
5023        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5024        return results;
5025    }
5026
5027    @Override
5028    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5029            int userId) {
5030        if (!sUserManager.exists(userId)) return Collections.emptyList();
5031        ComponentName comp = intent.getComponent();
5032        if (comp == null) {
5033            if (intent.getSelector() != null) {
5034                intent = intent.getSelector();
5035                comp = intent.getComponent();
5036            }
5037        }
5038        if (comp != null) {
5039            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5040            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5041            if (ai != null) {
5042                ResolveInfo ri = new ResolveInfo();
5043                ri.activityInfo = ai;
5044                list.add(ri);
5045            }
5046            return list;
5047        }
5048
5049        // reader
5050        synchronized (mPackages) {
5051            String pkgName = intent.getPackage();
5052            if (pkgName == null) {
5053                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5054            }
5055            final PackageParser.Package pkg = mPackages.get(pkgName);
5056            if (pkg != null) {
5057                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5058                        userId);
5059            }
5060            return null;
5061        }
5062    }
5063
5064    @Override
5065    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5066        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5067        if (!sUserManager.exists(userId)) return null;
5068        if (query != null) {
5069            if (query.size() >= 1) {
5070                // If there is more than one service with the same priority,
5071                // just arbitrarily pick the first one.
5072                return query.get(0);
5073            }
5074        }
5075        return null;
5076    }
5077
5078    @Override
5079    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5080            int userId) {
5081        if (!sUserManager.exists(userId)) return Collections.emptyList();
5082        ComponentName comp = intent.getComponent();
5083        if (comp == null) {
5084            if (intent.getSelector() != null) {
5085                intent = intent.getSelector();
5086                comp = intent.getComponent();
5087            }
5088        }
5089        if (comp != null) {
5090            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5091            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5092            if (si != null) {
5093                final ResolveInfo ri = new ResolveInfo();
5094                ri.serviceInfo = si;
5095                list.add(ri);
5096            }
5097            return list;
5098        }
5099
5100        // reader
5101        synchronized (mPackages) {
5102            String pkgName = intent.getPackage();
5103            if (pkgName == null) {
5104                return mServices.queryIntent(intent, resolvedType, flags, userId);
5105            }
5106            final PackageParser.Package pkg = mPackages.get(pkgName);
5107            if (pkg != null) {
5108                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5109                        userId);
5110            }
5111            return null;
5112        }
5113    }
5114
5115    @Override
5116    public List<ResolveInfo> queryIntentContentProviders(
5117            Intent intent, String resolvedType, int flags, int userId) {
5118        if (!sUserManager.exists(userId)) return Collections.emptyList();
5119        ComponentName comp = intent.getComponent();
5120        if (comp == null) {
5121            if (intent.getSelector() != null) {
5122                intent = intent.getSelector();
5123                comp = intent.getComponent();
5124            }
5125        }
5126        if (comp != null) {
5127            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5128            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5129            if (pi != null) {
5130                final ResolveInfo ri = new ResolveInfo();
5131                ri.providerInfo = pi;
5132                list.add(ri);
5133            }
5134            return list;
5135        }
5136
5137        // reader
5138        synchronized (mPackages) {
5139            String pkgName = intent.getPackage();
5140            if (pkgName == null) {
5141                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5142            }
5143            final PackageParser.Package pkg = mPackages.get(pkgName);
5144            if (pkg != null) {
5145                return mProviders.queryIntentForPackage(
5146                        intent, resolvedType, flags, pkg.providers, userId);
5147            }
5148            return null;
5149        }
5150    }
5151
5152    @Override
5153    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5154        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5155
5156        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5157
5158        // writer
5159        synchronized (mPackages) {
5160            ArrayList<PackageInfo> list;
5161            if (listUninstalled) {
5162                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5163                for (PackageSetting ps : mSettings.mPackages.values()) {
5164                    PackageInfo pi;
5165                    if (ps.pkg != null) {
5166                        pi = generatePackageInfo(ps.pkg, flags, userId);
5167                    } else {
5168                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5169                    }
5170                    if (pi != null) {
5171                        list.add(pi);
5172                    }
5173                }
5174            } else {
5175                list = new ArrayList<PackageInfo>(mPackages.size());
5176                for (PackageParser.Package p : mPackages.values()) {
5177                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5178                    if (pi != null) {
5179                        list.add(pi);
5180                    }
5181                }
5182            }
5183
5184            return new ParceledListSlice<PackageInfo>(list);
5185        }
5186    }
5187
5188    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5189            String[] permissions, boolean[] tmp, int flags, int userId) {
5190        int numMatch = 0;
5191        final PermissionsState permissionsState = ps.getPermissionsState();
5192        for (int i=0; i<permissions.length; i++) {
5193            final String permission = permissions[i];
5194            if (permissionsState.hasPermission(permission, userId)) {
5195                tmp[i] = true;
5196                numMatch++;
5197            } else {
5198                tmp[i] = false;
5199            }
5200        }
5201        if (numMatch == 0) {
5202            return;
5203        }
5204        PackageInfo pi;
5205        if (ps.pkg != null) {
5206            pi = generatePackageInfo(ps.pkg, flags, userId);
5207        } else {
5208            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5209        }
5210        // The above might return null in cases of uninstalled apps or install-state
5211        // skew across users/profiles.
5212        if (pi != null) {
5213            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5214                if (numMatch == permissions.length) {
5215                    pi.requestedPermissions = permissions;
5216                } else {
5217                    pi.requestedPermissions = new String[numMatch];
5218                    numMatch = 0;
5219                    for (int i=0; i<permissions.length; i++) {
5220                        if (tmp[i]) {
5221                            pi.requestedPermissions[numMatch] = permissions[i];
5222                            numMatch++;
5223                        }
5224                    }
5225                }
5226            }
5227            list.add(pi);
5228        }
5229    }
5230
5231    @Override
5232    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5233            String[] permissions, int flags, int userId) {
5234        if (!sUserManager.exists(userId)) return null;
5235        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5236
5237        // writer
5238        synchronized (mPackages) {
5239            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5240            boolean[] tmpBools = new boolean[permissions.length];
5241            if (listUninstalled) {
5242                for (PackageSetting ps : mSettings.mPackages.values()) {
5243                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5244                }
5245            } else {
5246                for (PackageParser.Package pkg : mPackages.values()) {
5247                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5248                    if (ps != null) {
5249                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5250                                userId);
5251                    }
5252                }
5253            }
5254
5255            return new ParceledListSlice<PackageInfo>(list);
5256        }
5257    }
5258
5259    @Override
5260    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5261        if (!sUserManager.exists(userId)) return null;
5262        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5263
5264        // writer
5265        synchronized (mPackages) {
5266            ArrayList<ApplicationInfo> list;
5267            if (listUninstalled) {
5268                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5269                for (PackageSetting ps : mSettings.mPackages.values()) {
5270                    ApplicationInfo ai;
5271                    if (ps.pkg != null) {
5272                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5273                                ps.readUserState(userId), userId);
5274                    } else {
5275                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5276                    }
5277                    if (ai != null) {
5278                        list.add(ai);
5279                    }
5280                }
5281            } else {
5282                list = new ArrayList<ApplicationInfo>(mPackages.size());
5283                for (PackageParser.Package p : mPackages.values()) {
5284                    if (p.mExtras != null) {
5285                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5286                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5287                        if (ai != null) {
5288                            list.add(ai);
5289                        }
5290                    }
5291                }
5292            }
5293
5294            return new ParceledListSlice<ApplicationInfo>(list);
5295        }
5296    }
5297
5298    public List<ApplicationInfo> getPersistentApplications(int flags) {
5299        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5300
5301        // reader
5302        synchronized (mPackages) {
5303            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5304            final int userId = UserHandle.getCallingUserId();
5305            while (i.hasNext()) {
5306                final PackageParser.Package p = i.next();
5307                if (p.applicationInfo != null
5308                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5309                        && (!mSafeMode || isSystemApp(p))) {
5310                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5311                    if (ps != null) {
5312                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5313                                ps.readUserState(userId), userId);
5314                        if (ai != null) {
5315                            finalList.add(ai);
5316                        }
5317                    }
5318                }
5319            }
5320        }
5321
5322        return finalList;
5323    }
5324
5325    @Override
5326    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5327        if (!sUserManager.exists(userId)) return null;
5328        // reader
5329        synchronized (mPackages) {
5330            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5331            PackageSetting ps = provider != null
5332                    ? mSettings.mPackages.get(provider.owner.packageName)
5333                    : null;
5334            return ps != null
5335                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5336                    && (!mSafeMode || (provider.info.applicationInfo.flags
5337                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5338                    ? PackageParser.generateProviderInfo(provider, flags,
5339                            ps.readUserState(userId), userId)
5340                    : null;
5341        }
5342    }
5343
5344    /**
5345     * @deprecated
5346     */
5347    @Deprecated
5348    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5349        // reader
5350        synchronized (mPackages) {
5351            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5352                    .entrySet().iterator();
5353            final int userId = UserHandle.getCallingUserId();
5354            while (i.hasNext()) {
5355                Map.Entry<String, PackageParser.Provider> entry = i.next();
5356                PackageParser.Provider p = entry.getValue();
5357                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5358
5359                if (ps != null && p.syncable
5360                        && (!mSafeMode || (p.info.applicationInfo.flags
5361                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5362                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5363                            ps.readUserState(userId), userId);
5364                    if (info != null) {
5365                        outNames.add(entry.getKey());
5366                        outInfo.add(info);
5367                    }
5368                }
5369            }
5370        }
5371    }
5372
5373    @Override
5374    public List<ProviderInfo> queryContentProviders(String processName,
5375            int uid, int flags) {
5376        ArrayList<ProviderInfo> finalList = null;
5377        // reader
5378        synchronized (mPackages) {
5379            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5380            final int userId = processName != null ?
5381                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5382            while (i.hasNext()) {
5383                final PackageParser.Provider p = i.next();
5384                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5385                if (ps != null && p.info.authority != null
5386                        && (processName == null
5387                                || (p.info.processName.equals(processName)
5388                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5389                        && mSettings.isEnabledLPr(p.info, flags, userId)
5390                        && (!mSafeMode
5391                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5392                    if (finalList == null) {
5393                        finalList = new ArrayList<ProviderInfo>(3);
5394                    }
5395                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5396                            ps.readUserState(userId), userId);
5397                    if (info != null) {
5398                        finalList.add(info);
5399                    }
5400                }
5401            }
5402        }
5403
5404        if (finalList != null) {
5405            Collections.sort(finalList, mProviderInitOrderSorter);
5406        }
5407
5408        return finalList;
5409    }
5410
5411    @Override
5412    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5413            int flags) {
5414        // reader
5415        synchronized (mPackages) {
5416            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5417            return PackageParser.generateInstrumentationInfo(i, flags);
5418        }
5419    }
5420
5421    @Override
5422    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5423            int flags) {
5424        ArrayList<InstrumentationInfo> finalList =
5425            new ArrayList<InstrumentationInfo>();
5426
5427        // reader
5428        synchronized (mPackages) {
5429            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5430            while (i.hasNext()) {
5431                final PackageParser.Instrumentation p = i.next();
5432                if (targetPackage == null
5433                        || targetPackage.equals(p.info.targetPackage)) {
5434                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5435                            flags);
5436                    if (ii != null) {
5437                        finalList.add(ii);
5438                    }
5439                }
5440            }
5441        }
5442
5443        return finalList;
5444    }
5445
5446    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5447        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5448        if (overlays == null) {
5449            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5450            return;
5451        }
5452        for (PackageParser.Package opkg : overlays.values()) {
5453            // Not much to do if idmap fails: we already logged the error
5454            // and we certainly don't want to abort installation of pkg simply
5455            // because an overlay didn't fit properly. For these reasons,
5456            // ignore the return value of createIdmapForPackagePairLI.
5457            createIdmapForPackagePairLI(pkg, opkg);
5458        }
5459    }
5460
5461    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5462            PackageParser.Package opkg) {
5463        if (!opkg.mTrustedOverlay) {
5464            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5465                    opkg.baseCodePath + ": overlay not trusted");
5466            return false;
5467        }
5468        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5469        if (overlaySet == null) {
5470            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5471                    opkg.baseCodePath + " but target package has no known overlays");
5472            return false;
5473        }
5474        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5475        // TODO: generate idmap for split APKs
5476        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5477            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5478                    + opkg.baseCodePath);
5479            return false;
5480        }
5481        PackageParser.Package[] overlayArray =
5482            overlaySet.values().toArray(new PackageParser.Package[0]);
5483        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5484            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5485                return p1.mOverlayPriority - p2.mOverlayPriority;
5486            }
5487        };
5488        Arrays.sort(overlayArray, cmp);
5489
5490        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5491        int i = 0;
5492        for (PackageParser.Package p : overlayArray) {
5493            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5494        }
5495        return true;
5496    }
5497
5498    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5499        final File[] files = dir.listFiles();
5500        if (ArrayUtils.isEmpty(files)) {
5501            Log.d(TAG, "No files in app dir " + dir);
5502            return;
5503        }
5504
5505        if (DEBUG_PACKAGE_SCANNING) {
5506            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5507                    + " flags=0x" + Integer.toHexString(parseFlags));
5508        }
5509
5510        for (File file : files) {
5511            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5512                    && !PackageInstallerService.isStageName(file.getName());
5513            if (!isPackage) {
5514                // Ignore entries which are not packages
5515                continue;
5516            }
5517            try {
5518                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5519                        scanFlags, currentTime, null);
5520            } catch (PackageManagerException e) {
5521                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5522
5523                // Delete invalid userdata apps
5524                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5525                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5526                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5527                    if (file.isDirectory()) {
5528                        mInstaller.rmPackageDir(file.getAbsolutePath());
5529                    } else {
5530                        file.delete();
5531                    }
5532                }
5533            }
5534        }
5535    }
5536
5537    private static File getSettingsProblemFile() {
5538        File dataDir = Environment.getDataDirectory();
5539        File systemDir = new File(dataDir, "system");
5540        File fname = new File(systemDir, "uiderrors.txt");
5541        return fname;
5542    }
5543
5544    static void reportSettingsProblem(int priority, String msg) {
5545        logCriticalInfo(priority, msg);
5546    }
5547
5548    static void logCriticalInfo(int priority, String msg) {
5549        Slog.println(priority, TAG, msg);
5550        EventLogTags.writePmCriticalInfo(msg);
5551        try {
5552            File fname = getSettingsProblemFile();
5553            FileOutputStream out = new FileOutputStream(fname, true);
5554            PrintWriter pw = new FastPrintWriter(out);
5555            SimpleDateFormat formatter = new SimpleDateFormat();
5556            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5557            pw.println(dateString + ": " + msg);
5558            pw.close();
5559            FileUtils.setPermissions(
5560                    fname.toString(),
5561                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5562                    -1, -1);
5563        } catch (java.io.IOException e) {
5564        }
5565    }
5566
5567    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5568            PackageParser.Package pkg, File srcFile, int parseFlags)
5569            throws PackageManagerException {
5570        if (ps != null
5571                && ps.codePath.equals(srcFile)
5572                && ps.timeStamp == srcFile.lastModified()
5573                && !isCompatSignatureUpdateNeeded(pkg)
5574                && !isRecoverSignatureUpdateNeeded(pkg)) {
5575            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5576            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5577            ArraySet<PublicKey> signingKs;
5578            synchronized (mPackages) {
5579                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5580            }
5581            if (ps.signatures.mSignatures != null
5582                    && ps.signatures.mSignatures.length != 0
5583                    && signingKs != null) {
5584                // Optimization: reuse the existing cached certificates
5585                // if the package appears to be unchanged.
5586                pkg.mSignatures = ps.signatures.mSignatures;
5587                pkg.mSigningKeys = signingKs;
5588                return;
5589            }
5590
5591            Slog.w(TAG, "PackageSetting for " + ps.name
5592                    + " is missing signatures.  Collecting certs again to recover them.");
5593        } else {
5594            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5595        }
5596
5597        try {
5598            pp.collectCertificates(pkg, parseFlags);
5599            pp.collectManifestDigest(pkg);
5600        } catch (PackageParserException e) {
5601            throw PackageManagerException.from(e);
5602        }
5603    }
5604
5605    /*
5606     *  Scan a package and return the newly parsed package.
5607     *  Returns null in case of errors and the error code is stored in mLastScanError
5608     */
5609    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5610            long currentTime, UserHandle user) throws PackageManagerException {
5611        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5612        parseFlags |= mDefParseFlags;
5613        PackageParser pp = new PackageParser();
5614        pp.setSeparateProcesses(mSeparateProcesses);
5615        pp.setOnlyCoreApps(mOnlyCore);
5616        pp.setDisplayMetrics(mMetrics);
5617
5618        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5619            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5620        }
5621
5622        final PackageParser.Package pkg;
5623        try {
5624            pkg = pp.parsePackage(scanFile, parseFlags);
5625        } catch (PackageParserException e) {
5626            throw PackageManagerException.from(e);
5627        }
5628
5629        PackageSetting ps = null;
5630        PackageSetting updatedPkg;
5631        // reader
5632        synchronized (mPackages) {
5633            // Look to see if we already know about this package.
5634            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5635            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5636                // This package has been renamed to its original name.  Let's
5637                // use that.
5638                ps = mSettings.peekPackageLPr(oldName);
5639            }
5640            // If there was no original package, see one for the real package name.
5641            if (ps == null) {
5642                ps = mSettings.peekPackageLPr(pkg.packageName);
5643            }
5644            // Check to see if this package could be hiding/updating a system
5645            // package.  Must look for it either under the original or real
5646            // package name depending on our state.
5647            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5648            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5649        }
5650        boolean updatedPkgBetter = false;
5651        // First check if this is a system package that may involve an update
5652        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5653            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5654            // it needs to drop FLAG_PRIVILEGED.
5655            if (locationIsPrivileged(scanFile)) {
5656                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5657            } else {
5658                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5659            }
5660
5661            if (ps != null && !ps.codePath.equals(scanFile)) {
5662                // The path has changed from what was last scanned...  check the
5663                // version of the new path against what we have stored to determine
5664                // what to do.
5665                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5666                if (pkg.mVersionCode <= ps.versionCode) {
5667                    // The system package has been updated and the code path does not match
5668                    // Ignore entry. Skip it.
5669                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5670                            + " ignored: updated version " + ps.versionCode
5671                            + " better than this " + pkg.mVersionCode);
5672                    if (!updatedPkg.codePath.equals(scanFile)) {
5673                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5674                                + ps.name + " changing from " + updatedPkg.codePathString
5675                                + " to " + scanFile);
5676                        updatedPkg.codePath = scanFile;
5677                        updatedPkg.codePathString = scanFile.toString();
5678                        updatedPkg.resourcePath = scanFile;
5679                        updatedPkg.resourcePathString = scanFile.toString();
5680                    }
5681                    updatedPkg.pkg = pkg;
5682                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5683                            "Package " + ps.name + " at " + scanFile
5684                                    + " ignored: updated version " + ps.versionCode
5685                                    + " better than this " + pkg.mVersionCode);
5686                } else {
5687                    // The current app on the system partition is better than
5688                    // what we have updated to on the data partition; switch
5689                    // back to the system partition version.
5690                    // At this point, its safely assumed that package installation for
5691                    // apps in system partition will go through. If not there won't be a working
5692                    // version of the app
5693                    // writer
5694                    synchronized (mPackages) {
5695                        // Just remove the loaded entries from package lists.
5696                        mPackages.remove(ps.name);
5697                    }
5698
5699                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5700                            + " reverting from " + ps.codePathString
5701                            + ": new version " + pkg.mVersionCode
5702                            + " better than installed " + ps.versionCode);
5703
5704                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5705                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5706                    synchronized (mInstallLock) {
5707                        args.cleanUpResourcesLI();
5708                    }
5709                    synchronized (mPackages) {
5710                        mSettings.enableSystemPackageLPw(ps.name);
5711                    }
5712                    updatedPkgBetter = true;
5713                }
5714            }
5715        }
5716
5717        if (updatedPkg != null) {
5718            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5719            // initially
5720            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5721
5722            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5723            // flag set initially
5724            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5725                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5726            }
5727        }
5728
5729        // Verify certificates against what was last scanned
5730        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5731
5732        /*
5733         * A new system app appeared, but we already had a non-system one of the
5734         * same name installed earlier.
5735         */
5736        boolean shouldHideSystemApp = false;
5737        if (updatedPkg == null && ps != null
5738                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5739            /*
5740             * Check to make sure the signatures match first. If they don't,
5741             * wipe the installed application and its data.
5742             */
5743            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5744                    != PackageManager.SIGNATURE_MATCH) {
5745                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5746                        + " signatures don't match existing userdata copy; removing");
5747                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5748                ps = null;
5749            } else {
5750                /*
5751                 * If the newly-added system app is an older version than the
5752                 * already installed version, hide it. It will be scanned later
5753                 * and re-added like an update.
5754                 */
5755                if (pkg.mVersionCode <= ps.versionCode) {
5756                    shouldHideSystemApp = true;
5757                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5758                            + " but new version " + pkg.mVersionCode + " better than installed "
5759                            + ps.versionCode + "; hiding system");
5760                } else {
5761                    /*
5762                     * The newly found system app is a newer version that the
5763                     * one previously installed. Simply remove the
5764                     * already-installed application and replace it with our own
5765                     * while keeping the application data.
5766                     */
5767                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5768                            + " reverting from " + ps.codePathString + ": new version "
5769                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5770                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5771                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5772                    synchronized (mInstallLock) {
5773                        args.cleanUpResourcesLI();
5774                    }
5775                }
5776            }
5777        }
5778
5779        // The apk is forward locked (not public) if its code and resources
5780        // are kept in different files. (except for app in either system or
5781        // vendor path).
5782        // TODO grab this value from PackageSettings
5783        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5784            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5785                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5786            }
5787        }
5788
5789        // TODO: extend to support forward-locked splits
5790        String resourcePath = null;
5791        String baseResourcePath = null;
5792        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5793            if (ps != null && ps.resourcePathString != null) {
5794                resourcePath = ps.resourcePathString;
5795                baseResourcePath = ps.resourcePathString;
5796            } else {
5797                // Should not happen at all. Just log an error.
5798                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5799            }
5800        } else {
5801            resourcePath = pkg.codePath;
5802            baseResourcePath = pkg.baseCodePath;
5803        }
5804
5805        // Set application objects path explicitly.
5806        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5807        pkg.applicationInfo.setCodePath(pkg.codePath);
5808        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5809        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5810        pkg.applicationInfo.setResourcePath(resourcePath);
5811        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5812        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5813
5814        // Note that we invoke the following method only if we are about to unpack an application
5815        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5816                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5817
5818        /*
5819         * If the system app should be overridden by a previously installed
5820         * data, hide the system app now and let the /data/app scan pick it up
5821         * again.
5822         */
5823        if (shouldHideSystemApp) {
5824            synchronized (mPackages) {
5825                /*
5826                 * We have to grant systems permissions before we hide, because
5827                 * grantPermissions will assume the package update is trying to
5828                 * expand its permissions.
5829                 */
5830                grantPermissionsLPw(pkg, true, pkg.packageName);
5831                mSettings.disableSystemPackageLPw(pkg.packageName);
5832            }
5833        }
5834
5835        return scannedPkg;
5836    }
5837
5838    private static String fixProcessName(String defProcessName,
5839            String processName, int uid) {
5840        if (processName == null) {
5841            return defProcessName;
5842        }
5843        return processName;
5844    }
5845
5846    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5847            throws PackageManagerException {
5848        if (pkgSetting.signatures.mSignatures != null) {
5849            // Already existing package. Make sure signatures match
5850            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5851                    == PackageManager.SIGNATURE_MATCH;
5852            if (!match) {
5853                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5854                        == PackageManager.SIGNATURE_MATCH;
5855            }
5856            if (!match) {
5857                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5858                        == PackageManager.SIGNATURE_MATCH;
5859            }
5860            if (!match) {
5861                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5862                        + pkg.packageName + " signatures do not match the "
5863                        + "previously installed version; ignoring!");
5864            }
5865        }
5866
5867        // Check for shared user signatures
5868        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5869            // Already existing package. Make sure signatures match
5870            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5871                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5872            if (!match) {
5873                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5874                        == PackageManager.SIGNATURE_MATCH;
5875            }
5876            if (!match) {
5877                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5878                        == PackageManager.SIGNATURE_MATCH;
5879            }
5880            if (!match) {
5881                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5882                        "Package " + pkg.packageName
5883                        + " has no signatures that match those in shared user "
5884                        + pkgSetting.sharedUser.name + "; ignoring!");
5885            }
5886        }
5887    }
5888
5889    /**
5890     * Enforces that only the system UID or root's UID can call a method exposed
5891     * via Binder.
5892     *
5893     * @param message used as message if SecurityException is thrown
5894     * @throws SecurityException if the caller is not system or root
5895     */
5896    private static final void enforceSystemOrRoot(String message) {
5897        final int uid = Binder.getCallingUid();
5898        if (uid != Process.SYSTEM_UID && uid != 0) {
5899            throw new SecurityException(message);
5900        }
5901    }
5902
5903    @Override
5904    public void performBootDexOpt() {
5905        enforceSystemOrRoot("Only the system can request dexopt be performed");
5906
5907        // Before everything else, see whether we need to fstrim.
5908        try {
5909            IMountService ms = PackageHelper.getMountService();
5910            if (ms != null) {
5911                final boolean isUpgrade = isUpgrade();
5912                boolean doTrim = isUpgrade;
5913                if (doTrim) {
5914                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5915                } else {
5916                    final long interval = android.provider.Settings.Global.getLong(
5917                            mContext.getContentResolver(),
5918                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5919                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5920                    if (interval > 0) {
5921                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5922                        if (timeSinceLast > interval) {
5923                            doTrim = true;
5924                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5925                                    + "; running immediately");
5926                        }
5927                    }
5928                }
5929                if (doTrim) {
5930                    if (!isFirstBoot()) {
5931                        try {
5932                            ActivityManagerNative.getDefault().showBootMessage(
5933                                    mContext.getResources().getString(
5934                                            R.string.android_upgrading_fstrim), true);
5935                        } catch (RemoteException e) {
5936                        }
5937                    }
5938                    ms.runMaintenance();
5939                }
5940            } else {
5941                Slog.e(TAG, "Mount service unavailable!");
5942            }
5943        } catch (RemoteException e) {
5944            // Can't happen; MountService is local
5945        }
5946
5947        final ArraySet<PackageParser.Package> pkgs;
5948        synchronized (mPackages) {
5949            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5950        }
5951
5952        if (pkgs != null) {
5953            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5954            // in case the device runs out of space.
5955            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5956            // Give priority to core apps.
5957            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5958                PackageParser.Package pkg = it.next();
5959                if (pkg.coreApp) {
5960                    if (DEBUG_DEXOPT) {
5961                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5962                    }
5963                    sortedPkgs.add(pkg);
5964                    it.remove();
5965                }
5966            }
5967            // Give priority to system apps that listen for pre boot complete.
5968            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5969            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5970            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5971                PackageParser.Package pkg = it.next();
5972                if (pkgNames.contains(pkg.packageName)) {
5973                    if (DEBUG_DEXOPT) {
5974                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5975                    }
5976                    sortedPkgs.add(pkg);
5977                    it.remove();
5978                }
5979            }
5980            // Give priority to system apps.
5981            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5982                PackageParser.Package pkg = it.next();
5983                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5984                    if (DEBUG_DEXOPT) {
5985                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5986                    }
5987                    sortedPkgs.add(pkg);
5988                    it.remove();
5989                }
5990            }
5991            // Give priority to updated system apps.
5992            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5993                PackageParser.Package pkg = it.next();
5994                if (pkg.isUpdatedSystemApp()) {
5995                    if (DEBUG_DEXOPT) {
5996                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5997                    }
5998                    sortedPkgs.add(pkg);
5999                    it.remove();
6000                }
6001            }
6002            // Give priority to apps that listen for boot complete.
6003            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6004            pkgNames = getPackageNamesForIntent(intent);
6005            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6006                PackageParser.Package pkg = it.next();
6007                if (pkgNames.contains(pkg.packageName)) {
6008                    if (DEBUG_DEXOPT) {
6009                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6010                    }
6011                    sortedPkgs.add(pkg);
6012                    it.remove();
6013                }
6014            }
6015            // Filter out packages that aren't recently used.
6016            filterRecentlyUsedApps(pkgs);
6017            // Add all remaining apps.
6018            for (PackageParser.Package pkg : pkgs) {
6019                if (DEBUG_DEXOPT) {
6020                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6021                }
6022                sortedPkgs.add(pkg);
6023            }
6024
6025            // If we want to be lazy, filter everything that wasn't recently used.
6026            if (mLazyDexOpt) {
6027                filterRecentlyUsedApps(sortedPkgs);
6028            }
6029
6030            int i = 0;
6031            int total = sortedPkgs.size();
6032            File dataDir = Environment.getDataDirectory();
6033            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6034            if (lowThreshold == 0) {
6035                throw new IllegalStateException("Invalid low memory threshold");
6036            }
6037            for (PackageParser.Package pkg : sortedPkgs) {
6038                long usableSpace = dataDir.getUsableSpace();
6039                if (usableSpace < lowThreshold) {
6040                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6041                    break;
6042                }
6043                performBootDexOpt(pkg, ++i, total);
6044            }
6045        }
6046    }
6047
6048    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6049        // Filter out packages that aren't recently used.
6050        //
6051        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6052        // should do a full dexopt.
6053        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6054            int total = pkgs.size();
6055            int skipped = 0;
6056            long now = System.currentTimeMillis();
6057            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6058                PackageParser.Package pkg = i.next();
6059                long then = pkg.mLastPackageUsageTimeInMills;
6060                if (then + mDexOptLRUThresholdInMills < now) {
6061                    if (DEBUG_DEXOPT) {
6062                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6063                              ((then == 0) ? "never" : new Date(then)));
6064                    }
6065                    i.remove();
6066                    skipped++;
6067                }
6068            }
6069            if (DEBUG_DEXOPT) {
6070                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6071            }
6072        }
6073    }
6074
6075    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6076        List<ResolveInfo> ris = null;
6077        try {
6078            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6079                    intent, null, 0, UserHandle.USER_OWNER);
6080        } catch (RemoteException e) {
6081        }
6082        ArraySet<String> pkgNames = new ArraySet<String>();
6083        if (ris != null) {
6084            for (ResolveInfo ri : ris) {
6085                pkgNames.add(ri.activityInfo.packageName);
6086            }
6087        }
6088        return pkgNames;
6089    }
6090
6091    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6092        if (DEBUG_DEXOPT) {
6093            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6094        }
6095        if (!isFirstBoot()) {
6096            try {
6097                ActivityManagerNative.getDefault().showBootMessage(
6098                        mContext.getResources().getString(R.string.android_upgrading_apk,
6099                                curr, total), true);
6100            } catch (RemoteException e) {
6101            }
6102        }
6103        PackageParser.Package p = pkg;
6104        synchronized (mInstallLock) {
6105            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6106                    false /* force dex */, false /* defer */, true /* include dependencies */);
6107        }
6108    }
6109
6110    @Override
6111    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6112        return performDexOpt(packageName, instructionSet, false);
6113    }
6114
6115    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6116        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6117        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6118        if (!dexopt && !updateUsage) {
6119            // We aren't going to dexopt or update usage, so bail early.
6120            return false;
6121        }
6122        PackageParser.Package p;
6123        final String targetInstructionSet;
6124        synchronized (mPackages) {
6125            p = mPackages.get(packageName);
6126            if (p == null) {
6127                return false;
6128            }
6129            if (updateUsage) {
6130                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6131            }
6132            mPackageUsage.write(false);
6133            if (!dexopt) {
6134                // We aren't going to dexopt, so bail early.
6135                return false;
6136            }
6137
6138            targetInstructionSet = instructionSet != null ? instructionSet :
6139                    getPrimaryInstructionSet(p.applicationInfo);
6140            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6141                return false;
6142            }
6143        }
6144
6145        synchronized (mInstallLock) {
6146            final String[] instructionSets = new String[] { targetInstructionSet };
6147            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6148                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6149            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6150        }
6151    }
6152
6153    public ArraySet<String> getPackagesThatNeedDexOpt() {
6154        ArraySet<String> pkgs = null;
6155        synchronized (mPackages) {
6156            for (PackageParser.Package p : mPackages.values()) {
6157                if (DEBUG_DEXOPT) {
6158                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6159                }
6160                if (!p.mDexOptPerformed.isEmpty()) {
6161                    continue;
6162                }
6163                if (pkgs == null) {
6164                    pkgs = new ArraySet<String>();
6165                }
6166                pkgs.add(p.packageName);
6167            }
6168        }
6169        return pkgs;
6170    }
6171
6172    public void shutdown() {
6173        mPackageUsage.write(true);
6174    }
6175
6176    @Override
6177    public void forceDexOpt(String packageName) {
6178        enforceSystemOrRoot("forceDexOpt");
6179
6180        PackageParser.Package pkg;
6181        synchronized (mPackages) {
6182            pkg = mPackages.get(packageName);
6183            if (pkg == null) {
6184                throw new IllegalArgumentException("Missing package: " + packageName);
6185            }
6186        }
6187
6188        synchronized (mInstallLock) {
6189            final String[] instructionSets = new String[] {
6190                    getPrimaryInstructionSet(pkg.applicationInfo) };
6191            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6192                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6193            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6194                throw new IllegalStateException("Failed to dexopt: " + res);
6195            }
6196        }
6197    }
6198
6199    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6200        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6201            Slog.w(TAG, "Unable to update from " + oldPkg.name
6202                    + " to " + newPkg.packageName
6203                    + ": old package not in system partition");
6204            return false;
6205        } else if (mPackages.get(oldPkg.name) != null) {
6206            Slog.w(TAG, "Unable to update from " + oldPkg.name
6207                    + " to " + newPkg.packageName
6208                    + ": old package still exists");
6209            return false;
6210        }
6211        return true;
6212    }
6213
6214    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6215        int[] users = sUserManager.getUserIds();
6216        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6217        if (res < 0) {
6218            return res;
6219        }
6220        for (int user : users) {
6221            if (user != 0) {
6222                res = mInstaller.createUserData(volumeUuid, packageName,
6223                        UserHandle.getUid(user, uid), user, seinfo);
6224                if (res < 0) {
6225                    return res;
6226                }
6227            }
6228        }
6229        return res;
6230    }
6231
6232    private int removeDataDirsLI(String volumeUuid, String packageName) {
6233        int[] users = sUserManager.getUserIds();
6234        int res = 0;
6235        for (int user : users) {
6236            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6237            if (resInner < 0) {
6238                res = resInner;
6239            }
6240        }
6241
6242        return res;
6243    }
6244
6245    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6246        int[] users = sUserManager.getUserIds();
6247        int res = 0;
6248        for (int user : users) {
6249            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6250            if (resInner < 0) {
6251                res = resInner;
6252            }
6253        }
6254        return res;
6255    }
6256
6257    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6258            PackageParser.Package changingLib) {
6259        if (file.path != null) {
6260            usesLibraryFiles.add(file.path);
6261            return;
6262        }
6263        PackageParser.Package p = mPackages.get(file.apk);
6264        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6265            // If we are doing this while in the middle of updating a library apk,
6266            // then we need to make sure to use that new apk for determining the
6267            // dependencies here.  (We haven't yet finished committing the new apk
6268            // to the package manager state.)
6269            if (p == null || p.packageName.equals(changingLib.packageName)) {
6270                p = changingLib;
6271            }
6272        }
6273        if (p != null) {
6274            usesLibraryFiles.addAll(p.getAllCodePaths());
6275        }
6276    }
6277
6278    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6279            PackageParser.Package changingLib) throws PackageManagerException {
6280        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6281            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6282            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6283            for (int i=0; i<N; i++) {
6284                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6285                if (file == null) {
6286                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6287                            "Package " + pkg.packageName + " requires unavailable shared library "
6288                            + pkg.usesLibraries.get(i) + "; failing!");
6289                }
6290                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6291            }
6292            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6293            for (int i=0; i<N; i++) {
6294                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6295                if (file == null) {
6296                    Slog.w(TAG, "Package " + pkg.packageName
6297                            + " desires unavailable shared library "
6298                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6299                } else {
6300                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6301                }
6302            }
6303            N = usesLibraryFiles.size();
6304            if (N > 0) {
6305                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6306            } else {
6307                pkg.usesLibraryFiles = null;
6308            }
6309        }
6310    }
6311
6312    private static boolean hasString(List<String> list, List<String> which) {
6313        if (list == null) {
6314            return false;
6315        }
6316        for (int i=list.size()-1; i>=0; i--) {
6317            for (int j=which.size()-1; j>=0; j--) {
6318                if (which.get(j).equals(list.get(i))) {
6319                    return true;
6320                }
6321            }
6322        }
6323        return false;
6324    }
6325
6326    private void updateAllSharedLibrariesLPw() {
6327        for (PackageParser.Package pkg : mPackages.values()) {
6328            try {
6329                updateSharedLibrariesLPw(pkg, null);
6330            } catch (PackageManagerException e) {
6331                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6332            }
6333        }
6334    }
6335
6336    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6337            PackageParser.Package changingPkg) {
6338        ArrayList<PackageParser.Package> res = null;
6339        for (PackageParser.Package pkg : mPackages.values()) {
6340            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6341                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6342                if (res == null) {
6343                    res = new ArrayList<PackageParser.Package>();
6344                }
6345                res.add(pkg);
6346                try {
6347                    updateSharedLibrariesLPw(pkg, changingPkg);
6348                } catch (PackageManagerException e) {
6349                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6350                }
6351            }
6352        }
6353        return res;
6354    }
6355
6356    /**
6357     * Derive the value of the {@code cpuAbiOverride} based on the provided
6358     * value and an optional stored value from the package settings.
6359     */
6360    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6361        String cpuAbiOverride = null;
6362
6363        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6364            cpuAbiOverride = null;
6365        } else if (abiOverride != null) {
6366            cpuAbiOverride = abiOverride;
6367        } else if (settings != null) {
6368            cpuAbiOverride = settings.cpuAbiOverrideString;
6369        }
6370
6371        return cpuAbiOverride;
6372    }
6373
6374    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6375            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6376        boolean success = false;
6377        try {
6378            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6379                    currentTime, user);
6380            success = true;
6381            return res;
6382        } finally {
6383            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6384                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6385            }
6386        }
6387    }
6388
6389    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6390            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6391        final File scanFile = new File(pkg.codePath);
6392        if (pkg.applicationInfo.getCodePath() == null ||
6393                pkg.applicationInfo.getResourcePath() == null) {
6394            // Bail out. The resource and code paths haven't been set.
6395            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6396                    "Code and resource paths haven't been set correctly");
6397        }
6398
6399        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6400            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6401        } else {
6402            // Only allow system apps to be flagged as core apps.
6403            pkg.coreApp = false;
6404        }
6405
6406        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6407            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6408        }
6409
6410        if (mCustomResolverComponentName != null &&
6411                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6412            setUpCustomResolverActivity(pkg);
6413        }
6414
6415        if (pkg.packageName.equals("android")) {
6416            synchronized (mPackages) {
6417                if (mAndroidApplication != null) {
6418                    Slog.w(TAG, "*************************************************");
6419                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6420                    Slog.w(TAG, " file=" + scanFile);
6421                    Slog.w(TAG, "*************************************************");
6422                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6423                            "Core android package being redefined.  Skipping.");
6424                }
6425
6426                // Set up information for our fall-back user intent resolution activity.
6427                mPlatformPackage = pkg;
6428                pkg.mVersionCode = mSdkVersion;
6429                mAndroidApplication = pkg.applicationInfo;
6430
6431                if (!mResolverReplaced) {
6432                    mResolveActivity.applicationInfo = mAndroidApplication;
6433                    mResolveActivity.name = ResolverActivity.class.getName();
6434                    mResolveActivity.packageName = mAndroidApplication.packageName;
6435                    mResolveActivity.processName = "system:ui";
6436                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6437                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6438                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6439                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6440                    mResolveActivity.exported = true;
6441                    mResolveActivity.enabled = true;
6442                    mResolveInfo.activityInfo = mResolveActivity;
6443                    mResolveInfo.priority = 0;
6444                    mResolveInfo.preferredOrder = 0;
6445                    mResolveInfo.match = 0;
6446                    mResolveComponentName = new ComponentName(
6447                            mAndroidApplication.packageName, mResolveActivity.name);
6448                }
6449            }
6450        }
6451
6452        if (DEBUG_PACKAGE_SCANNING) {
6453            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6454                Log.d(TAG, "Scanning package " + pkg.packageName);
6455        }
6456
6457        if (mPackages.containsKey(pkg.packageName)
6458                || mSharedLibraries.containsKey(pkg.packageName)) {
6459            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6460                    "Application package " + pkg.packageName
6461                    + " already installed.  Skipping duplicate.");
6462        }
6463
6464        // If we're only installing presumed-existing packages, require that the
6465        // scanned APK is both already known and at the path previously established
6466        // for it.  Previously unknown packages we pick up normally, but if we have an
6467        // a priori expectation about this package's install presence, enforce it.
6468        // With a singular exception for new system packages. When an OTA contains
6469        // a new system package, we allow the codepath to change from a system location
6470        // to the user-installed location. If we don't allow this change, any newer,
6471        // user-installed version of the application will be ignored.
6472        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6473            if (mExpectingBetter.containsKey(pkg.packageName)) {
6474                logCriticalInfo(Log.WARN,
6475                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6476            } else {
6477                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6478                if (known != null) {
6479                    if (DEBUG_PACKAGE_SCANNING) {
6480                        Log.d(TAG, "Examining " + pkg.codePath
6481                                + " and requiring known paths " + known.codePathString
6482                                + " & " + known.resourcePathString);
6483                    }
6484                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6485                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6486                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6487                                "Application package " + pkg.packageName
6488                                + " found at " + pkg.applicationInfo.getCodePath()
6489                                + " but expected at " + known.codePathString + "; ignoring.");
6490                    }
6491                }
6492            }
6493        }
6494
6495        // Initialize package source and resource directories
6496        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6497        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6498
6499        SharedUserSetting suid = null;
6500        PackageSetting pkgSetting = null;
6501
6502        if (!isSystemApp(pkg)) {
6503            // Only system apps can use these features.
6504            pkg.mOriginalPackages = null;
6505            pkg.mRealPackage = null;
6506            pkg.mAdoptPermissions = null;
6507        }
6508
6509        // writer
6510        synchronized (mPackages) {
6511            if (pkg.mSharedUserId != null) {
6512                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6513                if (suid == null) {
6514                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6515                            "Creating application package " + pkg.packageName
6516                            + " for shared user failed");
6517                }
6518                if (DEBUG_PACKAGE_SCANNING) {
6519                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6520                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6521                                + "): packages=" + suid.packages);
6522                }
6523            }
6524
6525            // Check if we are renaming from an original package name.
6526            PackageSetting origPackage = null;
6527            String realName = null;
6528            if (pkg.mOriginalPackages != null) {
6529                // This package may need to be renamed to a previously
6530                // installed name.  Let's check on that...
6531                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6532                if (pkg.mOriginalPackages.contains(renamed)) {
6533                    // This package had originally been installed as the
6534                    // original name, and we have already taken care of
6535                    // transitioning to the new one.  Just update the new
6536                    // one to continue using the old name.
6537                    realName = pkg.mRealPackage;
6538                    if (!pkg.packageName.equals(renamed)) {
6539                        // Callers into this function may have already taken
6540                        // care of renaming the package; only do it here if
6541                        // it is not already done.
6542                        pkg.setPackageName(renamed);
6543                    }
6544
6545                } else {
6546                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6547                        if ((origPackage = mSettings.peekPackageLPr(
6548                                pkg.mOriginalPackages.get(i))) != null) {
6549                            // We do have the package already installed under its
6550                            // original name...  should we use it?
6551                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6552                                // New package is not compatible with original.
6553                                origPackage = null;
6554                                continue;
6555                            } else if (origPackage.sharedUser != null) {
6556                                // Make sure uid is compatible between packages.
6557                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6558                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6559                                            + " to " + pkg.packageName + ": old uid "
6560                                            + origPackage.sharedUser.name
6561                                            + " differs from " + pkg.mSharedUserId);
6562                                    origPackage = null;
6563                                    continue;
6564                                }
6565                            } else {
6566                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6567                                        + pkg.packageName + " to old name " + origPackage.name);
6568                            }
6569                            break;
6570                        }
6571                    }
6572                }
6573            }
6574
6575            if (mTransferedPackages.contains(pkg.packageName)) {
6576                Slog.w(TAG, "Package " + pkg.packageName
6577                        + " was transferred to another, but its .apk remains");
6578            }
6579
6580            // Just create the setting, don't add it yet. For already existing packages
6581            // the PkgSetting exists already and doesn't have to be created.
6582            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6583                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6584                    pkg.applicationInfo.primaryCpuAbi,
6585                    pkg.applicationInfo.secondaryCpuAbi,
6586                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6587                    user, false);
6588            if (pkgSetting == null) {
6589                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6590                        "Creating application package " + pkg.packageName + " failed");
6591            }
6592
6593            if (pkgSetting.origPackage != null) {
6594                // If we are first transitioning from an original package,
6595                // fix up the new package's name now.  We need to do this after
6596                // looking up the package under its new name, so getPackageLP
6597                // can take care of fiddling things correctly.
6598                pkg.setPackageName(origPackage.name);
6599
6600                // File a report about this.
6601                String msg = "New package " + pkgSetting.realName
6602                        + " renamed to replace old package " + pkgSetting.name;
6603                reportSettingsProblem(Log.WARN, msg);
6604
6605                // Make a note of it.
6606                mTransferedPackages.add(origPackage.name);
6607
6608                // No longer need to retain this.
6609                pkgSetting.origPackage = null;
6610            }
6611
6612            if (realName != null) {
6613                // Make a note of it.
6614                mTransferedPackages.add(pkg.packageName);
6615            }
6616
6617            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6618                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6619            }
6620
6621            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6622                // Check all shared libraries and map to their actual file path.
6623                // We only do this here for apps not on a system dir, because those
6624                // are the only ones that can fail an install due to this.  We
6625                // will take care of the system apps by updating all of their
6626                // library paths after the scan is done.
6627                updateSharedLibrariesLPw(pkg, null);
6628            }
6629
6630            if (mFoundPolicyFile) {
6631                SELinuxMMAC.assignSeinfoValue(pkg);
6632            }
6633
6634            pkg.applicationInfo.uid = pkgSetting.appId;
6635            pkg.mExtras = pkgSetting;
6636            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6637                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6638                    // We just determined the app is signed correctly, so bring
6639                    // over the latest parsed certs.
6640                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6641                } else {
6642                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6643                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6644                                "Package " + pkg.packageName + " upgrade keys do not match the "
6645                                + "previously installed version");
6646                    } else {
6647                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6648                        String msg = "System package " + pkg.packageName
6649                            + " signature changed; retaining data.";
6650                        reportSettingsProblem(Log.WARN, msg);
6651                    }
6652                }
6653            } else {
6654                try {
6655                    verifySignaturesLP(pkgSetting, pkg);
6656                    // We just determined the app is signed correctly, so bring
6657                    // over the latest parsed certs.
6658                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6659                } catch (PackageManagerException e) {
6660                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6661                        throw e;
6662                    }
6663                    // The signature has changed, but this package is in the system
6664                    // image...  let's recover!
6665                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6666                    // However...  if this package is part of a shared user, but it
6667                    // doesn't match the signature of the shared user, let's fail.
6668                    // What this means is that you can't change the signatures
6669                    // associated with an overall shared user, which doesn't seem all
6670                    // that unreasonable.
6671                    if (pkgSetting.sharedUser != null) {
6672                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6673                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6674                            throw new PackageManagerException(
6675                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6676                                            "Signature mismatch for shared user : "
6677                                            + pkgSetting.sharedUser);
6678                        }
6679                    }
6680                    // File a report about this.
6681                    String msg = "System package " + pkg.packageName
6682                        + " signature changed; retaining data.";
6683                    reportSettingsProblem(Log.WARN, msg);
6684                }
6685            }
6686            // Verify that this new package doesn't have any content providers
6687            // that conflict with existing packages.  Only do this if the
6688            // package isn't already installed, since we don't want to break
6689            // things that are installed.
6690            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6691                final int N = pkg.providers.size();
6692                int i;
6693                for (i=0; i<N; i++) {
6694                    PackageParser.Provider p = pkg.providers.get(i);
6695                    if (p.info.authority != null) {
6696                        String names[] = p.info.authority.split(";");
6697                        for (int j = 0; j < names.length; j++) {
6698                            if (mProvidersByAuthority.containsKey(names[j])) {
6699                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6700                                final String otherPackageName =
6701                                        ((other != null && other.getComponentName() != null) ?
6702                                                other.getComponentName().getPackageName() : "?");
6703                                throw new PackageManagerException(
6704                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6705                                                "Can't install because provider name " + names[j]
6706                                                + " (in package " + pkg.applicationInfo.packageName
6707                                                + ") is already used by " + otherPackageName);
6708                            }
6709                        }
6710                    }
6711                }
6712            }
6713
6714            if (pkg.mAdoptPermissions != null) {
6715                // This package wants to adopt ownership of permissions from
6716                // another package.
6717                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6718                    final String origName = pkg.mAdoptPermissions.get(i);
6719                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6720                    if (orig != null) {
6721                        if (verifyPackageUpdateLPr(orig, pkg)) {
6722                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6723                                    + pkg.packageName);
6724                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6725                        }
6726                    }
6727                }
6728            }
6729        }
6730
6731        final String pkgName = pkg.packageName;
6732
6733        final long scanFileTime = scanFile.lastModified();
6734        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6735        pkg.applicationInfo.processName = fixProcessName(
6736                pkg.applicationInfo.packageName,
6737                pkg.applicationInfo.processName,
6738                pkg.applicationInfo.uid);
6739
6740        File dataPath;
6741        if (mPlatformPackage == pkg) {
6742            // The system package is special.
6743            dataPath = new File(Environment.getDataDirectory(), "system");
6744
6745            pkg.applicationInfo.dataDir = dataPath.getPath();
6746
6747        } else {
6748            // This is a normal package, need to make its data directory.
6749            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6750                    UserHandle.USER_OWNER, pkg.packageName);
6751
6752            boolean uidError = false;
6753            if (dataPath.exists()) {
6754                int currentUid = 0;
6755                try {
6756                    StructStat stat = Os.stat(dataPath.getPath());
6757                    currentUid = stat.st_uid;
6758                } catch (ErrnoException e) {
6759                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6760                }
6761
6762                // If we have mismatched owners for the data path, we have a problem.
6763                if (currentUid != pkg.applicationInfo.uid) {
6764                    boolean recovered = false;
6765                    if (currentUid == 0) {
6766                        // The directory somehow became owned by root.  Wow.
6767                        // This is probably because the system was stopped while
6768                        // installd was in the middle of messing with its libs
6769                        // directory.  Ask installd to fix that.
6770                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6771                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6772                        if (ret >= 0) {
6773                            recovered = true;
6774                            String msg = "Package " + pkg.packageName
6775                                    + " unexpectedly changed to uid 0; recovered to " +
6776                                    + pkg.applicationInfo.uid;
6777                            reportSettingsProblem(Log.WARN, msg);
6778                        }
6779                    }
6780                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6781                            || (scanFlags&SCAN_BOOTING) != 0)) {
6782                        // If this is a system app, we can at least delete its
6783                        // current data so the application will still work.
6784                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6785                        if (ret >= 0) {
6786                            // TODO: Kill the processes first
6787                            // Old data gone!
6788                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6789                                    ? "System package " : "Third party package ";
6790                            String msg = prefix + pkg.packageName
6791                                    + " has changed from uid: "
6792                                    + currentUid + " to "
6793                                    + pkg.applicationInfo.uid + "; old data erased";
6794                            reportSettingsProblem(Log.WARN, msg);
6795                            recovered = true;
6796
6797                            // And now re-install the app.
6798                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6799                                    pkg.applicationInfo.seinfo);
6800                            if (ret == -1) {
6801                                // Ack should not happen!
6802                                msg = prefix + pkg.packageName
6803                                        + " could not have data directory re-created after delete.";
6804                                reportSettingsProblem(Log.WARN, msg);
6805                                throw new PackageManagerException(
6806                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6807                            }
6808                        }
6809                        if (!recovered) {
6810                            mHasSystemUidErrors = true;
6811                        }
6812                    } else if (!recovered) {
6813                        // If we allow this install to proceed, we will be broken.
6814                        // Abort, abort!
6815                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6816                                "scanPackageLI");
6817                    }
6818                    if (!recovered) {
6819                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6820                            + pkg.applicationInfo.uid + "/fs_"
6821                            + currentUid;
6822                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6823                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6824                        String msg = "Package " + pkg.packageName
6825                                + " has mismatched uid: "
6826                                + currentUid + " on disk, "
6827                                + pkg.applicationInfo.uid + " in settings";
6828                        // writer
6829                        synchronized (mPackages) {
6830                            mSettings.mReadMessages.append(msg);
6831                            mSettings.mReadMessages.append('\n');
6832                            uidError = true;
6833                            if (!pkgSetting.uidError) {
6834                                reportSettingsProblem(Log.ERROR, msg);
6835                            }
6836                        }
6837                    }
6838                }
6839                pkg.applicationInfo.dataDir = dataPath.getPath();
6840                if (mShouldRestoreconData) {
6841                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6842                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6843                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6844                }
6845            } else {
6846                if (DEBUG_PACKAGE_SCANNING) {
6847                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6848                        Log.v(TAG, "Want this data dir: " + dataPath);
6849                }
6850                //invoke installer to do the actual installation
6851                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6852                        pkg.applicationInfo.seinfo);
6853                if (ret < 0) {
6854                    // Error from installer
6855                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6856                            "Unable to create data dirs [errorCode=" + ret + "]");
6857                }
6858
6859                if (dataPath.exists()) {
6860                    pkg.applicationInfo.dataDir = dataPath.getPath();
6861                } else {
6862                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6863                    pkg.applicationInfo.dataDir = null;
6864                }
6865            }
6866
6867            pkgSetting.uidError = uidError;
6868        }
6869
6870        final String path = scanFile.getPath();
6871        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6872
6873        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6874            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6875
6876            // Some system apps still use directory structure for native libraries
6877            // in which case we might end up not detecting abi solely based on apk
6878            // structure. Try to detect abi based on directory structure.
6879            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6880                    pkg.applicationInfo.primaryCpuAbi == null) {
6881                setBundledAppAbisAndRoots(pkg, pkgSetting);
6882                setNativeLibraryPaths(pkg);
6883            }
6884
6885        } else {
6886            if ((scanFlags & SCAN_MOVE) != 0) {
6887                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6888                // but we already have this packages package info in the PackageSetting. We just
6889                // use that and derive the native library path based on the new codepath.
6890                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6891                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6892            }
6893
6894            // Set native library paths again. For moves, the path will be updated based on the
6895            // ABIs we've determined above. For non-moves, the path will be updated based on the
6896            // ABIs we determined during compilation, but the path will depend on the final
6897            // package path (after the rename away from the stage path).
6898            setNativeLibraryPaths(pkg);
6899        }
6900
6901        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6902        final int[] userIds = sUserManager.getUserIds();
6903        synchronized (mInstallLock) {
6904            // Make sure all user data directories are ready to roll; we're okay
6905            // if they already exist
6906            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6907                for (int userId : userIds) {
6908                    if (userId != 0) {
6909                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6910                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6911                                pkg.applicationInfo.seinfo);
6912                    }
6913                }
6914            }
6915
6916            // Create a native library symlink only if we have native libraries
6917            // and if the native libraries are 32 bit libraries. We do not provide
6918            // this symlink for 64 bit libraries.
6919            if (pkg.applicationInfo.primaryCpuAbi != null &&
6920                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6921                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6922                for (int userId : userIds) {
6923                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6924                            nativeLibPath, userId) < 0) {
6925                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6926                                "Failed linking native library dir (user=" + userId + ")");
6927                    }
6928                }
6929            }
6930        }
6931
6932        // This is a special case for the "system" package, where the ABI is
6933        // dictated by the zygote configuration (and init.rc). We should keep track
6934        // of this ABI so that we can deal with "normal" applications that run under
6935        // the same UID correctly.
6936        if (mPlatformPackage == pkg) {
6937            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6938                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6939        }
6940
6941        // If there's a mismatch between the abi-override in the package setting
6942        // and the abiOverride specified for the install. Warn about this because we
6943        // would've already compiled the app without taking the package setting into
6944        // account.
6945        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6946            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6947                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6948                        " for package: " + pkg.packageName);
6949            }
6950        }
6951
6952        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6953        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6954        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6955
6956        // Copy the derived override back to the parsed package, so that we can
6957        // update the package settings accordingly.
6958        pkg.cpuAbiOverride = cpuAbiOverride;
6959
6960        if (DEBUG_ABI_SELECTION) {
6961            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6962                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6963                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6964        }
6965
6966        // Push the derived path down into PackageSettings so we know what to
6967        // clean up at uninstall time.
6968        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6969
6970        if (DEBUG_ABI_SELECTION) {
6971            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6972                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6973                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6974        }
6975
6976        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6977            // We don't do this here during boot because we can do it all
6978            // at once after scanning all existing packages.
6979            //
6980            // We also do this *before* we perform dexopt on this package, so that
6981            // we can avoid redundant dexopts, and also to make sure we've got the
6982            // code and package path correct.
6983            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6984                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6985        }
6986
6987        if ((scanFlags & SCAN_NO_DEX) == 0) {
6988            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6989                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6990            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6991                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6992            }
6993        }
6994        if (mFactoryTest && pkg.requestedPermissions.contains(
6995                android.Manifest.permission.FACTORY_TEST)) {
6996            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6997        }
6998
6999        ArrayList<PackageParser.Package> clientLibPkgs = null;
7000
7001        // writer
7002        synchronized (mPackages) {
7003            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7004                // Only system apps can add new shared libraries.
7005                if (pkg.libraryNames != null) {
7006                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7007                        String name = pkg.libraryNames.get(i);
7008                        boolean allowed = false;
7009                        if (pkg.isUpdatedSystemApp()) {
7010                            // New library entries can only be added through the
7011                            // system image.  This is important to get rid of a lot
7012                            // of nasty edge cases: for example if we allowed a non-
7013                            // system update of the app to add a library, then uninstalling
7014                            // the update would make the library go away, and assumptions
7015                            // we made such as through app install filtering would now
7016                            // have allowed apps on the device which aren't compatible
7017                            // with it.  Better to just have the restriction here, be
7018                            // conservative, and create many fewer cases that can negatively
7019                            // impact the user experience.
7020                            final PackageSetting sysPs = mSettings
7021                                    .getDisabledSystemPkgLPr(pkg.packageName);
7022                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7023                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7024                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7025                                        allowed = true;
7026                                        allowed = true;
7027                                        break;
7028                                    }
7029                                }
7030                            }
7031                        } else {
7032                            allowed = true;
7033                        }
7034                        if (allowed) {
7035                            if (!mSharedLibraries.containsKey(name)) {
7036                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7037                            } else if (!name.equals(pkg.packageName)) {
7038                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7039                                        + name + " already exists; skipping");
7040                            }
7041                        } else {
7042                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7043                                    + name + " that is not declared on system image; skipping");
7044                        }
7045                    }
7046                    if ((scanFlags&SCAN_BOOTING) == 0) {
7047                        // If we are not booting, we need to update any applications
7048                        // that are clients of our shared library.  If we are booting,
7049                        // this will all be done once the scan is complete.
7050                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7051                    }
7052                }
7053            }
7054        }
7055
7056        // We also need to dexopt any apps that are dependent on this library.  Note that
7057        // if these fail, we should abort the install since installing the library will
7058        // result in some apps being broken.
7059        if (clientLibPkgs != null) {
7060            if ((scanFlags & SCAN_NO_DEX) == 0) {
7061                for (int i = 0; i < clientLibPkgs.size(); i++) {
7062                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7063                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7064                            null /* instruction sets */, forceDex,
7065                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7066                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7067                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7068                                "scanPackageLI failed to dexopt clientLibPkgs");
7069                    }
7070                }
7071            }
7072        }
7073
7074        // Also need to kill any apps that are dependent on the library.
7075        if (clientLibPkgs != null) {
7076            for (int i=0; i<clientLibPkgs.size(); i++) {
7077                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7078                killApplication(clientPkg.applicationInfo.packageName,
7079                        clientPkg.applicationInfo.uid, "update lib");
7080            }
7081        }
7082
7083        // Make sure we're not adding any bogus keyset info
7084        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7085        ksms.assertScannedPackageValid(pkg);
7086
7087        // writer
7088        synchronized (mPackages) {
7089            // We don't expect installation to fail beyond this point
7090
7091            // Add the new setting to mSettings
7092            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7093            // Add the new setting to mPackages
7094            mPackages.put(pkg.applicationInfo.packageName, pkg);
7095            // Make sure we don't accidentally delete its data.
7096            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7097            while (iter.hasNext()) {
7098                PackageCleanItem item = iter.next();
7099                if (pkgName.equals(item.packageName)) {
7100                    iter.remove();
7101                }
7102            }
7103
7104            // Take care of first install / last update times.
7105            if (currentTime != 0) {
7106                if (pkgSetting.firstInstallTime == 0) {
7107                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7108                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7109                    pkgSetting.lastUpdateTime = currentTime;
7110                }
7111            } else if (pkgSetting.firstInstallTime == 0) {
7112                // We need *something*.  Take time time stamp of the file.
7113                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7114            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7115                if (scanFileTime != pkgSetting.timeStamp) {
7116                    // A package on the system image has changed; consider this
7117                    // to be an update.
7118                    pkgSetting.lastUpdateTime = scanFileTime;
7119                }
7120            }
7121
7122            // Add the package's KeySets to the global KeySetManagerService
7123            ksms.addScannedPackageLPw(pkg);
7124
7125            int N = pkg.providers.size();
7126            StringBuilder r = null;
7127            int i;
7128            for (i=0; i<N; i++) {
7129                PackageParser.Provider p = pkg.providers.get(i);
7130                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7131                        p.info.processName, pkg.applicationInfo.uid);
7132                mProviders.addProvider(p);
7133                p.syncable = p.info.isSyncable;
7134                if (p.info.authority != null) {
7135                    String names[] = p.info.authority.split(";");
7136                    p.info.authority = null;
7137                    for (int j = 0; j < names.length; j++) {
7138                        if (j == 1 && p.syncable) {
7139                            // We only want the first authority for a provider to possibly be
7140                            // syncable, so if we already added this provider using a different
7141                            // authority clear the syncable flag. We copy the provider before
7142                            // changing it because the mProviders object contains a reference
7143                            // to a provider that we don't want to change.
7144                            // Only do this for the second authority since the resulting provider
7145                            // object can be the same for all future authorities for this provider.
7146                            p = new PackageParser.Provider(p);
7147                            p.syncable = false;
7148                        }
7149                        if (!mProvidersByAuthority.containsKey(names[j])) {
7150                            mProvidersByAuthority.put(names[j], p);
7151                            if (p.info.authority == null) {
7152                                p.info.authority = names[j];
7153                            } else {
7154                                p.info.authority = p.info.authority + ";" + names[j];
7155                            }
7156                            if (DEBUG_PACKAGE_SCANNING) {
7157                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7158                                    Log.d(TAG, "Registered content provider: " + names[j]
7159                                            + ", className = " + p.info.name + ", isSyncable = "
7160                                            + p.info.isSyncable);
7161                            }
7162                        } else {
7163                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7164                            Slog.w(TAG, "Skipping provider name " + names[j] +
7165                                    " (in package " + pkg.applicationInfo.packageName +
7166                                    "): name already used by "
7167                                    + ((other != null && other.getComponentName() != null)
7168                                            ? other.getComponentName().getPackageName() : "?"));
7169                        }
7170                    }
7171                }
7172                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7173                    if (r == null) {
7174                        r = new StringBuilder(256);
7175                    } else {
7176                        r.append(' ');
7177                    }
7178                    r.append(p.info.name);
7179                }
7180            }
7181            if (r != null) {
7182                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7183            }
7184
7185            N = pkg.services.size();
7186            r = null;
7187            for (i=0; i<N; i++) {
7188                PackageParser.Service s = pkg.services.get(i);
7189                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7190                        s.info.processName, pkg.applicationInfo.uid);
7191                mServices.addService(s);
7192                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7193                    if (r == null) {
7194                        r = new StringBuilder(256);
7195                    } else {
7196                        r.append(' ');
7197                    }
7198                    r.append(s.info.name);
7199                }
7200            }
7201            if (r != null) {
7202                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7203            }
7204
7205            N = pkg.receivers.size();
7206            r = null;
7207            for (i=0; i<N; i++) {
7208                PackageParser.Activity a = pkg.receivers.get(i);
7209                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7210                        a.info.processName, pkg.applicationInfo.uid);
7211                mReceivers.addActivity(a, "receiver");
7212                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7213                    if (r == null) {
7214                        r = new StringBuilder(256);
7215                    } else {
7216                        r.append(' ');
7217                    }
7218                    r.append(a.info.name);
7219                }
7220            }
7221            if (r != null) {
7222                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7223            }
7224
7225            N = pkg.activities.size();
7226            r = null;
7227            for (i=0; i<N; i++) {
7228                PackageParser.Activity a = pkg.activities.get(i);
7229                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7230                        a.info.processName, pkg.applicationInfo.uid);
7231                mActivities.addActivity(a, "activity");
7232                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7233                    if (r == null) {
7234                        r = new StringBuilder(256);
7235                    } else {
7236                        r.append(' ');
7237                    }
7238                    r.append(a.info.name);
7239                }
7240            }
7241            if (r != null) {
7242                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7243            }
7244
7245            N = pkg.permissionGroups.size();
7246            r = null;
7247            for (i=0; i<N; i++) {
7248                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7249                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7250                if (cur == null) {
7251                    mPermissionGroups.put(pg.info.name, pg);
7252                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7253                        if (r == null) {
7254                            r = new StringBuilder(256);
7255                        } else {
7256                            r.append(' ');
7257                        }
7258                        r.append(pg.info.name);
7259                    }
7260                } else {
7261                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7262                            + pg.info.packageName + " ignored: original from "
7263                            + cur.info.packageName);
7264                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7265                        if (r == null) {
7266                            r = new StringBuilder(256);
7267                        } else {
7268                            r.append(' ');
7269                        }
7270                        r.append("DUP:");
7271                        r.append(pg.info.name);
7272                    }
7273                }
7274            }
7275            if (r != null) {
7276                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7277            }
7278
7279            N = pkg.permissions.size();
7280            r = null;
7281            for (i=0; i<N; i++) {
7282                PackageParser.Permission p = pkg.permissions.get(i);
7283
7284                // Now that permission groups have a special meaning, we ignore permission
7285                // groups for legacy apps to prevent unexpected behavior. In particular,
7286                // permissions for one app being granted to someone just becuase they happen
7287                // to be in a group defined by another app (before this had no implications).
7288                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7289                    p.group = mPermissionGroups.get(p.info.group);
7290                    // Warn for a permission in an unknown group.
7291                    if (p.info.group != null && p.group == null) {
7292                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7293                                + p.info.packageName + " in an unknown group " + p.info.group);
7294                    }
7295                }
7296
7297                ArrayMap<String, BasePermission> permissionMap =
7298                        p.tree ? mSettings.mPermissionTrees
7299                                : mSettings.mPermissions;
7300                BasePermission bp = permissionMap.get(p.info.name);
7301
7302                // Allow system apps to redefine non-system permissions
7303                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7304                    final boolean currentOwnerIsSystem = (bp.perm != null
7305                            && isSystemApp(bp.perm.owner));
7306                    if (isSystemApp(p.owner)) {
7307                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7308                            // It's a built-in permission and no owner, take ownership now
7309                            bp.packageSetting = pkgSetting;
7310                            bp.perm = p;
7311                            bp.uid = pkg.applicationInfo.uid;
7312                            bp.sourcePackage = p.info.packageName;
7313                        } else if (!currentOwnerIsSystem) {
7314                            String msg = "New decl " + p.owner + " of permission  "
7315                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7316                            reportSettingsProblem(Log.WARN, msg);
7317                            bp = null;
7318                        }
7319                    }
7320                }
7321
7322                if (bp == null) {
7323                    bp = new BasePermission(p.info.name, p.info.packageName,
7324                            BasePermission.TYPE_NORMAL);
7325                    permissionMap.put(p.info.name, bp);
7326                }
7327
7328                if (bp.perm == null) {
7329                    if (bp.sourcePackage == null
7330                            || bp.sourcePackage.equals(p.info.packageName)) {
7331                        BasePermission tree = findPermissionTreeLP(p.info.name);
7332                        if (tree == null
7333                                || tree.sourcePackage.equals(p.info.packageName)) {
7334                            bp.packageSetting = pkgSetting;
7335                            bp.perm = p;
7336                            bp.uid = pkg.applicationInfo.uid;
7337                            bp.sourcePackage = p.info.packageName;
7338                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7339                                if (r == null) {
7340                                    r = new StringBuilder(256);
7341                                } else {
7342                                    r.append(' ');
7343                                }
7344                                r.append(p.info.name);
7345                            }
7346                        } else {
7347                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7348                                    + p.info.packageName + " ignored: base tree "
7349                                    + tree.name + " is from package "
7350                                    + tree.sourcePackage);
7351                        }
7352                    } else {
7353                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7354                                + p.info.packageName + " ignored: original from "
7355                                + bp.sourcePackage);
7356                    }
7357                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7358                    if (r == null) {
7359                        r = new StringBuilder(256);
7360                    } else {
7361                        r.append(' ');
7362                    }
7363                    r.append("DUP:");
7364                    r.append(p.info.name);
7365                }
7366                if (bp.perm == p) {
7367                    bp.protectionLevel = p.info.protectionLevel;
7368                }
7369            }
7370
7371            if (r != null) {
7372                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7373            }
7374
7375            N = pkg.instrumentation.size();
7376            r = null;
7377            for (i=0; i<N; i++) {
7378                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7379                a.info.packageName = pkg.applicationInfo.packageName;
7380                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7381                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7382                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7383                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7384                a.info.dataDir = pkg.applicationInfo.dataDir;
7385
7386                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7387                // need other information about the application, like the ABI and what not ?
7388                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7389                mInstrumentation.put(a.getComponentName(), a);
7390                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7391                    if (r == null) {
7392                        r = new StringBuilder(256);
7393                    } else {
7394                        r.append(' ');
7395                    }
7396                    r.append(a.info.name);
7397                }
7398            }
7399            if (r != null) {
7400                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7401            }
7402
7403            if (pkg.protectedBroadcasts != null) {
7404                N = pkg.protectedBroadcasts.size();
7405                for (i=0; i<N; i++) {
7406                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7407                }
7408            }
7409
7410            pkgSetting.setTimeStamp(scanFileTime);
7411
7412            // Create idmap files for pairs of (packages, overlay packages).
7413            // Note: "android", ie framework-res.apk, is handled by native layers.
7414            if (pkg.mOverlayTarget != null) {
7415                // This is an overlay package.
7416                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7417                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7418                        mOverlays.put(pkg.mOverlayTarget,
7419                                new ArrayMap<String, PackageParser.Package>());
7420                    }
7421                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7422                    map.put(pkg.packageName, pkg);
7423                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7424                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7425                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7426                                "scanPackageLI failed to createIdmap");
7427                    }
7428                }
7429            } else if (mOverlays.containsKey(pkg.packageName) &&
7430                    !pkg.packageName.equals("android")) {
7431                // This is a regular package, with one or more known overlay packages.
7432                createIdmapsForPackageLI(pkg);
7433            }
7434        }
7435
7436        return pkg;
7437    }
7438
7439    /**
7440     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7441     * is derived purely on the basis of the contents of {@code scanFile} and
7442     * {@code cpuAbiOverride}.
7443     *
7444     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7445     */
7446    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7447                                 String cpuAbiOverride, boolean extractLibs)
7448            throws PackageManagerException {
7449        // TODO: We can probably be smarter about this stuff. For installed apps,
7450        // we can calculate this information at install time once and for all. For
7451        // system apps, we can probably assume that this information doesn't change
7452        // after the first boot scan. As things stand, we do lots of unnecessary work.
7453
7454        // Give ourselves some initial paths; we'll come back for another
7455        // pass once we've determined ABI below.
7456        setNativeLibraryPaths(pkg);
7457
7458        // We would never need to extract libs for forward-locked and external packages,
7459        // since the container service will do it for us. We shouldn't attempt to
7460        // extract libs from system app when it was not updated.
7461        if (pkg.isForwardLocked() || isExternal(pkg) ||
7462            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7463            extractLibs = false;
7464        }
7465
7466        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7467        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7468
7469        NativeLibraryHelper.Handle handle = null;
7470        try {
7471            handle = NativeLibraryHelper.Handle.create(scanFile);
7472            // TODO(multiArch): This can be null for apps that didn't go through the
7473            // usual installation process. We can calculate it again, like we
7474            // do during install time.
7475            //
7476            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7477            // unnecessary.
7478            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7479
7480            // Null out the abis so that they can be recalculated.
7481            pkg.applicationInfo.primaryCpuAbi = null;
7482            pkg.applicationInfo.secondaryCpuAbi = null;
7483            if (isMultiArch(pkg.applicationInfo)) {
7484                // Warn if we've set an abiOverride for multi-lib packages..
7485                // By definition, we need to copy both 32 and 64 bit libraries for
7486                // such packages.
7487                if (pkg.cpuAbiOverride != null
7488                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7489                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7490                }
7491
7492                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7493                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7494                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7495                    if (extractLibs) {
7496                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7497                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7498                                useIsaSpecificSubdirs);
7499                    } else {
7500                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7501                    }
7502                }
7503
7504                maybeThrowExceptionForMultiArchCopy(
7505                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7506
7507                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7508                    if (extractLibs) {
7509                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7510                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7511                                useIsaSpecificSubdirs);
7512                    } else {
7513                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7514                    }
7515                }
7516
7517                maybeThrowExceptionForMultiArchCopy(
7518                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7519
7520                if (abi64 >= 0) {
7521                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7522                }
7523
7524                if (abi32 >= 0) {
7525                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7526                    if (abi64 >= 0) {
7527                        pkg.applicationInfo.secondaryCpuAbi = abi;
7528                    } else {
7529                        pkg.applicationInfo.primaryCpuAbi = abi;
7530                    }
7531                }
7532            } else {
7533                String[] abiList = (cpuAbiOverride != null) ?
7534                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7535
7536                // Enable gross and lame hacks for apps that are built with old
7537                // SDK tools. We must scan their APKs for renderscript bitcode and
7538                // not launch them if it's present. Don't bother checking on devices
7539                // that don't have 64 bit support.
7540                boolean needsRenderScriptOverride = false;
7541                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7542                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7543                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7544                    needsRenderScriptOverride = true;
7545                }
7546
7547                final int copyRet;
7548                if (extractLibs) {
7549                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7550                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7551                } else {
7552                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7553                }
7554
7555                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7556                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7557                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7558                }
7559
7560                if (copyRet >= 0) {
7561                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7562                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7563                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7564                } else if (needsRenderScriptOverride) {
7565                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7566                }
7567            }
7568        } catch (IOException ioe) {
7569            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7570        } finally {
7571            IoUtils.closeQuietly(handle);
7572        }
7573
7574        // Now that we've calculated the ABIs and determined if it's an internal app,
7575        // we will go ahead and populate the nativeLibraryPath.
7576        setNativeLibraryPaths(pkg);
7577    }
7578
7579    /**
7580     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7581     * i.e, so that all packages can be run inside a single process if required.
7582     *
7583     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7584     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7585     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7586     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7587     * updating a package that belongs to a shared user.
7588     *
7589     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7590     * adds unnecessary complexity.
7591     */
7592    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7593            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7594        String requiredInstructionSet = null;
7595        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7596            requiredInstructionSet = VMRuntime.getInstructionSet(
7597                     scannedPackage.applicationInfo.primaryCpuAbi);
7598        }
7599
7600        PackageSetting requirer = null;
7601        for (PackageSetting ps : packagesForUser) {
7602            // If packagesForUser contains scannedPackage, we skip it. This will happen
7603            // when scannedPackage is an update of an existing package. Without this check,
7604            // we will never be able to change the ABI of any package belonging to a shared
7605            // user, even if it's compatible with other packages.
7606            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7607                if (ps.primaryCpuAbiString == null) {
7608                    continue;
7609                }
7610
7611                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7612                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7613                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7614                    // this but there's not much we can do.
7615                    String errorMessage = "Instruction set mismatch, "
7616                            + ((requirer == null) ? "[caller]" : requirer)
7617                            + " requires " + requiredInstructionSet + " whereas " + ps
7618                            + " requires " + instructionSet;
7619                    Slog.w(TAG, errorMessage);
7620                }
7621
7622                if (requiredInstructionSet == null) {
7623                    requiredInstructionSet = instructionSet;
7624                    requirer = ps;
7625                }
7626            }
7627        }
7628
7629        if (requiredInstructionSet != null) {
7630            String adjustedAbi;
7631            if (requirer != null) {
7632                // requirer != null implies that either scannedPackage was null or that scannedPackage
7633                // did not require an ABI, in which case we have to adjust scannedPackage to match
7634                // the ABI of the set (which is the same as requirer's ABI)
7635                adjustedAbi = requirer.primaryCpuAbiString;
7636                if (scannedPackage != null) {
7637                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7638                }
7639            } else {
7640                // requirer == null implies that we're updating all ABIs in the set to
7641                // match scannedPackage.
7642                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7643            }
7644
7645            for (PackageSetting ps : packagesForUser) {
7646                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7647                    if (ps.primaryCpuAbiString != null) {
7648                        continue;
7649                    }
7650
7651                    ps.primaryCpuAbiString = adjustedAbi;
7652                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7653                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7654                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7655
7656                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7657                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7658                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7659                            ps.primaryCpuAbiString = null;
7660                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7661                            return;
7662                        } else {
7663                            mInstaller.rmdex(ps.codePathString,
7664                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7665                        }
7666                    }
7667                }
7668            }
7669        }
7670    }
7671
7672    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7673        synchronized (mPackages) {
7674            mResolverReplaced = true;
7675            // Set up information for custom user intent resolution activity.
7676            mResolveActivity.applicationInfo = pkg.applicationInfo;
7677            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7678            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7679            mResolveActivity.processName = pkg.applicationInfo.packageName;
7680            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7681            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7682                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7683            mResolveActivity.theme = 0;
7684            mResolveActivity.exported = true;
7685            mResolveActivity.enabled = true;
7686            mResolveInfo.activityInfo = mResolveActivity;
7687            mResolveInfo.priority = 0;
7688            mResolveInfo.preferredOrder = 0;
7689            mResolveInfo.match = 0;
7690            mResolveComponentName = mCustomResolverComponentName;
7691            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7692                    mResolveComponentName);
7693        }
7694    }
7695
7696    private static String calculateBundledApkRoot(final String codePathString) {
7697        final File codePath = new File(codePathString);
7698        final File codeRoot;
7699        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7700            codeRoot = Environment.getRootDirectory();
7701        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7702            codeRoot = Environment.getOemDirectory();
7703        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7704            codeRoot = Environment.getVendorDirectory();
7705        } else {
7706            // Unrecognized code path; take its top real segment as the apk root:
7707            // e.g. /something/app/blah.apk => /something
7708            try {
7709                File f = codePath.getCanonicalFile();
7710                File parent = f.getParentFile();    // non-null because codePath is a file
7711                File tmp;
7712                while ((tmp = parent.getParentFile()) != null) {
7713                    f = parent;
7714                    parent = tmp;
7715                }
7716                codeRoot = f;
7717                Slog.w(TAG, "Unrecognized code path "
7718                        + codePath + " - using " + codeRoot);
7719            } catch (IOException e) {
7720                // Can't canonicalize the code path -- shenanigans?
7721                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7722                return Environment.getRootDirectory().getPath();
7723            }
7724        }
7725        return codeRoot.getPath();
7726    }
7727
7728    /**
7729     * Derive and set the location of native libraries for the given package,
7730     * which varies depending on where and how the package was installed.
7731     */
7732    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7733        final ApplicationInfo info = pkg.applicationInfo;
7734        final String codePath = pkg.codePath;
7735        final File codeFile = new File(codePath);
7736        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7737        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7738
7739        info.nativeLibraryRootDir = null;
7740        info.nativeLibraryRootRequiresIsa = false;
7741        info.nativeLibraryDir = null;
7742        info.secondaryNativeLibraryDir = null;
7743
7744        if (isApkFile(codeFile)) {
7745            // Monolithic install
7746            if (bundledApp) {
7747                // If "/system/lib64/apkname" exists, assume that is the per-package
7748                // native library directory to use; otherwise use "/system/lib/apkname".
7749                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7750                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7751                        getPrimaryInstructionSet(info));
7752
7753                // This is a bundled system app so choose the path based on the ABI.
7754                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7755                // is just the default path.
7756                final String apkName = deriveCodePathName(codePath);
7757                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7758                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7759                        apkName).getAbsolutePath();
7760
7761                if (info.secondaryCpuAbi != null) {
7762                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7763                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7764                            secondaryLibDir, apkName).getAbsolutePath();
7765                }
7766            } else if (asecApp) {
7767                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7768                        .getAbsolutePath();
7769            } else {
7770                final String apkName = deriveCodePathName(codePath);
7771                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7772                        .getAbsolutePath();
7773            }
7774
7775            info.nativeLibraryRootRequiresIsa = false;
7776            info.nativeLibraryDir = info.nativeLibraryRootDir;
7777        } else {
7778            // Cluster install
7779            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7780            info.nativeLibraryRootRequiresIsa = true;
7781
7782            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7783                    getPrimaryInstructionSet(info)).getAbsolutePath();
7784
7785            if (info.secondaryCpuAbi != null) {
7786                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7787                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7788            }
7789        }
7790    }
7791
7792    /**
7793     * Calculate the abis and roots for a bundled app. These can uniquely
7794     * be determined from the contents of the system partition, i.e whether
7795     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7796     * of this information, and instead assume that the system was built
7797     * sensibly.
7798     */
7799    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7800                                           PackageSetting pkgSetting) {
7801        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7802
7803        // If "/system/lib64/apkname" exists, assume that is the per-package
7804        // native library directory to use; otherwise use "/system/lib/apkname".
7805        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7806        setBundledAppAbi(pkg, apkRoot, apkName);
7807        // pkgSetting might be null during rescan following uninstall of updates
7808        // to a bundled app, so accommodate that possibility.  The settings in
7809        // that case will be established later from the parsed package.
7810        //
7811        // If the settings aren't null, sync them up with what we've just derived.
7812        // note that apkRoot isn't stored in the package settings.
7813        if (pkgSetting != null) {
7814            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7815            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7816        }
7817    }
7818
7819    /**
7820     * Deduces the ABI of a bundled app and sets the relevant fields on the
7821     * parsed pkg object.
7822     *
7823     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7824     *        under which system libraries are installed.
7825     * @param apkName the name of the installed package.
7826     */
7827    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7828        final File codeFile = new File(pkg.codePath);
7829
7830        final boolean has64BitLibs;
7831        final boolean has32BitLibs;
7832        if (isApkFile(codeFile)) {
7833            // Monolithic install
7834            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7835            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7836        } else {
7837            // Cluster install
7838            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7839            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7840                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7841                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7842                has64BitLibs = (new File(rootDir, isa)).exists();
7843            } else {
7844                has64BitLibs = false;
7845            }
7846            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7847                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7848                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7849                has32BitLibs = (new File(rootDir, isa)).exists();
7850            } else {
7851                has32BitLibs = false;
7852            }
7853        }
7854
7855        if (has64BitLibs && !has32BitLibs) {
7856            // The package has 64 bit libs, but not 32 bit libs. Its primary
7857            // ABI should be 64 bit. We can safely assume here that the bundled
7858            // native libraries correspond to the most preferred ABI in the list.
7859
7860            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7861            pkg.applicationInfo.secondaryCpuAbi = null;
7862        } else if (has32BitLibs && !has64BitLibs) {
7863            // The package has 32 bit libs but not 64 bit libs. Its primary
7864            // ABI should be 32 bit.
7865
7866            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7867            pkg.applicationInfo.secondaryCpuAbi = null;
7868        } else if (has32BitLibs && has64BitLibs) {
7869            // The application has both 64 and 32 bit bundled libraries. We check
7870            // here that the app declares multiArch support, and warn if it doesn't.
7871            //
7872            // We will be lenient here and record both ABIs. The primary will be the
7873            // ABI that's higher on the list, i.e, a device that's configured to prefer
7874            // 64 bit apps will see a 64 bit primary ABI,
7875
7876            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7877                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7878            }
7879
7880            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7881                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7882                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7883            } else {
7884                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7885                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7886            }
7887        } else {
7888            pkg.applicationInfo.primaryCpuAbi = null;
7889            pkg.applicationInfo.secondaryCpuAbi = null;
7890        }
7891    }
7892
7893    private void killApplication(String pkgName, int appId, String reason) {
7894        // Request the ActivityManager to kill the process(only for existing packages)
7895        // so that we do not end up in a confused state while the user is still using the older
7896        // version of the application while the new one gets installed.
7897        IActivityManager am = ActivityManagerNative.getDefault();
7898        if (am != null) {
7899            try {
7900                am.killApplicationWithAppId(pkgName, appId, reason);
7901            } catch (RemoteException e) {
7902            }
7903        }
7904    }
7905
7906    void removePackageLI(PackageSetting ps, boolean chatty) {
7907        if (DEBUG_INSTALL) {
7908            if (chatty)
7909                Log.d(TAG, "Removing package " + ps.name);
7910        }
7911
7912        // writer
7913        synchronized (mPackages) {
7914            mPackages.remove(ps.name);
7915            final PackageParser.Package pkg = ps.pkg;
7916            if (pkg != null) {
7917                cleanPackageDataStructuresLILPw(pkg, chatty);
7918            }
7919        }
7920    }
7921
7922    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7923        if (DEBUG_INSTALL) {
7924            if (chatty)
7925                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7926        }
7927
7928        // writer
7929        synchronized (mPackages) {
7930            mPackages.remove(pkg.applicationInfo.packageName);
7931            cleanPackageDataStructuresLILPw(pkg, chatty);
7932        }
7933    }
7934
7935    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7936        int N = pkg.providers.size();
7937        StringBuilder r = null;
7938        int i;
7939        for (i=0; i<N; i++) {
7940            PackageParser.Provider p = pkg.providers.get(i);
7941            mProviders.removeProvider(p);
7942            if (p.info.authority == null) {
7943
7944                /* There was another ContentProvider with this authority when
7945                 * this app was installed so this authority is null,
7946                 * Ignore it as we don't have to unregister the provider.
7947                 */
7948                continue;
7949            }
7950            String names[] = p.info.authority.split(";");
7951            for (int j = 0; j < names.length; j++) {
7952                if (mProvidersByAuthority.get(names[j]) == p) {
7953                    mProvidersByAuthority.remove(names[j]);
7954                    if (DEBUG_REMOVE) {
7955                        if (chatty)
7956                            Log.d(TAG, "Unregistered content provider: " + names[j]
7957                                    + ", className = " + p.info.name + ", isSyncable = "
7958                                    + p.info.isSyncable);
7959                    }
7960                }
7961            }
7962            if (DEBUG_REMOVE && chatty) {
7963                if (r == null) {
7964                    r = new StringBuilder(256);
7965                } else {
7966                    r.append(' ');
7967                }
7968                r.append(p.info.name);
7969            }
7970        }
7971        if (r != null) {
7972            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7973        }
7974
7975        N = pkg.services.size();
7976        r = null;
7977        for (i=0; i<N; i++) {
7978            PackageParser.Service s = pkg.services.get(i);
7979            mServices.removeService(s);
7980            if (chatty) {
7981                if (r == null) {
7982                    r = new StringBuilder(256);
7983                } else {
7984                    r.append(' ');
7985                }
7986                r.append(s.info.name);
7987            }
7988        }
7989        if (r != null) {
7990            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7991        }
7992
7993        N = pkg.receivers.size();
7994        r = null;
7995        for (i=0; i<N; i++) {
7996            PackageParser.Activity a = pkg.receivers.get(i);
7997            mReceivers.removeActivity(a, "receiver");
7998            if (DEBUG_REMOVE && chatty) {
7999                if (r == null) {
8000                    r = new StringBuilder(256);
8001                } else {
8002                    r.append(' ');
8003                }
8004                r.append(a.info.name);
8005            }
8006        }
8007        if (r != null) {
8008            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8009        }
8010
8011        N = pkg.activities.size();
8012        r = null;
8013        for (i=0; i<N; i++) {
8014            PackageParser.Activity a = pkg.activities.get(i);
8015            mActivities.removeActivity(a, "activity");
8016            if (DEBUG_REMOVE && chatty) {
8017                if (r == null) {
8018                    r = new StringBuilder(256);
8019                } else {
8020                    r.append(' ');
8021                }
8022                r.append(a.info.name);
8023            }
8024        }
8025        if (r != null) {
8026            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8027        }
8028
8029        N = pkg.permissions.size();
8030        r = null;
8031        for (i=0; i<N; i++) {
8032            PackageParser.Permission p = pkg.permissions.get(i);
8033            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8034            if (bp == null) {
8035                bp = mSettings.mPermissionTrees.get(p.info.name);
8036            }
8037            if (bp != null && bp.perm == p) {
8038                bp.perm = null;
8039                if (DEBUG_REMOVE && chatty) {
8040                    if (r == null) {
8041                        r = new StringBuilder(256);
8042                    } else {
8043                        r.append(' ');
8044                    }
8045                    r.append(p.info.name);
8046                }
8047            }
8048            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8049                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8050                if (appOpPerms != null) {
8051                    appOpPerms.remove(pkg.packageName);
8052                }
8053            }
8054        }
8055        if (r != null) {
8056            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8057        }
8058
8059        N = pkg.requestedPermissions.size();
8060        r = null;
8061        for (i=0; i<N; i++) {
8062            String perm = pkg.requestedPermissions.get(i);
8063            BasePermission bp = mSettings.mPermissions.get(perm);
8064            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8065                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8066                if (appOpPerms != null) {
8067                    appOpPerms.remove(pkg.packageName);
8068                    if (appOpPerms.isEmpty()) {
8069                        mAppOpPermissionPackages.remove(perm);
8070                    }
8071                }
8072            }
8073        }
8074        if (r != null) {
8075            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8076        }
8077
8078        N = pkg.instrumentation.size();
8079        r = null;
8080        for (i=0; i<N; i++) {
8081            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8082            mInstrumentation.remove(a.getComponentName());
8083            if (DEBUG_REMOVE && chatty) {
8084                if (r == null) {
8085                    r = new StringBuilder(256);
8086                } else {
8087                    r.append(' ');
8088                }
8089                r.append(a.info.name);
8090            }
8091        }
8092        if (r != null) {
8093            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8094        }
8095
8096        r = null;
8097        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8098            // Only system apps can hold shared libraries.
8099            if (pkg.libraryNames != null) {
8100                for (i=0; i<pkg.libraryNames.size(); i++) {
8101                    String name = pkg.libraryNames.get(i);
8102                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8103                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8104                        mSharedLibraries.remove(name);
8105                        if (DEBUG_REMOVE && chatty) {
8106                            if (r == null) {
8107                                r = new StringBuilder(256);
8108                            } else {
8109                                r.append(' ');
8110                            }
8111                            r.append(name);
8112                        }
8113                    }
8114                }
8115            }
8116        }
8117        if (r != null) {
8118            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8119        }
8120    }
8121
8122    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8123        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8124            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8125                return true;
8126            }
8127        }
8128        return false;
8129    }
8130
8131    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8132    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8133    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8134
8135    private void updatePermissionsLPw(String changingPkg,
8136            PackageParser.Package pkgInfo, int flags) {
8137        // Make sure there are no dangling permission trees.
8138        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8139        while (it.hasNext()) {
8140            final BasePermission bp = it.next();
8141            if (bp.packageSetting == null) {
8142                // We may not yet have parsed the package, so just see if
8143                // we still know about its settings.
8144                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8145            }
8146            if (bp.packageSetting == null) {
8147                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8148                        + " from package " + bp.sourcePackage);
8149                it.remove();
8150            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8151                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8152                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8153                            + " from package " + bp.sourcePackage);
8154                    flags |= UPDATE_PERMISSIONS_ALL;
8155                    it.remove();
8156                }
8157            }
8158        }
8159
8160        // Make sure all dynamic permissions have been assigned to a package,
8161        // and make sure there are no dangling permissions.
8162        it = mSettings.mPermissions.values().iterator();
8163        while (it.hasNext()) {
8164            final BasePermission bp = it.next();
8165            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8166                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8167                        + bp.name + " pkg=" + bp.sourcePackage
8168                        + " info=" + bp.pendingInfo);
8169                if (bp.packageSetting == null && bp.pendingInfo != null) {
8170                    final BasePermission tree = findPermissionTreeLP(bp.name);
8171                    if (tree != null && tree.perm != null) {
8172                        bp.packageSetting = tree.packageSetting;
8173                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8174                                new PermissionInfo(bp.pendingInfo));
8175                        bp.perm.info.packageName = tree.perm.info.packageName;
8176                        bp.perm.info.name = bp.name;
8177                        bp.uid = tree.uid;
8178                    }
8179                }
8180            }
8181            if (bp.packageSetting == null) {
8182                // We may not yet have parsed the package, so just see if
8183                // we still know about its settings.
8184                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8185            }
8186            if (bp.packageSetting == null) {
8187                Slog.w(TAG, "Removing dangling permission: " + bp.name
8188                        + " from package " + bp.sourcePackage);
8189                it.remove();
8190            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8191                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8192                    Slog.i(TAG, "Removing old permission: " + bp.name
8193                            + " from package " + bp.sourcePackage);
8194                    flags |= UPDATE_PERMISSIONS_ALL;
8195                    it.remove();
8196                }
8197            }
8198        }
8199
8200        // Now update the permissions for all packages, in particular
8201        // replace the granted permissions of the system packages.
8202        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8203            for (PackageParser.Package pkg : mPackages.values()) {
8204                if (pkg != pkgInfo) {
8205                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8206                            changingPkg);
8207                }
8208            }
8209        }
8210
8211        if (pkgInfo != null) {
8212            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8213        }
8214    }
8215
8216    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8217            String packageOfInterest) {
8218        // IMPORTANT: There are two types of permissions: install and runtime.
8219        // Install time permissions are granted when the app is installed to
8220        // all device users and users added in the future. Runtime permissions
8221        // are granted at runtime explicitly to specific users. Normal and signature
8222        // protected permissions are install time permissions. Dangerous permissions
8223        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8224        // otherwise they are runtime permissions. This function does not manage
8225        // runtime permissions except for the case an app targeting Lollipop MR1
8226        // being upgraded to target a newer SDK, in which case dangerous permissions
8227        // are transformed from install time to runtime ones.
8228
8229        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8230        if (ps == null) {
8231            return;
8232        }
8233
8234        PermissionsState permissionsState = ps.getPermissionsState();
8235        PermissionsState origPermissions = permissionsState;
8236
8237        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8238
8239        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8240
8241        boolean changedInstallPermission = false;
8242
8243        if (replace) {
8244            ps.installPermissionsFixed = false;
8245            if (!ps.isSharedUser()) {
8246                origPermissions = new PermissionsState(permissionsState);
8247                permissionsState.reset();
8248            }
8249        }
8250
8251        permissionsState.setGlobalGids(mGlobalGids);
8252
8253        final int N = pkg.requestedPermissions.size();
8254        for (int i=0; i<N; i++) {
8255            final String name = pkg.requestedPermissions.get(i);
8256            final BasePermission bp = mSettings.mPermissions.get(name);
8257
8258            if (DEBUG_INSTALL) {
8259                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8260            }
8261
8262            if (bp == null || bp.packageSetting == null) {
8263                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8264                    Slog.w(TAG, "Unknown permission " + name
8265                            + " in package " + pkg.packageName);
8266                }
8267                continue;
8268            }
8269
8270            final String perm = bp.name;
8271            boolean allowedSig = false;
8272            int grant = GRANT_DENIED;
8273
8274            // Keep track of app op permissions.
8275            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8276                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8277                if (pkgs == null) {
8278                    pkgs = new ArraySet<>();
8279                    mAppOpPermissionPackages.put(bp.name, pkgs);
8280                }
8281                pkgs.add(pkg.packageName);
8282            }
8283
8284            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8285            switch (level) {
8286                case PermissionInfo.PROTECTION_NORMAL: {
8287                    // For all apps normal permissions are install time ones.
8288                    grant = GRANT_INSTALL;
8289                } break;
8290
8291                case PermissionInfo.PROTECTION_DANGEROUS: {
8292                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8293                        // For legacy apps dangerous permissions are install time ones.
8294                        grant = GRANT_INSTALL_LEGACY;
8295                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8296                        // For legacy apps that became modern, install becomes runtime.
8297                        grant = GRANT_UPGRADE;
8298                    } else {
8299                        // For modern apps keep runtime permissions unchanged.
8300                        grant = GRANT_RUNTIME;
8301                    }
8302                } break;
8303
8304                case PermissionInfo.PROTECTION_SIGNATURE: {
8305                    // For all apps signature permissions are install time ones.
8306                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8307                    if (allowedSig) {
8308                        grant = GRANT_INSTALL;
8309                    }
8310                } break;
8311            }
8312
8313            if (DEBUG_INSTALL) {
8314                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8315            }
8316
8317            if (grant != GRANT_DENIED) {
8318                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8319                    // If this is an existing, non-system package, then
8320                    // we can't add any new permissions to it.
8321                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8322                        // Except...  if this is a permission that was added
8323                        // to the platform (note: need to only do this when
8324                        // updating the platform).
8325                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8326                            grant = GRANT_DENIED;
8327                        }
8328                    }
8329                }
8330
8331                switch (grant) {
8332                    case GRANT_INSTALL: {
8333                        // Revoke this as runtime permission to handle the case of
8334                        // a runtime permission being downgraded to an install one.
8335                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8336                            if (origPermissions.getRuntimePermissionState(
8337                                    bp.name, userId) != null) {
8338                                // Revoke the runtime permission and clear the flags.
8339                                origPermissions.revokeRuntimePermission(bp, userId);
8340                                origPermissions.updatePermissionFlags(bp, userId,
8341                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8342                                // If we revoked a permission permission, we have to write.
8343                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8344                                        changedRuntimePermissionUserIds, userId);
8345                            }
8346                        }
8347                        // Grant an install permission.
8348                        if (permissionsState.grantInstallPermission(bp) !=
8349                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8350                            changedInstallPermission = true;
8351                        }
8352                    } break;
8353
8354                    case GRANT_INSTALL_LEGACY: {
8355                        // Grant an install permission.
8356                        if (permissionsState.grantInstallPermission(bp) !=
8357                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8358                            changedInstallPermission = true;
8359                        }
8360                    } break;
8361
8362                    case GRANT_RUNTIME: {
8363                        // Grant previously granted runtime permissions.
8364                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8365                            PermissionState permissionState = origPermissions
8366                                    .getRuntimePermissionState(bp.name, userId);
8367                            final int flags = permissionState != null
8368                                    ? permissionState.getFlags() : 0;
8369                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8370                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8371                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8372                                    // If we cannot put the permission as it was, we have to write.
8373                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8374                                            changedRuntimePermissionUserIds, userId);
8375                                }
8376                            }
8377                            // Propagate the permission flags.
8378                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8379                        }
8380                    } break;
8381
8382                    case GRANT_UPGRADE: {
8383                        // Grant runtime permissions for a previously held install permission.
8384                        PermissionState permissionState = origPermissions
8385                                .getInstallPermissionState(bp.name);
8386                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8387
8388                        if (origPermissions.revokeInstallPermission(bp)
8389                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8390                            // We will be transferring the permission flags, so clear them.
8391                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8392                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8393                            changedInstallPermission = true;
8394                        }
8395
8396                        // If the permission is not to be promoted to runtime we ignore it and
8397                        // also its other flags as they are not applicable to install permissions.
8398                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8399                            for (int userId : currentUserIds) {
8400                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8401                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8402                                    // Transfer the permission flags.
8403                                    permissionsState.updatePermissionFlags(bp, userId,
8404                                            flags, flags);
8405                                    // If we granted the permission, we have to write.
8406                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8407                                            changedRuntimePermissionUserIds, userId);
8408                                }
8409                            }
8410                        }
8411                    } break;
8412
8413                    default: {
8414                        if (packageOfInterest == null
8415                                || packageOfInterest.equals(pkg.packageName)) {
8416                            Slog.w(TAG, "Not granting permission " + perm
8417                                    + " to package " + pkg.packageName
8418                                    + " because it was previously installed without");
8419                        }
8420                    } break;
8421                }
8422            } else {
8423                if (permissionsState.revokeInstallPermission(bp) !=
8424                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8425                    // Also drop the permission flags.
8426                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8427                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8428                    changedInstallPermission = true;
8429                    Slog.i(TAG, "Un-granting permission " + perm
8430                            + " from package " + pkg.packageName
8431                            + " (protectionLevel=" + bp.protectionLevel
8432                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8433                            + ")");
8434                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8435                    // Don't print warning for app op permissions, since it is fine for them
8436                    // not to be granted, there is a UI for the user to decide.
8437                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8438                        Slog.w(TAG, "Not granting permission " + perm
8439                                + " to package " + pkg.packageName
8440                                + " (protectionLevel=" + bp.protectionLevel
8441                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8442                                + ")");
8443                    }
8444                }
8445            }
8446        }
8447
8448        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8449                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8450            // This is the first that we have heard about this package, so the
8451            // permissions we have now selected are fixed until explicitly
8452            // changed.
8453            ps.installPermissionsFixed = true;
8454        }
8455
8456        // Persist the runtime permissions state for users with changes.
8457        for (int userId : changedRuntimePermissionUserIds) {
8458            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8459        }
8460    }
8461
8462    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8463        boolean allowed = false;
8464        final int NP = PackageParser.NEW_PERMISSIONS.length;
8465        for (int ip=0; ip<NP; ip++) {
8466            final PackageParser.NewPermissionInfo npi
8467                    = PackageParser.NEW_PERMISSIONS[ip];
8468            if (npi.name.equals(perm)
8469                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8470                allowed = true;
8471                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8472                        + pkg.packageName);
8473                break;
8474            }
8475        }
8476        return allowed;
8477    }
8478
8479    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8480            BasePermission bp, PermissionsState origPermissions) {
8481        boolean allowed;
8482        allowed = (compareSignatures(
8483                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8484                        == PackageManager.SIGNATURE_MATCH)
8485                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8486                        == PackageManager.SIGNATURE_MATCH);
8487        if (!allowed && (bp.protectionLevel
8488                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8489            if (isSystemApp(pkg)) {
8490                // For updated system applications, a system permission
8491                // is granted only if it had been defined by the original application.
8492                if (pkg.isUpdatedSystemApp()) {
8493                    final PackageSetting sysPs = mSettings
8494                            .getDisabledSystemPkgLPr(pkg.packageName);
8495                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8496                        // If the original was granted this permission, we take
8497                        // that grant decision as read and propagate it to the
8498                        // update.
8499                        if (sysPs.isPrivileged()) {
8500                            allowed = true;
8501                        }
8502                    } else {
8503                        // The system apk may have been updated with an older
8504                        // version of the one on the data partition, but which
8505                        // granted a new system permission that it didn't have
8506                        // before.  In this case we do want to allow the app to
8507                        // now get the new permission if the ancestral apk is
8508                        // privileged to get it.
8509                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8510                            for (int j=0;
8511                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8512                                if (perm.equals(
8513                                        sysPs.pkg.requestedPermissions.get(j))) {
8514                                    allowed = true;
8515                                    break;
8516                                }
8517                            }
8518                        }
8519                    }
8520                } else {
8521                    allowed = isPrivilegedApp(pkg);
8522                }
8523            }
8524        }
8525        if (!allowed) {
8526            if (!allowed && (bp.protectionLevel
8527                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8528                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8529                // If this was a previously normal/dangerous permission that got moved
8530                // to a system permission as part of the runtime permission redesign, then
8531                // we still want to blindly grant it to old apps.
8532                allowed = true;
8533            }
8534            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8535                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8536                // If this permission is to be granted to the system installer and
8537                // this app is an installer, then it gets the permission.
8538                allowed = true;
8539            }
8540            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8541                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8542                // If this permission is to be granted to the system verifier and
8543                // this app is a verifier, then it gets the permission.
8544                allowed = true;
8545            }
8546            if (!allowed && (bp.protectionLevel
8547                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8548                    && isSystemApp(pkg)) {
8549                // Any pre-installed system app is allowed to get this permission.
8550                allowed = true;
8551            }
8552            if (!allowed && (bp.protectionLevel
8553                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8554                // For development permissions, a development permission
8555                // is granted only if it was already granted.
8556                allowed = origPermissions.hasInstallPermission(perm);
8557            }
8558        }
8559        return allowed;
8560    }
8561
8562    final class ActivityIntentResolver
8563            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8564        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8565                boolean defaultOnly, int userId) {
8566            if (!sUserManager.exists(userId)) return null;
8567            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8568            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8569        }
8570
8571        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8572                int userId) {
8573            if (!sUserManager.exists(userId)) return null;
8574            mFlags = flags;
8575            return super.queryIntent(intent, resolvedType,
8576                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8577        }
8578
8579        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8580                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8581            if (!sUserManager.exists(userId)) return null;
8582            if (packageActivities == null) {
8583                return null;
8584            }
8585            mFlags = flags;
8586            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8587            final int N = packageActivities.size();
8588            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8589                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8590
8591            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8592            for (int i = 0; i < N; ++i) {
8593                intentFilters = packageActivities.get(i).intents;
8594                if (intentFilters != null && intentFilters.size() > 0) {
8595                    PackageParser.ActivityIntentInfo[] array =
8596                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8597                    intentFilters.toArray(array);
8598                    listCut.add(array);
8599                }
8600            }
8601            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8602        }
8603
8604        public final void addActivity(PackageParser.Activity a, String type) {
8605            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8606            mActivities.put(a.getComponentName(), a);
8607            if (DEBUG_SHOW_INFO)
8608                Log.v(
8609                TAG, "  " + type + " " +
8610                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8611            if (DEBUG_SHOW_INFO)
8612                Log.v(TAG, "    Class=" + a.info.name);
8613            final int NI = a.intents.size();
8614            for (int j=0; j<NI; j++) {
8615                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8616                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8617                    intent.setPriority(0);
8618                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8619                            + a.className + " with priority > 0, forcing to 0");
8620                }
8621                if (DEBUG_SHOW_INFO) {
8622                    Log.v(TAG, "    IntentFilter:");
8623                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8624                }
8625                if (!intent.debugCheck()) {
8626                    Log.w(TAG, "==> For Activity " + a.info.name);
8627                }
8628                addFilter(intent);
8629            }
8630        }
8631
8632        public final void removeActivity(PackageParser.Activity a, String type) {
8633            mActivities.remove(a.getComponentName());
8634            if (DEBUG_SHOW_INFO) {
8635                Log.v(TAG, "  " + type + " "
8636                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8637                                : a.info.name) + ":");
8638                Log.v(TAG, "    Class=" + a.info.name);
8639            }
8640            final int NI = a.intents.size();
8641            for (int j=0; j<NI; j++) {
8642                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8643                if (DEBUG_SHOW_INFO) {
8644                    Log.v(TAG, "    IntentFilter:");
8645                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8646                }
8647                removeFilter(intent);
8648            }
8649        }
8650
8651        @Override
8652        protected boolean allowFilterResult(
8653                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8654            ActivityInfo filterAi = filter.activity.info;
8655            for (int i=dest.size()-1; i>=0; i--) {
8656                ActivityInfo destAi = dest.get(i).activityInfo;
8657                if (destAi.name == filterAi.name
8658                        && destAi.packageName == filterAi.packageName) {
8659                    return false;
8660                }
8661            }
8662            return true;
8663        }
8664
8665        @Override
8666        protected ActivityIntentInfo[] newArray(int size) {
8667            return new ActivityIntentInfo[size];
8668        }
8669
8670        @Override
8671        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8672            if (!sUserManager.exists(userId)) return true;
8673            PackageParser.Package p = filter.activity.owner;
8674            if (p != null) {
8675                PackageSetting ps = (PackageSetting)p.mExtras;
8676                if (ps != null) {
8677                    // System apps are never considered stopped for purposes of
8678                    // filtering, because there may be no way for the user to
8679                    // actually re-launch them.
8680                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8681                            && ps.getStopped(userId);
8682                }
8683            }
8684            return false;
8685        }
8686
8687        @Override
8688        protected boolean isPackageForFilter(String packageName,
8689                PackageParser.ActivityIntentInfo info) {
8690            return packageName.equals(info.activity.owner.packageName);
8691        }
8692
8693        @Override
8694        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8695                int match, int userId) {
8696            if (!sUserManager.exists(userId)) return null;
8697            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8698                return null;
8699            }
8700            final PackageParser.Activity activity = info.activity;
8701            if (mSafeMode && (activity.info.applicationInfo.flags
8702                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8703                return null;
8704            }
8705            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8706            if (ps == null) {
8707                return null;
8708            }
8709            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8710                    ps.readUserState(userId), userId);
8711            if (ai == null) {
8712                return null;
8713            }
8714            final ResolveInfo res = new ResolveInfo();
8715            res.activityInfo = ai;
8716            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8717                res.filter = info;
8718            }
8719            if (info != null) {
8720                res.handleAllWebDataURI = info.handleAllWebDataURI();
8721            }
8722            res.priority = info.getPriority();
8723            res.preferredOrder = activity.owner.mPreferredOrder;
8724            //System.out.println("Result: " + res.activityInfo.className +
8725            //                   " = " + res.priority);
8726            res.match = match;
8727            res.isDefault = info.hasDefault;
8728            res.labelRes = info.labelRes;
8729            res.nonLocalizedLabel = info.nonLocalizedLabel;
8730            if (userNeedsBadging(userId)) {
8731                res.noResourceId = true;
8732            } else {
8733                res.icon = info.icon;
8734            }
8735            res.iconResourceId = info.icon;
8736            res.system = res.activityInfo.applicationInfo.isSystemApp();
8737            return res;
8738        }
8739
8740        @Override
8741        protected void sortResults(List<ResolveInfo> results) {
8742            Collections.sort(results, mResolvePrioritySorter);
8743        }
8744
8745        @Override
8746        protected void dumpFilter(PrintWriter out, String prefix,
8747                PackageParser.ActivityIntentInfo filter) {
8748            out.print(prefix); out.print(
8749                    Integer.toHexString(System.identityHashCode(filter.activity)));
8750                    out.print(' ');
8751                    filter.activity.printComponentShortName(out);
8752                    out.print(" filter ");
8753                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8754        }
8755
8756        @Override
8757        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8758            return filter.activity;
8759        }
8760
8761        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8762            PackageParser.Activity activity = (PackageParser.Activity)label;
8763            out.print(prefix); out.print(
8764                    Integer.toHexString(System.identityHashCode(activity)));
8765                    out.print(' ');
8766                    activity.printComponentShortName(out);
8767            if (count > 1) {
8768                out.print(" ("); out.print(count); out.print(" filters)");
8769            }
8770            out.println();
8771        }
8772
8773//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8774//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8775//            final List<ResolveInfo> retList = Lists.newArrayList();
8776//            while (i.hasNext()) {
8777//                final ResolveInfo resolveInfo = i.next();
8778//                if (isEnabledLP(resolveInfo.activityInfo)) {
8779//                    retList.add(resolveInfo);
8780//                }
8781//            }
8782//            return retList;
8783//        }
8784
8785        // Keys are String (activity class name), values are Activity.
8786        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8787                = new ArrayMap<ComponentName, PackageParser.Activity>();
8788        private int mFlags;
8789    }
8790
8791    private final class ServiceIntentResolver
8792            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8793        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8794                boolean defaultOnly, int userId) {
8795            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8796            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8797        }
8798
8799        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8800                int userId) {
8801            if (!sUserManager.exists(userId)) return null;
8802            mFlags = flags;
8803            return super.queryIntent(intent, resolvedType,
8804                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8805        }
8806
8807        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8808                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8809            if (!sUserManager.exists(userId)) return null;
8810            if (packageServices == null) {
8811                return null;
8812            }
8813            mFlags = flags;
8814            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8815            final int N = packageServices.size();
8816            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8817                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8818
8819            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8820            for (int i = 0; i < N; ++i) {
8821                intentFilters = packageServices.get(i).intents;
8822                if (intentFilters != null && intentFilters.size() > 0) {
8823                    PackageParser.ServiceIntentInfo[] array =
8824                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8825                    intentFilters.toArray(array);
8826                    listCut.add(array);
8827                }
8828            }
8829            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8830        }
8831
8832        public final void addService(PackageParser.Service s) {
8833            mServices.put(s.getComponentName(), s);
8834            if (DEBUG_SHOW_INFO) {
8835                Log.v(TAG, "  "
8836                        + (s.info.nonLocalizedLabel != null
8837                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8838                Log.v(TAG, "    Class=" + s.info.name);
8839            }
8840            final int NI = s.intents.size();
8841            int j;
8842            for (j=0; j<NI; j++) {
8843                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8844                if (DEBUG_SHOW_INFO) {
8845                    Log.v(TAG, "    IntentFilter:");
8846                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8847                }
8848                if (!intent.debugCheck()) {
8849                    Log.w(TAG, "==> For Service " + s.info.name);
8850                }
8851                addFilter(intent);
8852            }
8853        }
8854
8855        public final void removeService(PackageParser.Service s) {
8856            mServices.remove(s.getComponentName());
8857            if (DEBUG_SHOW_INFO) {
8858                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8859                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8860                Log.v(TAG, "    Class=" + s.info.name);
8861            }
8862            final int NI = s.intents.size();
8863            int j;
8864            for (j=0; j<NI; j++) {
8865                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8866                if (DEBUG_SHOW_INFO) {
8867                    Log.v(TAG, "    IntentFilter:");
8868                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8869                }
8870                removeFilter(intent);
8871            }
8872        }
8873
8874        @Override
8875        protected boolean allowFilterResult(
8876                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8877            ServiceInfo filterSi = filter.service.info;
8878            for (int i=dest.size()-1; i>=0; i--) {
8879                ServiceInfo destAi = dest.get(i).serviceInfo;
8880                if (destAi.name == filterSi.name
8881                        && destAi.packageName == filterSi.packageName) {
8882                    return false;
8883                }
8884            }
8885            return true;
8886        }
8887
8888        @Override
8889        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8890            return new PackageParser.ServiceIntentInfo[size];
8891        }
8892
8893        @Override
8894        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8895            if (!sUserManager.exists(userId)) return true;
8896            PackageParser.Package p = filter.service.owner;
8897            if (p != null) {
8898                PackageSetting ps = (PackageSetting)p.mExtras;
8899                if (ps != null) {
8900                    // System apps are never considered stopped for purposes of
8901                    // filtering, because there may be no way for the user to
8902                    // actually re-launch them.
8903                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8904                            && ps.getStopped(userId);
8905                }
8906            }
8907            return false;
8908        }
8909
8910        @Override
8911        protected boolean isPackageForFilter(String packageName,
8912                PackageParser.ServiceIntentInfo info) {
8913            return packageName.equals(info.service.owner.packageName);
8914        }
8915
8916        @Override
8917        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8918                int match, int userId) {
8919            if (!sUserManager.exists(userId)) return null;
8920            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8921            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8922                return null;
8923            }
8924            final PackageParser.Service service = info.service;
8925            if (mSafeMode && (service.info.applicationInfo.flags
8926                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8927                return null;
8928            }
8929            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8930            if (ps == null) {
8931                return null;
8932            }
8933            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8934                    ps.readUserState(userId), userId);
8935            if (si == null) {
8936                return null;
8937            }
8938            final ResolveInfo res = new ResolveInfo();
8939            res.serviceInfo = si;
8940            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8941                res.filter = filter;
8942            }
8943            res.priority = info.getPriority();
8944            res.preferredOrder = service.owner.mPreferredOrder;
8945            res.match = match;
8946            res.isDefault = info.hasDefault;
8947            res.labelRes = info.labelRes;
8948            res.nonLocalizedLabel = info.nonLocalizedLabel;
8949            res.icon = info.icon;
8950            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8951            return res;
8952        }
8953
8954        @Override
8955        protected void sortResults(List<ResolveInfo> results) {
8956            Collections.sort(results, mResolvePrioritySorter);
8957        }
8958
8959        @Override
8960        protected void dumpFilter(PrintWriter out, String prefix,
8961                PackageParser.ServiceIntentInfo filter) {
8962            out.print(prefix); out.print(
8963                    Integer.toHexString(System.identityHashCode(filter.service)));
8964                    out.print(' ');
8965                    filter.service.printComponentShortName(out);
8966                    out.print(" filter ");
8967                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8968        }
8969
8970        @Override
8971        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8972            return filter.service;
8973        }
8974
8975        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8976            PackageParser.Service service = (PackageParser.Service)label;
8977            out.print(prefix); out.print(
8978                    Integer.toHexString(System.identityHashCode(service)));
8979                    out.print(' ');
8980                    service.printComponentShortName(out);
8981            if (count > 1) {
8982                out.print(" ("); out.print(count); out.print(" filters)");
8983            }
8984            out.println();
8985        }
8986
8987//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8988//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8989//            final List<ResolveInfo> retList = Lists.newArrayList();
8990//            while (i.hasNext()) {
8991//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8992//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8993//                    retList.add(resolveInfo);
8994//                }
8995//            }
8996//            return retList;
8997//        }
8998
8999        // Keys are String (activity class name), values are Activity.
9000        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9001                = new ArrayMap<ComponentName, PackageParser.Service>();
9002        private int mFlags;
9003    };
9004
9005    private final class ProviderIntentResolver
9006            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9007        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9008                boolean defaultOnly, int userId) {
9009            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9010            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9011        }
9012
9013        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9014                int userId) {
9015            if (!sUserManager.exists(userId))
9016                return null;
9017            mFlags = flags;
9018            return super.queryIntent(intent, resolvedType,
9019                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9020        }
9021
9022        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9023                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9024            if (!sUserManager.exists(userId))
9025                return null;
9026            if (packageProviders == null) {
9027                return null;
9028            }
9029            mFlags = flags;
9030            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9031            final int N = packageProviders.size();
9032            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9033                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9034
9035            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9036            for (int i = 0; i < N; ++i) {
9037                intentFilters = packageProviders.get(i).intents;
9038                if (intentFilters != null && intentFilters.size() > 0) {
9039                    PackageParser.ProviderIntentInfo[] array =
9040                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9041                    intentFilters.toArray(array);
9042                    listCut.add(array);
9043                }
9044            }
9045            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9046        }
9047
9048        public final void addProvider(PackageParser.Provider p) {
9049            if (mProviders.containsKey(p.getComponentName())) {
9050                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9051                return;
9052            }
9053
9054            mProviders.put(p.getComponentName(), p);
9055            if (DEBUG_SHOW_INFO) {
9056                Log.v(TAG, "  "
9057                        + (p.info.nonLocalizedLabel != null
9058                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9059                Log.v(TAG, "    Class=" + p.info.name);
9060            }
9061            final int NI = p.intents.size();
9062            int j;
9063            for (j = 0; j < NI; j++) {
9064                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9065                if (DEBUG_SHOW_INFO) {
9066                    Log.v(TAG, "    IntentFilter:");
9067                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9068                }
9069                if (!intent.debugCheck()) {
9070                    Log.w(TAG, "==> For Provider " + p.info.name);
9071                }
9072                addFilter(intent);
9073            }
9074        }
9075
9076        public final void removeProvider(PackageParser.Provider p) {
9077            mProviders.remove(p.getComponentName());
9078            if (DEBUG_SHOW_INFO) {
9079                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9080                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9081                Log.v(TAG, "    Class=" + p.info.name);
9082            }
9083            final int NI = p.intents.size();
9084            int j;
9085            for (j = 0; j < NI; j++) {
9086                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9087                if (DEBUG_SHOW_INFO) {
9088                    Log.v(TAG, "    IntentFilter:");
9089                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9090                }
9091                removeFilter(intent);
9092            }
9093        }
9094
9095        @Override
9096        protected boolean allowFilterResult(
9097                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9098            ProviderInfo filterPi = filter.provider.info;
9099            for (int i = dest.size() - 1; i >= 0; i--) {
9100                ProviderInfo destPi = dest.get(i).providerInfo;
9101                if (destPi.name == filterPi.name
9102                        && destPi.packageName == filterPi.packageName) {
9103                    return false;
9104                }
9105            }
9106            return true;
9107        }
9108
9109        @Override
9110        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9111            return new PackageParser.ProviderIntentInfo[size];
9112        }
9113
9114        @Override
9115        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9116            if (!sUserManager.exists(userId))
9117                return true;
9118            PackageParser.Package p = filter.provider.owner;
9119            if (p != null) {
9120                PackageSetting ps = (PackageSetting) p.mExtras;
9121                if (ps != null) {
9122                    // System apps are never considered stopped for purposes of
9123                    // filtering, because there may be no way for the user to
9124                    // actually re-launch them.
9125                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9126                            && ps.getStopped(userId);
9127                }
9128            }
9129            return false;
9130        }
9131
9132        @Override
9133        protected boolean isPackageForFilter(String packageName,
9134                PackageParser.ProviderIntentInfo info) {
9135            return packageName.equals(info.provider.owner.packageName);
9136        }
9137
9138        @Override
9139        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9140                int match, int userId) {
9141            if (!sUserManager.exists(userId))
9142                return null;
9143            final PackageParser.ProviderIntentInfo info = filter;
9144            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9145                return null;
9146            }
9147            final PackageParser.Provider provider = info.provider;
9148            if (mSafeMode && (provider.info.applicationInfo.flags
9149                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9150                return null;
9151            }
9152            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9153            if (ps == null) {
9154                return null;
9155            }
9156            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9157                    ps.readUserState(userId), userId);
9158            if (pi == null) {
9159                return null;
9160            }
9161            final ResolveInfo res = new ResolveInfo();
9162            res.providerInfo = pi;
9163            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9164                res.filter = filter;
9165            }
9166            res.priority = info.getPriority();
9167            res.preferredOrder = provider.owner.mPreferredOrder;
9168            res.match = match;
9169            res.isDefault = info.hasDefault;
9170            res.labelRes = info.labelRes;
9171            res.nonLocalizedLabel = info.nonLocalizedLabel;
9172            res.icon = info.icon;
9173            res.system = res.providerInfo.applicationInfo.isSystemApp();
9174            return res;
9175        }
9176
9177        @Override
9178        protected void sortResults(List<ResolveInfo> results) {
9179            Collections.sort(results, mResolvePrioritySorter);
9180        }
9181
9182        @Override
9183        protected void dumpFilter(PrintWriter out, String prefix,
9184                PackageParser.ProviderIntentInfo filter) {
9185            out.print(prefix);
9186            out.print(
9187                    Integer.toHexString(System.identityHashCode(filter.provider)));
9188            out.print(' ');
9189            filter.provider.printComponentShortName(out);
9190            out.print(" filter ");
9191            out.println(Integer.toHexString(System.identityHashCode(filter)));
9192        }
9193
9194        @Override
9195        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9196            return filter.provider;
9197        }
9198
9199        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9200            PackageParser.Provider provider = (PackageParser.Provider)label;
9201            out.print(prefix); out.print(
9202                    Integer.toHexString(System.identityHashCode(provider)));
9203                    out.print(' ');
9204                    provider.printComponentShortName(out);
9205            if (count > 1) {
9206                out.print(" ("); out.print(count); out.print(" filters)");
9207            }
9208            out.println();
9209        }
9210
9211        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9212                = new ArrayMap<ComponentName, PackageParser.Provider>();
9213        private int mFlags;
9214    };
9215
9216    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9217            new Comparator<ResolveInfo>() {
9218        public int compare(ResolveInfo r1, ResolveInfo r2) {
9219            int v1 = r1.priority;
9220            int v2 = r2.priority;
9221            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9222            if (v1 != v2) {
9223                return (v1 > v2) ? -1 : 1;
9224            }
9225            v1 = r1.preferredOrder;
9226            v2 = r2.preferredOrder;
9227            if (v1 != v2) {
9228                return (v1 > v2) ? -1 : 1;
9229            }
9230            if (r1.isDefault != r2.isDefault) {
9231                return r1.isDefault ? -1 : 1;
9232            }
9233            v1 = r1.match;
9234            v2 = r2.match;
9235            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9236            if (v1 != v2) {
9237                return (v1 > v2) ? -1 : 1;
9238            }
9239            if (r1.system != r2.system) {
9240                return r1.system ? -1 : 1;
9241            }
9242            return 0;
9243        }
9244    };
9245
9246    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9247            new Comparator<ProviderInfo>() {
9248        public int compare(ProviderInfo p1, ProviderInfo p2) {
9249            final int v1 = p1.initOrder;
9250            final int v2 = p2.initOrder;
9251            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9252        }
9253    };
9254
9255    final void sendPackageBroadcast(final String action, final String pkg,
9256            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9257            final int[] userIds) {
9258        mHandler.post(new Runnable() {
9259            @Override
9260            public void run() {
9261                try {
9262                    final IActivityManager am = ActivityManagerNative.getDefault();
9263                    if (am == null) return;
9264                    final int[] resolvedUserIds;
9265                    if (userIds == null) {
9266                        resolvedUserIds = am.getRunningUserIds();
9267                    } else {
9268                        resolvedUserIds = userIds;
9269                    }
9270                    for (int id : resolvedUserIds) {
9271                        final Intent intent = new Intent(action,
9272                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9273                        if (extras != null) {
9274                            intent.putExtras(extras);
9275                        }
9276                        if (targetPkg != null) {
9277                            intent.setPackage(targetPkg);
9278                        }
9279                        // Modify the UID when posting to other users
9280                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9281                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9282                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9283                            intent.putExtra(Intent.EXTRA_UID, uid);
9284                        }
9285                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9286                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9287                        if (DEBUG_BROADCASTS) {
9288                            RuntimeException here = new RuntimeException("here");
9289                            here.fillInStackTrace();
9290                            Slog.d(TAG, "Sending to user " + id + ": "
9291                                    + intent.toShortString(false, true, false, false)
9292                                    + " " + intent.getExtras(), here);
9293                        }
9294                        am.broadcastIntent(null, intent, null, finishedReceiver,
9295                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9296                                null, finishedReceiver != null, false, id);
9297                    }
9298                } catch (RemoteException ex) {
9299                }
9300            }
9301        });
9302    }
9303
9304    /**
9305     * Check if the external storage media is available. This is true if there
9306     * is a mounted external storage medium or if the external storage is
9307     * emulated.
9308     */
9309    private boolean isExternalMediaAvailable() {
9310        return mMediaMounted || Environment.isExternalStorageEmulated();
9311    }
9312
9313    @Override
9314    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9315        // writer
9316        synchronized (mPackages) {
9317            if (!isExternalMediaAvailable()) {
9318                // If the external storage is no longer mounted at this point,
9319                // the caller may not have been able to delete all of this
9320                // packages files and can not delete any more.  Bail.
9321                return null;
9322            }
9323            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9324            if (lastPackage != null) {
9325                pkgs.remove(lastPackage);
9326            }
9327            if (pkgs.size() > 0) {
9328                return pkgs.get(0);
9329            }
9330        }
9331        return null;
9332    }
9333
9334    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9335        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9336                userId, andCode ? 1 : 0, packageName);
9337        if (mSystemReady) {
9338            msg.sendToTarget();
9339        } else {
9340            if (mPostSystemReadyMessages == null) {
9341                mPostSystemReadyMessages = new ArrayList<>();
9342            }
9343            mPostSystemReadyMessages.add(msg);
9344        }
9345    }
9346
9347    void startCleaningPackages() {
9348        // reader
9349        synchronized (mPackages) {
9350            if (!isExternalMediaAvailable()) {
9351                return;
9352            }
9353            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9354                return;
9355            }
9356        }
9357        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9358        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9359        IActivityManager am = ActivityManagerNative.getDefault();
9360        if (am != null) {
9361            try {
9362                am.startService(null, intent, null, mContext.getOpPackageName(),
9363                        UserHandle.USER_OWNER);
9364            } catch (RemoteException e) {
9365            }
9366        }
9367    }
9368
9369    @Override
9370    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9371            int installFlags, String installerPackageName, VerificationParams verificationParams,
9372            String packageAbiOverride) {
9373        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9374                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9375    }
9376
9377    @Override
9378    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9379            int installFlags, String installerPackageName, VerificationParams verificationParams,
9380            String packageAbiOverride, int userId) {
9381        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9382
9383        final int callingUid = Binder.getCallingUid();
9384        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9385
9386        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9387            try {
9388                if (observer != null) {
9389                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9390                }
9391            } catch (RemoteException re) {
9392            }
9393            return;
9394        }
9395
9396        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9397            installFlags |= PackageManager.INSTALL_FROM_ADB;
9398
9399        } else {
9400            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9401            // about installerPackageName.
9402
9403            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9404            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9405        }
9406
9407        UserHandle user;
9408        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9409            user = UserHandle.ALL;
9410        } else {
9411            user = new UserHandle(userId);
9412        }
9413
9414        // Only system components can circumvent runtime permissions when installing.
9415        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9416                && mContext.checkCallingOrSelfPermission(Manifest.permission
9417                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9418            throw new SecurityException("You need the "
9419                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9420                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9421        }
9422
9423        verificationParams.setInstallerUid(callingUid);
9424
9425        final File originFile = new File(originPath);
9426        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9427
9428        final Message msg = mHandler.obtainMessage(INIT_COPY);
9429        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9430                null, verificationParams, user, packageAbiOverride);
9431        mHandler.sendMessage(msg);
9432    }
9433
9434    void installStage(String packageName, File stagedDir, String stagedCid,
9435            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9436            String installerPackageName, int installerUid, UserHandle user) {
9437        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9438                params.referrerUri, installerUid, null);
9439        verifParams.setInstallerUid(installerUid);
9440
9441        final OriginInfo origin;
9442        if (stagedDir != null) {
9443            origin = OriginInfo.fromStagedFile(stagedDir);
9444        } else {
9445            origin = OriginInfo.fromStagedContainer(stagedCid);
9446        }
9447
9448        final Message msg = mHandler.obtainMessage(INIT_COPY);
9449        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9450                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9451        mHandler.sendMessage(msg);
9452    }
9453
9454    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9455        Bundle extras = new Bundle(1);
9456        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9457
9458        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9459                packageName, extras, null, null, new int[] {userId});
9460        try {
9461            IActivityManager am = ActivityManagerNative.getDefault();
9462            final boolean isSystem =
9463                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9464            if (isSystem && am.isUserRunning(userId, false)) {
9465                // The just-installed/enabled app is bundled on the system, so presumed
9466                // to be able to run automatically without needing an explicit launch.
9467                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9468                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9469                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9470                        .setPackage(packageName);
9471                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9472                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9473            }
9474        } catch (RemoteException e) {
9475            // shouldn't happen
9476            Slog.w(TAG, "Unable to bootstrap installed package", e);
9477        }
9478    }
9479
9480    @Override
9481    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9482            int userId) {
9483        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9484        PackageSetting pkgSetting;
9485        final int uid = Binder.getCallingUid();
9486        enforceCrossUserPermission(uid, userId, true, true,
9487                "setApplicationHiddenSetting for user " + userId);
9488
9489        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9490            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9491            return false;
9492        }
9493
9494        long callingId = Binder.clearCallingIdentity();
9495        try {
9496            boolean sendAdded = false;
9497            boolean sendRemoved = false;
9498            // writer
9499            synchronized (mPackages) {
9500                pkgSetting = mSettings.mPackages.get(packageName);
9501                if (pkgSetting == null) {
9502                    return false;
9503                }
9504                if (pkgSetting.getHidden(userId) != hidden) {
9505                    pkgSetting.setHidden(hidden, userId);
9506                    mSettings.writePackageRestrictionsLPr(userId);
9507                    if (hidden) {
9508                        sendRemoved = true;
9509                    } else {
9510                        sendAdded = true;
9511                    }
9512                }
9513            }
9514            if (sendAdded) {
9515                sendPackageAddedForUser(packageName, pkgSetting, userId);
9516                return true;
9517            }
9518            if (sendRemoved) {
9519                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9520                        "hiding pkg");
9521                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9522            }
9523        } finally {
9524            Binder.restoreCallingIdentity(callingId);
9525        }
9526        return false;
9527    }
9528
9529    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9530            int userId) {
9531        final PackageRemovedInfo info = new PackageRemovedInfo();
9532        info.removedPackage = packageName;
9533        info.removedUsers = new int[] {userId};
9534        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9535        info.sendBroadcast(false, false, false);
9536    }
9537
9538    /**
9539     * Returns true if application is not found or there was an error. Otherwise it returns
9540     * the hidden state of the package for the given user.
9541     */
9542    @Override
9543    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9544        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9545        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9546                false, "getApplicationHidden for user " + userId);
9547        PackageSetting pkgSetting;
9548        long callingId = Binder.clearCallingIdentity();
9549        try {
9550            // writer
9551            synchronized (mPackages) {
9552                pkgSetting = mSettings.mPackages.get(packageName);
9553                if (pkgSetting == null) {
9554                    return true;
9555                }
9556                return pkgSetting.getHidden(userId);
9557            }
9558        } finally {
9559            Binder.restoreCallingIdentity(callingId);
9560        }
9561    }
9562
9563    /**
9564     * @hide
9565     */
9566    @Override
9567    public int installExistingPackageAsUser(String packageName, int userId) {
9568        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9569                null);
9570        PackageSetting pkgSetting;
9571        final int uid = Binder.getCallingUid();
9572        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9573                + userId);
9574        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9575            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9576        }
9577
9578        long callingId = Binder.clearCallingIdentity();
9579        try {
9580            boolean sendAdded = false;
9581
9582            // writer
9583            synchronized (mPackages) {
9584                pkgSetting = mSettings.mPackages.get(packageName);
9585                if (pkgSetting == null) {
9586                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9587                }
9588                if (!pkgSetting.getInstalled(userId)) {
9589                    pkgSetting.setInstalled(true, userId);
9590                    pkgSetting.setHidden(false, userId);
9591                    mSettings.writePackageRestrictionsLPr(userId);
9592                    sendAdded = true;
9593                }
9594            }
9595
9596            if (sendAdded) {
9597                sendPackageAddedForUser(packageName, pkgSetting, userId);
9598            }
9599        } finally {
9600            Binder.restoreCallingIdentity(callingId);
9601        }
9602
9603        return PackageManager.INSTALL_SUCCEEDED;
9604    }
9605
9606    boolean isUserRestricted(int userId, String restrictionKey) {
9607        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9608        if (restrictions.getBoolean(restrictionKey, false)) {
9609            Log.w(TAG, "User is restricted: " + restrictionKey);
9610            return true;
9611        }
9612        return false;
9613    }
9614
9615    @Override
9616    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9617        mContext.enforceCallingOrSelfPermission(
9618                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9619                "Only package verification agents can verify applications");
9620
9621        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9622        final PackageVerificationResponse response = new PackageVerificationResponse(
9623                verificationCode, Binder.getCallingUid());
9624        msg.arg1 = id;
9625        msg.obj = response;
9626        mHandler.sendMessage(msg);
9627    }
9628
9629    @Override
9630    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9631            long millisecondsToDelay) {
9632        mContext.enforceCallingOrSelfPermission(
9633                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9634                "Only package verification agents can extend verification timeouts");
9635
9636        final PackageVerificationState state = mPendingVerification.get(id);
9637        final PackageVerificationResponse response = new PackageVerificationResponse(
9638                verificationCodeAtTimeout, Binder.getCallingUid());
9639
9640        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9641            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9642        }
9643        if (millisecondsToDelay < 0) {
9644            millisecondsToDelay = 0;
9645        }
9646        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9647                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9648            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9649        }
9650
9651        if ((state != null) && !state.timeoutExtended()) {
9652            state.extendTimeout();
9653
9654            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9655            msg.arg1 = id;
9656            msg.obj = response;
9657            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9658        }
9659    }
9660
9661    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9662            int verificationCode, UserHandle user) {
9663        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9664        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9665        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9666        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9667        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9668
9669        mContext.sendBroadcastAsUser(intent, user,
9670                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9671    }
9672
9673    private ComponentName matchComponentForVerifier(String packageName,
9674            List<ResolveInfo> receivers) {
9675        ActivityInfo targetReceiver = null;
9676
9677        final int NR = receivers.size();
9678        for (int i = 0; i < NR; i++) {
9679            final ResolveInfo info = receivers.get(i);
9680            if (info.activityInfo == null) {
9681                continue;
9682            }
9683
9684            if (packageName.equals(info.activityInfo.packageName)) {
9685                targetReceiver = info.activityInfo;
9686                break;
9687            }
9688        }
9689
9690        if (targetReceiver == null) {
9691            return null;
9692        }
9693
9694        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9695    }
9696
9697    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9698            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9699        if (pkgInfo.verifiers.length == 0) {
9700            return null;
9701        }
9702
9703        final int N = pkgInfo.verifiers.length;
9704        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9705        for (int i = 0; i < N; i++) {
9706            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9707
9708            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9709                    receivers);
9710            if (comp == null) {
9711                continue;
9712            }
9713
9714            final int verifierUid = getUidForVerifier(verifierInfo);
9715            if (verifierUid == -1) {
9716                continue;
9717            }
9718
9719            if (DEBUG_VERIFY) {
9720                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9721                        + " with the correct signature");
9722            }
9723            sufficientVerifiers.add(comp);
9724            verificationState.addSufficientVerifier(verifierUid);
9725        }
9726
9727        return sufficientVerifiers;
9728    }
9729
9730    private int getUidForVerifier(VerifierInfo verifierInfo) {
9731        synchronized (mPackages) {
9732            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9733            if (pkg == null) {
9734                return -1;
9735            } else if (pkg.mSignatures.length != 1) {
9736                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9737                        + " has more than one signature; ignoring");
9738                return -1;
9739            }
9740
9741            /*
9742             * If the public key of the package's signature does not match
9743             * our expected public key, then this is a different package and
9744             * we should skip.
9745             */
9746
9747            final byte[] expectedPublicKey;
9748            try {
9749                final Signature verifierSig = pkg.mSignatures[0];
9750                final PublicKey publicKey = verifierSig.getPublicKey();
9751                expectedPublicKey = publicKey.getEncoded();
9752            } catch (CertificateException e) {
9753                return -1;
9754            }
9755
9756            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9757
9758            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9759                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9760                        + " does not have the expected public key; ignoring");
9761                return -1;
9762            }
9763
9764            return pkg.applicationInfo.uid;
9765        }
9766    }
9767
9768    @Override
9769    public void finishPackageInstall(int token) {
9770        enforceSystemOrRoot("Only the system is allowed to finish installs");
9771
9772        if (DEBUG_INSTALL) {
9773            Slog.v(TAG, "BM finishing package install for " + token);
9774        }
9775
9776        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9777        mHandler.sendMessage(msg);
9778    }
9779
9780    /**
9781     * Get the verification agent timeout.
9782     *
9783     * @return verification timeout in milliseconds
9784     */
9785    private long getVerificationTimeout() {
9786        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9787                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9788                DEFAULT_VERIFICATION_TIMEOUT);
9789    }
9790
9791    /**
9792     * Get the default verification agent response code.
9793     *
9794     * @return default verification response code
9795     */
9796    private int getDefaultVerificationResponse() {
9797        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9798                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9799                DEFAULT_VERIFICATION_RESPONSE);
9800    }
9801
9802    /**
9803     * Check whether or not package verification has been enabled.
9804     *
9805     * @return true if verification should be performed
9806     */
9807    private boolean isVerificationEnabled(int userId, int installFlags) {
9808        if (!DEFAULT_VERIFY_ENABLE) {
9809            return false;
9810        }
9811
9812        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9813
9814        // Check if installing from ADB
9815        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9816            // Do not run verification in a test harness environment
9817            if (ActivityManager.isRunningInTestHarness()) {
9818                return false;
9819            }
9820            if (ensureVerifyAppsEnabled) {
9821                return true;
9822            }
9823            // Check if the developer does not want package verification for ADB installs
9824            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9825                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9826                return false;
9827            }
9828        }
9829
9830        if (ensureVerifyAppsEnabled) {
9831            return true;
9832        }
9833
9834        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9835                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9836    }
9837
9838    @Override
9839    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9840            throws RemoteException {
9841        mContext.enforceCallingOrSelfPermission(
9842                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9843                "Only intentfilter verification agents can verify applications");
9844
9845        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9846        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9847                Binder.getCallingUid(), verificationCode, failedDomains);
9848        msg.arg1 = id;
9849        msg.obj = response;
9850        mHandler.sendMessage(msg);
9851    }
9852
9853    @Override
9854    public int getIntentVerificationStatus(String packageName, int userId) {
9855        synchronized (mPackages) {
9856            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9857        }
9858    }
9859
9860    @Override
9861    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9862        mContext.enforceCallingOrSelfPermission(
9863                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9864
9865        boolean result = false;
9866        synchronized (mPackages) {
9867            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9868        }
9869        if (result) {
9870            scheduleWritePackageRestrictionsLocked(userId);
9871        }
9872        return result;
9873    }
9874
9875    @Override
9876    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9877        synchronized (mPackages) {
9878            return mSettings.getIntentFilterVerificationsLPr(packageName);
9879        }
9880    }
9881
9882    @Override
9883    public List<IntentFilter> getAllIntentFilters(String packageName) {
9884        if (TextUtils.isEmpty(packageName)) {
9885            return Collections.<IntentFilter>emptyList();
9886        }
9887        synchronized (mPackages) {
9888            PackageParser.Package pkg = mPackages.get(packageName);
9889            if (pkg == null || pkg.activities == null) {
9890                return Collections.<IntentFilter>emptyList();
9891            }
9892            final int count = pkg.activities.size();
9893            ArrayList<IntentFilter> result = new ArrayList<>();
9894            for (int n=0; n<count; n++) {
9895                PackageParser.Activity activity = pkg.activities.get(n);
9896                if (activity.intents != null || activity.intents.size() > 0) {
9897                    result.addAll(activity.intents);
9898                }
9899            }
9900            return result;
9901        }
9902    }
9903
9904    @Override
9905    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9906        mContext.enforceCallingOrSelfPermission(
9907                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9908
9909        synchronized (mPackages) {
9910            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9911            if (packageName != null) {
9912                result |= updateIntentVerificationStatus(packageName,
9913                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9914                        UserHandle.myUserId());
9915                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9916                        packageName, userId);
9917            }
9918            return result;
9919        }
9920    }
9921
9922    @Override
9923    public String getDefaultBrowserPackageName(int userId) {
9924        synchronized (mPackages) {
9925            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9926        }
9927    }
9928
9929    /**
9930     * Get the "allow unknown sources" setting.
9931     *
9932     * @return the current "allow unknown sources" setting
9933     */
9934    private int getUnknownSourcesSettings() {
9935        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9936                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9937                -1);
9938    }
9939
9940    @Override
9941    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9942        final int uid = Binder.getCallingUid();
9943        // writer
9944        synchronized (mPackages) {
9945            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9946            if (targetPackageSetting == null) {
9947                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9948            }
9949
9950            PackageSetting installerPackageSetting;
9951            if (installerPackageName != null) {
9952                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9953                if (installerPackageSetting == null) {
9954                    throw new IllegalArgumentException("Unknown installer package: "
9955                            + installerPackageName);
9956                }
9957            } else {
9958                installerPackageSetting = null;
9959            }
9960
9961            Signature[] callerSignature;
9962            Object obj = mSettings.getUserIdLPr(uid);
9963            if (obj != null) {
9964                if (obj instanceof SharedUserSetting) {
9965                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9966                } else if (obj instanceof PackageSetting) {
9967                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9968                } else {
9969                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9970                }
9971            } else {
9972                throw new SecurityException("Unknown calling uid " + uid);
9973            }
9974
9975            // Verify: can't set installerPackageName to a package that is
9976            // not signed with the same cert as the caller.
9977            if (installerPackageSetting != null) {
9978                if (compareSignatures(callerSignature,
9979                        installerPackageSetting.signatures.mSignatures)
9980                        != PackageManager.SIGNATURE_MATCH) {
9981                    throw new SecurityException(
9982                            "Caller does not have same cert as new installer package "
9983                            + installerPackageName);
9984                }
9985            }
9986
9987            // Verify: if target already has an installer package, it must
9988            // be signed with the same cert as the caller.
9989            if (targetPackageSetting.installerPackageName != null) {
9990                PackageSetting setting = mSettings.mPackages.get(
9991                        targetPackageSetting.installerPackageName);
9992                // If the currently set package isn't valid, then it's always
9993                // okay to change it.
9994                if (setting != null) {
9995                    if (compareSignatures(callerSignature,
9996                            setting.signatures.mSignatures)
9997                            != PackageManager.SIGNATURE_MATCH) {
9998                        throw new SecurityException(
9999                                "Caller does not have same cert as old installer package "
10000                                + targetPackageSetting.installerPackageName);
10001                    }
10002                }
10003            }
10004
10005            // Okay!
10006            targetPackageSetting.installerPackageName = installerPackageName;
10007            scheduleWriteSettingsLocked();
10008        }
10009    }
10010
10011    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10012        // Queue up an async operation since the package installation may take a little while.
10013        mHandler.post(new Runnable() {
10014            public void run() {
10015                mHandler.removeCallbacks(this);
10016                 // Result object to be returned
10017                PackageInstalledInfo res = new PackageInstalledInfo();
10018                res.returnCode = currentStatus;
10019                res.uid = -1;
10020                res.pkg = null;
10021                res.removedInfo = new PackageRemovedInfo();
10022                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10023                    args.doPreInstall(res.returnCode);
10024                    synchronized (mInstallLock) {
10025                        installPackageLI(args, res);
10026                    }
10027                    args.doPostInstall(res.returnCode, res.uid);
10028                }
10029
10030                // A restore should be performed at this point if (a) the install
10031                // succeeded, (b) the operation is not an update, and (c) the new
10032                // package has not opted out of backup participation.
10033                final boolean update = res.removedInfo.removedPackage != null;
10034                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10035                boolean doRestore = !update
10036                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10037
10038                // Set up the post-install work request bookkeeping.  This will be used
10039                // and cleaned up by the post-install event handling regardless of whether
10040                // there's a restore pass performed.  Token values are >= 1.
10041                int token;
10042                if (mNextInstallToken < 0) mNextInstallToken = 1;
10043                token = mNextInstallToken++;
10044
10045                PostInstallData data = new PostInstallData(args, res);
10046                mRunningInstalls.put(token, data);
10047                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10048
10049                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10050                    // Pass responsibility to the Backup Manager.  It will perform a
10051                    // restore if appropriate, then pass responsibility back to the
10052                    // Package Manager to run the post-install observer callbacks
10053                    // and broadcasts.
10054                    IBackupManager bm = IBackupManager.Stub.asInterface(
10055                            ServiceManager.getService(Context.BACKUP_SERVICE));
10056                    if (bm != null) {
10057                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10058                                + " to BM for possible restore");
10059                        try {
10060                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10061                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10062                            } else {
10063                                doRestore = false;
10064                            }
10065                        } catch (RemoteException e) {
10066                            // can't happen; the backup manager is local
10067                        } catch (Exception e) {
10068                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10069                            doRestore = false;
10070                        }
10071                    } else {
10072                        Slog.e(TAG, "Backup Manager not found!");
10073                        doRestore = false;
10074                    }
10075                }
10076
10077                if (!doRestore) {
10078                    // No restore possible, or the Backup Manager was mysteriously not
10079                    // available -- just fire the post-install work request directly.
10080                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10081                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10082                    mHandler.sendMessage(msg);
10083                }
10084            }
10085        });
10086    }
10087
10088    private abstract class HandlerParams {
10089        private static final int MAX_RETRIES = 4;
10090
10091        /**
10092         * Number of times startCopy() has been attempted and had a non-fatal
10093         * error.
10094         */
10095        private int mRetries = 0;
10096
10097        /** User handle for the user requesting the information or installation. */
10098        private final UserHandle mUser;
10099
10100        HandlerParams(UserHandle user) {
10101            mUser = user;
10102        }
10103
10104        UserHandle getUser() {
10105            return mUser;
10106        }
10107
10108        final boolean startCopy() {
10109            boolean res;
10110            try {
10111                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10112
10113                if (++mRetries > MAX_RETRIES) {
10114                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10115                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10116                    handleServiceError();
10117                    return false;
10118                } else {
10119                    handleStartCopy();
10120                    res = true;
10121                }
10122            } catch (RemoteException e) {
10123                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10124                mHandler.sendEmptyMessage(MCS_RECONNECT);
10125                res = false;
10126            }
10127            handleReturnCode();
10128            return res;
10129        }
10130
10131        final void serviceError() {
10132            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10133            handleServiceError();
10134            handleReturnCode();
10135        }
10136
10137        abstract void handleStartCopy() throws RemoteException;
10138        abstract void handleServiceError();
10139        abstract void handleReturnCode();
10140    }
10141
10142    class MeasureParams extends HandlerParams {
10143        private final PackageStats mStats;
10144        private boolean mSuccess;
10145
10146        private final IPackageStatsObserver mObserver;
10147
10148        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10149            super(new UserHandle(stats.userHandle));
10150            mObserver = observer;
10151            mStats = stats;
10152        }
10153
10154        @Override
10155        public String toString() {
10156            return "MeasureParams{"
10157                + Integer.toHexString(System.identityHashCode(this))
10158                + " " + mStats.packageName + "}";
10159        }
10160
10161        @Override
10162        void handleStartCopy() throws RemoteException {
10163            synchronized (mInstallLock) {
10164                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10165            }
10166
10167            if (mSuccess) {
10168                final boolean mounted;
10169                if (Environment.isExternalStorageEmulated()) {
10170                    mounted = true;
10171                } else {
10172                    final String status = Environment.getExternalStorageState();
10173                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10174                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10175                }
10176
10177                if (mounted) {
10178                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10179
10180                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10181                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10182
10183                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10184                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10185
10186                    // Always subtract cache size, since it's a subdirectory
10187                    mStats.externalDataSize -= mStats.externalCacheSize;
10188
10189                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10190                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10191
10192                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10193                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10194                }
10195            }
10196        }
10197
10198        @Override
10199        void handleReturnCode() {
10200            if (mObserver != null) {
10201                try {
10202                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10203                } catch (RemoteException e) {
10204                    Slog.i(TAG, "Observer no longer exists.");
10205                }
10206            }
10207        }
10208
10209        @Override
10210        void handleServiceError() {
10211            Slog.e(TAG, "Could not measure application " + mStats.packageName
10212                            + " external storage");
10213        }
10214    }
10215
10216    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10217            throws RemoteException {
10218        long result = 0;
10219        for (File path : paths) {
10220            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10221        }
10222        return result;
10223    }
10224
10225    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10226        for (File path : paths) {
10227            try {
10228                mcs.clearDirectory(path.getAbsolutePath());
10229            } catch (RemoteException e) {
10230            }
10231        }
10232    }
10233
10234    static class OriginInfo {
10235        /**
10236         * Location where install is coming from, before it has been
10237         * copied/renamed into place. This could be a single monolithic APK
10238         * file, or a cluster directory. This location may be untrusted.
10239         */
10240        final File file;
10241        final String cid;
10242
10243        /**
10244         * Flag indicating that {@link #file} or {@link #cid} has already been
10245         * staged, meaning downstream users don't need to defensively copy the
10246         * contents.
10247         */
10248        final boolean staged;
10249
10250        /**
10251         * Flag indicating that {@link #file} or {@link #cid} is an already
10252         * installed app that is being moved.
10253         */
10254        final boolean existing;
10255
10256        final String resolvedPath;
10257        final File resolvedFile;
10258
10259        static OriginInfo fromNothing() {
10260            return new OriginInfo(null, null, false, false);
10261        }
10262
10263        static OriginInfo fromUntrustedFile(File file) {
10264            return new OriginInfo(file, null, false, false);
10265        }
10266
10267        static OriginInfo fromExistingFile(File file) {
10268            return new OriginInfo(file, null, false, true);
10269        }
10270
10271        static OriginInfo fromStagedFile(File file) {
10272            return new OriginInfo(file, null, true, false);
10273        }
10274
10275        static OriginInfo fromStagedContainer(String cid) {
10276            return new OriginInfo(null, cid, true, false);
10277        }
10278
10279        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10280            this.file = file;
10281            this.cid = cid;
10282            this.staged = staged;
10283            this.existing = existing;
10284
10285            if (cid != null) {
10286                resolvedPath = PackageHelper.getSdDir(cid);
10287                resolvedFile = new File(resolvedPath);
10288            } else if (file != null) {
10289                resolvedPath = file.getAbsolutePath();
10290                resolvedFile = file;
10291            } else {
10292                resolvedPath = null;
10293                resolvedFile = null;
10294            }
10295        }
10296    }
10297
10298    class MoveInfo {
10299        final int moveId;
10300        final String fromUuid;
10301        final String toUuid;
10302        final String packageName;
10303        final String dataAppName;
10304        final int appId;
10305        final String seinfo;
10306
10307        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10308                String dataAppName, int appId, String seinfo) {
10309            this.moveId = moveId;
10310            this.fromUuid = fromUuid;
10311            this.toUuid = toUuid;
10312            this.packageName = packageName;
10313            this.dataAppName = dataAppName;
10314            this.appId = appId;
10315            this.seinfo = seinfo;
10316        }
10317    }
10318
10319    class InstallParams extends HandlerParams {
10320        final OriginInfo origin;
10321        final MoveInfo move;
10322        final IPackageInstallObserver2 observer;
10323        int installFlags;
10324        final String installerPackageName;
10325        final String volumeUuid;
10326        final VerificationParams verificationParams;
10327        private InstallArgs mArgs;
10328        private int mRet;
10329        final String packageAbiOverride;
10330
10331        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10332                int installFlags, String installerPackageName, String volumeUuid,
10333                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10334            super(user);
10335            this.origin = origin;
10336            this.move = move;
10337            this.observer = observer;
10338            this.installFlags = installFlags;
10339            this.installerPackageName = installerPackageName;
10340            this.volumeUuid = volumeUuid;
10341            this.verificationParams = verificationParams;
10342            this.packageAbiOverride = packageAbiOverride;
10343        }
10344
10345        @Override
10346        public String toString() {
10347            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10348                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10349        }
10350
10351        public ManifestDigest getManifestDigest() {
10352            if (verificationParams == null) {
10353                return null;
10354            }
10355            return verificationParams.getManifestDigest();
10356        }
10357
10358        private int installLocationPolicy(PackageInfoLite pkgLite) {
10359            String packageName = pkgLite.packageName;
10360            int installLocation = pkgLite.installLocation;
10361            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10362            // reader
10363            synchronized (mPackages) {
10364                PackageParser.Package pkg = mPackages.get(packageName);
10365                if (pkg != null) {
10366                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10367                        // Check for downgrading.
10368                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10369                            try {
10370                                checkDowngrade(pkg, pkgLite);
10371                            } catch (PackageManagerException e) {
10372                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10373                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10374                            }
10375                        }
10376                        // Check for updated system application.
10377                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10378                            if (onSd) {
10379                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10380                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10381                            }
10382                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10383                        } else {
10384                            if (onSd) {
10385                                // Install flag overrides everything.
10386                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10387                            }
10388                            // If current upgrade specifies particular preference
10389                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10390                                // Application explicitly specified internal.
10391                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10392                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10393                                // App explictly prefers external. Let policy decide
10394                            } else {
10395                                // Prefer previous location
10396                                if (isExternal(pkg)) {
10397                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10398                                }
10399                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10400                            }
10401                        }
10402                    } else {
10403                        // Invalid install. Return error code
10404                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10405                    }
10406                }
10407            }
10408            // All the special cases have been taken care of.
10409            // Return result based on recommended install location.
10410            if (onSd) {
10411                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10412            }
10413            return pkgLite.recommendedInstallLocation;
10414        }
10415
10416        /*
10417         * Invoke remote method to get package information and install
10418         * location values. Override install location based on default
10419         * policy if needed and then create install arguments based
10420         * on the install location.
10421         */
10422        public void handleStartCopy() throws RemoteException {
10423            int ret = PackageManager.INSTALL_SUCCEEDED;
10424
10425            // If we're already staged, we've firmly committed to an install location
10426            if (origin.staged) {
10427                if (origin.file != null) {
10428                    installFlags |= PackageManager.INSTALL_INTERNAL;
10429                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10430                } else if (origin.cid != null) {
10431                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10432                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10433                } else {
10434                    throw new IllegalStateException("Invalid stage location");
10435                }
10436            }
10437
10438            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10439            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10440
10441            PackageInfoLite pkgLite = null;
10442
10443            if (onInt && onSd) {
10444                // Check if both bits are set.
10445                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10446                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10447            } else {
10448                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10449                        packageAbiOverride);
10450
10451                /*
10452                 * If we have too little free space, try to free cache
10453                 * before giving up.
10454                 */
10455                if (!origin.staged && pkgLite.recommendedInstallLocation
10456                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10457                    // TODO: focus freeing disk space on the target device
10458                    final StorageManager storage = StorageManager.from(mContext);
10459                    final long lowThreshold = storage.getStorageLowBytes(
10460                            Environment.getDataDirectory());
10461
10462                    final long sizeBytes = mContainerService.calculateInstalledSize(
10463                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10464
10465                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10466                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10467                                installFlags, packageAbiOverride);
10468                    }
10469
10470                    /*
10471                     * The cache free must have deleted the file we
10472                     * downloaded to install.
10473                     *
10474                     * TODO: fix the "freeCache" call to not delete
10475                     *       the file we care about.
10476                     */
10477                    if (pkgLite.recommendedInstallLocation
10478                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10479                        pkgLite.recommendedInstallLocation
10480                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10481                    }
10482                }
10483            }
10484
10485            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10486                int loc = pkgLite.recommendedInstallLocation;
10487                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10488                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10489                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10490                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10491                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10492                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10493                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10494                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10495                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10496                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10497                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10498                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10499                } else {
10500                    // Override with defaults if needed.
10501                    loc = installLocationPolicy(pkgLite);
10502                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10503                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10504                    } else if (!onSd && !onInt) {
10505                        // Override install location with flags
10506                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10507                            // Set the flag to install on external media.
10508                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10509                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10510                        } else {
10511                            // Make sure the flag for installing on external
10512                            // media is unset
10513                            installFlags |= PackageManager.INSTALL_INTERNAL;
10514                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10515                        }
10516                    }
10517                }
10518            }
10519
10520            final InstallArgs args = createInstallArgs(this);
10521            mArgs = args;
10522
10523            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10524                 /*
10525                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10526                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10527                 */
10528                int userIdentifier = getUser().getIdentifier();
10529                if (userIdentifier == UserHandle.USER_ALL
10530                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10531                    userIdentifier = UserHandle.USER_OWNER;
10532                }
10533
10534                /*
10535                 * Determine if we have any installed package verifiers. If we
10536                 * do, then we'll defer to them to verify the packages.
10537                 */
10538                final int requiredUid = mRequiredVerifierPackage == null ? -1
10539                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10540                if (!origin.existing && requiredUid != -1
10541                        && isVerificationEnabled(userIdentifier, installFlags)) {
10542                    final Intent verification = new Intent(
10543                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10544                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10545                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10546                            PACKAGE_MIME_TYPE);
10547                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10548
10549                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10550                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10551                            0 /* TODO: Which userId? */);
10552
10553                    if (DEBUG_VERIFY) {
10554                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10555                                + verification.toString() + " with " + pkgLite.verifiers.length
10556                                + " optional verifiers");
10557                    }
10558
10559                    final int verificationId = mPendingVerificationToken++;
10560
10561                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10562
10563                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10564                            installerPackageName);
10565
10566                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10567                            installFlags);
10568
10569                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10570                            pkgLite.packageName);
10571
10572                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10573                            pkgLite.versionCode);
10574
10575                    if (verificationParams != null) {
10576                        if (verificationParams.getVerificationURI() != null) {
10577                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10578                                 verificationParams.getVerificationURI());
10579                        }
10580                        if (verificationParams.getOriginatingURI() != null) {
10581                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10582                                  verificationParams.getOriginatingURI());
10583                        }
10584                        if (verificationParams.getReferrer() != null) {
10585                            verification.putExtra(Intent.EXTRA_REFERRER,
10586                                  verificationParams.getReferrer());
10587                        }
10588                        if (verificationParams.getOriginatingUid() >= 0) {
10589                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10590                                  verificationParams.getOriginatingUid());
10591                        }
10592                        if (verificationParams.getInstallerUid() >= 0) {
10593                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10594                                  verificationParams.getInstallerUid());
10595                        }
10596                    }
10597
10598                    final PackageVerificationState verificationState = new PackageVerificationState(
10599                            requiredUid, args);
10600
10601                    mPendingVerification.append(verificationId, verificationState);
10602
10603                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10604                            receivers, verificationState);
10605
10606                    /*
10607                     * If any sufficient verifiers were listed in the package
10608                     * manifest, attempt to ask them.
10609                     */
10610                    if (sufficientVerifiers != null) {
10611                        final int N = sufficientVerifiers.size();
10612                        if (N == 0) {
10613                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10614                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10615                        } else {
10616                            for (int i = 0; i < N; i++) {
10617                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10618
10619                                final Intent sufficientIntent = new Intent(verification);
10620                                sufficientIntent.setComponent(verifierComponent);
10621
10622                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10623                            }
10624                        }
10625                    }
10626
10627                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10628                            mRequiredVerifierPackage, receivers);
10629                    if (ret == PackageManager.INSTALL_SUCCEEDED
10630                            && mRequiredVerifierPackage != null) {
10631                        /*
10632                         * Send the intent to the required verification agent,
10633                         * but only start the verification timeout after the
10634                         * target BroadcastReceivers have run.
10635                         */
10636                        verification.setComponent(requiredVerifierComponent);
10637                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10638                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10639                                new BroadcastReceiver() {
10640                                    @Override
10641                                    public void onReceive(Context context, Intent intent) {
10642                                        final Message msg = mHandler
10643                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10644                                        msg.arg1 = verificationId;
10645                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10646                                    }
10647                                }, null, 0, null, null);
10648
10649                        /*
10650                         * We don't want the copy to proceed until verification
10651                         * succeeds, so null out this field.
10652                         */
10653                        mArgs = null;
10654                    }
10655                } else {
10656                    /*
10657                     * No package verification is enabled, so immediately start
10658                     * the remote call to initiate copy using temporary file.
10659                     */
10660                    ret = args.copyApk(mContainerService, true);
10661                }
10662            }
10663
10664            mRet = ret;
10665        }
10666
10667        @Override
10668        void handleReturnCode() {
10669            // If mArgs is null, then MCS couldn't be reached. When it
10670            // reconnects, it will try again to install. At that point, this
10671            // will succeed.
10672            if (mArgs != null) {
10673                processPendingInstall(mArgs, mRet);
10674            }
10675        }
10676
10677        @Override
10678        void handleServiceError() {
10679            mArgs = createInstallArgs(this);
10680            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10681        }
10682
10683        public boolean isForwardLocked() {
10684            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10685        }
10686    }
10687
10688    /**
10689     * Used during creation of InstallArgs
10690     *
10691     * @param installFlags package installation flags
10692     * @return true if should be installed on external storage
10693     */
10694    private static boolean installOnExternalAsec(int installFlags) {
10695        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10696            return false;
10697        }
10698        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10699            return true;
10700        }
10701        return false;
10702    }
10703
10704    /**
10705     * Used during creation of InstallArgs
10706     *
10707     * @param installFlags package installation flags
10708     * @return true if should be installed as forward locked
10709     */
10710    private static boolean installForwardLocked(int installFlags) {
10711        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10712    }
10713
10714    private InstallArgs createInstallArgs(InstallParams params) {
10715        if (params.move != null) {
10716            return new MoveInstallArgs(params);
10717        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10718            return new AsecInstallArgs(params);
10719        } else {
10720            return new FileInstallArgs(params);
10721        }
10722    }
10723
10724    /**
10725     * Create args that describe an existing installed package. Typically used
10726     * when cleaning up old installs, or used as a move source.
10727     */
10728    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10729            String resourcePath, String[] instructionSets) {
10730        final boolean isInAsec;
10731        if (installOnExternalAsec(installFlags)) {
10732            /* Apps on SD card are always in ASEC containers. */
10733            isInAsec = true;
10734        } else if (installForwardLocked(installFlags)
10735                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10736            /*
10737             * Forward-locked apps are only in ASEC containers if they're the
10738             * new style
10739             */
10740            isInAsec = true;
10741        } else {
10742            isInAsec = false;
10743        }
10744
10745        if (isInAsec) {
10746            return new AsecInstallArgs(codePath, instructionSets,
10747                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10748        } else {
10749            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10750        }
10751    }
10752
10753    static abstract class InstallArgs {
10754        /** @see InstallParams#origin */
10755        final OriginInfo origin;
10756        /** @see InstallParams#move */
10757        final MoveInfo move;
10758
10759        final IPackageInstallObserver2 observer;
10760        // Always refers to PackageManager flags only
10761        final int installFlags;
10762        final String installerPackageName;
10763        final String volumeUuid;
10764        final ManifestDigest manifestDigest;
10765        final UserHandle user;
10766        final String abiOverride;
10767
10768        // The list of instruction sets supported by this app. This is currently
10769        // only used during the rmdex() phase to clean up resources. We can get rid of this
10770        // if we move dex files under the common app path.
10771        /* nullable */ String[] instructionSets;
10772
10773        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10774                int installFlags, String installerPackageName, String volumeUuid,
10775                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10776                String abiOverride) {
10777            this.origin = origin;
10778            this.move = move;
10779            this.installFlags = installFlags;
10780            this.observer = observer;
10781            this.installerPackageName = installerPackageName;
10782            this.volumeUuid = volumeUuid;
10783            this.manifestDigest = manifestDigest;
10784            this.user = user;
10785            this.instructionSets = instructionSets;
10786            this.abiOverride = abiOverride;
10787        }
10788
10789        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10790        abstract int doPreInstall(int status);
10791
10792        /**
10793         * Rename package into final resting place. All paths on the given
10794         * scanned package should be updated to reflect the rename.
10795         */
10796        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10797        abstract int doPostInstall(int status, int uid);
10798
10799        /** @see PackageSettingBase#codePathString */
10800        abstract String getCodePath();
10801        /** @see PackageSettingBase#resourcePathString */
10802        abstract String getResourcePath();
10803
10804        // Need installer lock especially for dex file removal.
10805        abstract void cleanUpResourcesLI();
10806        abstract boolean doPostDeleteLI(boolean delete);
10807
10808        /**
10809         * Called before the source arguments are copied. This is used mostly
10810         * for MoveParams when it needs to read the source file to put it in the
10811         * destination.
10812         */
10813        int doPreCopy() {
10814            return PackageManager.INSTALL_SUCCEEDED;
10815        }
10816
10817        /**
10818         * Called after the source arguments are copied. This is used mostly for
10819         * MoveParams when it needs to read the source file to put it in the
10820         * destination.
10821         *
10822         * @return
10823         */
10824        int doPostCopy(int uid) {
10825            return PackageManager.INSTALL_SUCCEEDED;
10826        }
10827
10828        protected boolean isFwdLocked() {
10829            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10830        }
10831
10832        protected boolean isExternalAsec() {
10833            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10834        }
10835
10836        UserHandle getUser() {
10837            return user;
10838        }
10839    }
10840
10841    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10842        if (!allCodePaths.isEmpty()) {
10843            if (instructionSets == null) {
10844                throw new IllegalStateException("instructionSet == null");
10845            }
10846            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10847            for (String codePath : allCodePaths) {
10848                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10849                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10850                    if (retCode < 0) {
10851                        Slog.w(TAG, "Couldn't remove dex file for package: "
10852                                + " at location " + codePath + ", retcode=" + retCode);
10853                        // we don't consider this to be a failure of the core package deletion
10854                    }
10855                }
10856            }
10857        }
10858    }
10859
10860    /**
10861     * Logic to handle installation of non-ASEC applications, including copying
10862     * and renaming logic.
10863     */
10864    class FileInstallArgs extends InstallArgs {
10865        private File codeFile;
10866        private File resourceFile;
10867
10868        // Example topology:
10869        // /data/app/com.example/base.apk
10870        // /data/app/com.example/split_foo.apk
10871        // /data/app/com.example/lib/arm/libfoo.so
10872        // /data/app/com.example/lib/arm64/libfoo.so
10873        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10874
10875        /** New install */
10876        FileInstallArgs(InstallParams params) {
10877            super(params.origin, params.move, params.observer, params.installFlags,
10878                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10879                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10880            if (isFwdLocked()) {
10881                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10882            }
10883        }
10884
10885        /** Existing install */
10886        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10887            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10888                    null);
10889            this.codeFile = (codePath != null) ? new File(codePath) : null;
10890            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10891        }
10892
10893        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10894            if (origin.staged) {
10895                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10896                codeFile = origin.file;
10897                resourceFile = origin.file;
10898                return PackageManager.INSTALL_SUCCEEDED;
10899            }
10900
10901            try {
10902                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10903                codeFile = tempDir;
10904                resourceFile = tempDir;
10905            } catch (IOException e) {
10906                Slog.w(TAG, "Failed to create copy file: " + e);
10907                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10908            }
10909
10910            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10911                @Override
10912                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10913                    if (!FileUtils.isValidExtFilename(name)) {
10914                        throw new IllegalArgumentException("Invalid filename: " + name);
10915                    }
10916                    try {
10917                        final File file = new File(codeFile, name);
10918                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10919                                O_RDWR | O_CREAT, 0644);
10920                        Os.chmod(file.getAbsolutePath(), 0644);
10921                        return new ParcelFileDescriptor(fd);
10922                    } catch (ErrnoException e) {
10923                        throw new RemoteException("Failed to open: " + e.getMessage());
10924                    }
10925                }
10926            };
10927
10928            int ret = PackageManager.INSTALL_SUCCEEDED;
10929            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10930            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10931                Slog.e(TAG, "Failed to copy package");
10932                return ret;
10933            }
10934
10935            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10936            NativeLibraryHelper.Handle handle = null;
10937            try {
10938                handle = NativeLibraryHelper.Handle.create(codeFile);
10939                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10940                        abiOverride);
10941            } catch (IOException e) {
10942                Slog.e(TAG, "Copying native libraries failed", e);
10943                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10944            } finally {
10945                IoUtils.closeQuietly(handle);
10946            }
10947
10948            return ret;
10949        }
10950
10951        int doPreInstall(int status) {
10952            if (status != PackageManager.INSTALL_SUCCEEDED) {
10953                cleanUp();
10954            }
10955            return status;
10956        }
10957
10958        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10959            if (status != PackageManager.INSTALL_SUCCEEDED) {
10960                cleanUp();
10961                return false;
10962            }
10963
10964            final File targetDir = codeFile.getParentFile();
10965            final File beforeCodeFile = codeFile;
10966            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10967
10968            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10969            try {
10970                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10971            } catch (ErrnoException e) {
10972                Slog.w(TAG, "Failed to rename", e);
10973                return false;
10974            }
10975
10976            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10977                Slog.w(TAG, "Failed to restorecon");
10978                return false;
10979            }
10980
10981            // Reflect the rename internally
10982            codeFile = afterCodeFile;
10983            resourceFile = afterCodeFile;
10984
10985            // Reflect the rename in scanned details
10986            pkg.codePath = afterCodeFile.getAbsolutePath();
10987            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10988                    pkg.baseCodePath);
10989            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10990                    pkg.splitCodePaths);
10991
10992            // Reflect the rename in app info
10993            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10994            pkg.applicationInfo.setCodePath(pkg.codePath);
10995            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10996            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10997            pkg.applicationInfo.setResourcePath(pkg.codePath);
10998            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10999            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11000
11001            return true;
11002        }
11003
11004        int doPostInstall(int status, int uid) {
11005            if (status != PackageManager.INSTALL_SUCCEEDED) {
11006                cleanUp();
11007            }
11008            return status;
11009        }
11010
11011        @Override
11012        String getCodePath() {
11013            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11014        }
11015
11016        @Override
11017        String getResourcePath() {
11018            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11019        }
11020
11021        private boolean cleanUp() {
11022            if (codeFile == null || !codeFile.exists()) {
11023                return false;
11024            }
11025
11026            if (codeFile.isDirectory()) {
11027                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11028            } else {
11029                codeFile.delete();
11030            }
11031
11032            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11033                resourceFile.delete();
11034            }
11035
11036            return true;
11037        }
11038
11039        void cleanUpResourcesLI() {
11040            // Try enumerating all code paths before deleting
11041            List<String> allCodePaths = Collections.EMPTY_LIST;
11042            if (codeFile != null && codeFile.exists()) {
11043                try {
11044                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11045                    allCodePaths = pkg.getAllCodePaths();
11046                } catch (PackageParserException e) {
11047                    // Ignored; we tried our best
11048                }
11049            }
11050
11051            cleanUp();
11052            removeDexFiles(allCodePaths, instructionSets);
11053        }
11054
11055        boolean doPostDeleteLI(boolean delete) {
11056            // XXX err, shouldn't we respect the delete flag?
11057            cleanUpResourcesLI();
11058            return true;
11059        }
11060    }
11061
11062    private boolean isAsecExternal(String cid) {
11063        final String asecPath = PackageHelper.getSdFilesystem(cid);
11064        return !asecPath.startsWith(mAsecInternalPath);
11065    }
11066
11067    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11068            PackageManagerException {
11069        if (copyRet < 0) {
11070            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11071                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11072                throw new PackageManagerException(copyRet, message);
11073            }
11074        }
11075    }
11076
11077    /**
11078     * Extract the MountService "container ID" from the full code path of an
11079     * .apk.
11080     */
11081    static String cidFromCodePath(String fullCodePath) {
11082        int eidx = fullCodePath.lastIndexOf("/");
11083        String subStr1 = fullCodePath.substring(0, eidx);
11084        int sidx = subStr1.lastIndexOf("/");
11085        return subStr1.substring(sidx+1, eidx);
11086    }
11087
11088    /**
11089     * Logic to handle installation of ASEC applications, including copying and
11090     * renaming logic.
11091     */
11092    class AsecInstallArgs extends InstallArgs {
11093        static final String RES_FILE_NAME = "pkg.apk";
11094        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11095
11096        String cid;
11097        String packagePath;
11098        String resourcePath;
11099
11100        /** New install */
11101        AsecInstallArgs(InstallParams params) {
11102            super(params.origin, params.move, params.observer, params.installFlags,
11103                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11104                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11105        }
11106
11107        /** Existing install */
11108        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11109                        boolean isExternal, boolean isForwardLocked) {
11110            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11111                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11112                    instructionSets, null);
11113            // Hackily pretend we're still looking at a full code path
11114            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11115                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11116            }
11117
11118            // Extract cid from fullCodePath
11119            int eidx = fullCodePath.lastIndexOf("/");
11120            String subStr1 = fullCodePath.substring(0, eidx);
11121            int sidx = subStr1.lastIndexOf("/");
11122            cid = subStr1.substring(sidx+1, eidx);
11123            setMountPath(subStr1);
11124        }
11125
11126        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11127            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11128                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11129                    instructionSets, null);
11130            this.cid = cid;
11131            setMountPath(PackageHelper.getSdDir(cid));
11132        }
11133
11134        void createCopyFile() {
11135            cid = mInstallerService.allocateExternalStageCidLegacy();
11136        }
11137
11138        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11139            if (origin.staged) {
11140                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11141                cid = origin.cid;
11142                setMountPath(PackageHelper.getSdDir(cid));
11143                return PackageManager.INSTALL_SUCCEEDED;
11144            }
11145
11146            if (temp) {
11147                createCopyFile();
11148            } else {
11149                /*
11150                 * Pre-emptively destroy the container since it's destroyed if
11151                 * copying fails due to it existing anyway.
11152                 */
11153                PackageHelper.destroySdDir(cid);
11154            }
11155
11156            final String newMountPath = imcs.copyPackageToContainer(
11157                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11158                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11159
11160            if (newMountPath != null) {
11161                setMountPath(newMountPath);
11162                return PackageManager.INSTALL_SUCCEEDED;
11163            } else {
11164                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11165            }
11166        }
11167
11168        @Override
11169        String getCodePath() {
11170            return packagePath;
11171        }
11172
11173        @Override
11174        String getResourcePath() {
11175            return resourcePath;
11176        }
11177
11178        int doPreInstall(int status) {
11179            if (status != PackageManager.INSTALL_SUCCEEDED) {
11180                // Destroy container
11181                PackageHelper.destroySdDir(cid);
11182            } else {
11183                boolean mounted = PackageHelper.isContainerMounted(cid);
11184                if (!mounted) {
11185                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11186                            Process.SYSTEM_UID);
11187                    if (newMountPath != null) {
11188                        setMountPath(newMountPath);
11189                    } else {
11190                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11191                    }
11192                }
11193            }
11194            return status;
11195        }
11196
11197        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11198            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11199            String newMountPath = null;
11200            if (PackageHelper.isContainerMounted(cid)) {
11201                // Unmount the container
11202                if (!PackageHelper.unMountSdDir(cid)) {
11203                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11204                    return false;
11205                }
11206            }
11207            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11208                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11209                        " which might be stale. Will try to clean up.");
11210                // Clean up the stale container and proceed to recreate.
11211                if (!PackageHelper.destroySdDir(newCacheId)) {
11212                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11213                    return false;
11214                }
11215                // Successfully cleaned up stale container. Try to rename again.
11216                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11217                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11218                            + " inspite of cleaning it up.");
11219                    return false;
11220                }
11221            }
11222            if (!PackageHelper.isContainerMounted(newCacheId)) {
11223                Slog.w(TAG, "Mounting container " + newCacheId);
11224                newMountPath = PackageHelper.mountSdDir(newCacheId,
11225                        getEncryptKey(), Process.SYSTEM_UID);
11226            } else {
11227                newMountPath = PackageHelper.getSdDir(newCacheId);
11228            }
11229            if (newMountPath == null) {
11230                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11231                return false;
11232            }
11233            Log.i(TAG, "Succesfully renamed " + cid +
11234                    " to " + newCacheId +
11235                    " at new path: " + newMountPath);
11236            cid = newCacheId;
11237
11238            final File beforeCodeFile = new File(packagePath);
11239            setMountPath(newMountPath);
11240            final File afterCodeFile = new File(packagePath);
11241
11242            // Reflect the rename in scanned details
11243            pkg.codePath = afterCodeFile.getAbsolutePath();
11244            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11245                    pkg.baseCodePath);
11246            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11247                    pkg.splitCodePaths);
11248
11249            // Reflect the rename in app info
11250            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11251            pkg.applicationInfo.setCodePath(pkg.codePath);
11252            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11253            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11254            pkg.applicationInfo.setResourcePath(pkg.codePath);
11255            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11256            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11257
11258            return true;
11259        }
11260
11261        private void setMountPath(String mountPath) {
11262            final File mountFile = new File(mountPath);
11263
11264            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11265            if (monolithicFile.exists()) {
11266                packagePath = monolithicFile.getAbsolutePath();
11267                if (isFwdLocked()) {
11268                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11269                } else {
11270                    resourcePath = packagePath;
11271                }
11272            } else {
11273                packagePath = mountFile.getAbsolutePath();
11274                resourcePath = packagePath;
11275            }
11276        }
11277
11278        int doPostInstall(int status, int uid) {
11279            if (status != PackageManager.INSTALL_SUCCEEDED) {
11280                cleanUp();
11281            } else {
11282                final int groupOwner;
11283                final String protectedFile;
11284                if (isFwdLocked()) {
11285                    groupOwner = UserHandle.getSharedAppGid(uid);
11286                    protectedFile = RES_FILE_NAME;
11287                } else {
11288                    groupOwner = -1;
11289                    protectedFile = null;
11290                }
11291
11292                if (uid < Process.FIRST_APPLICATION_UID
11293                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11294                    Slog.e(TAG, "Failed to finalize " + cid);
11295                    PackageHelper.destroySdDir(cid);
11296                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11297                }
11298
11299                boolean mounted = PackageHelper.isContainerMounted(cid);
11300                if (!mounted) {
11301                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11302                }
11303            }
11304            return status;
11305        }
11306
11307        private void cleanUp() {
11308            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11309
11310            // Destroy secure container
11311            PackageHelper.destroySdDir(cid);
11312        }
11313
11314        private List<String> getAllCodePaths() {
11315            final File codeFile = new File(getCodePath());
11316            if (codeFile != null && codeFile.exists()) {
11317                try {
11318                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11319                    return pkg.getAllCodePaths();
11320                } catch (PackageParserException e) {
11321                    // Ignored; we tried our best
11322                }
11323            }
11324            return Collections.EMPTY_LIST;
11325        }
11326
11327        void cleanUpResourcesLI() {
11328            // Enumerate all code paths before deleting
11329            cleanUpResourcesLI(getAllCodePaths());
11330        }
11331
11332        private void cleanUpResourcesLI(List<String> allCodePaths) {
11333            cleanUp();
11334            removeDexFiles(allCodePaths, instructionSets);
11335        }
11336
11337        String getPackageName() {
11338            return getAsecPackageName(cid);
11339        }
11340
11341        boolean doPostDeleteLI(boolean delete) {
11342            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11343            final List<String> allCodePaths = getAllCodePaths();
11344            boolean mounted = PackageHelper.isContainerMounted(cid);
11345            if (mounted) {
11346                // Unmount first
11347                if (PackageHelper.unMountSdDir(cid)) {
11348                    mounted = false;
11349                }
11350            }
11351            if (!mounted && delete) {
11352                cleanUpResourcesLI(allCodePaths);
11353            }
11354            return !mounted;
11355        }
11356
11357        @Override
11358        int doPreCopy() {
11359            if (isFwdLocked()) {
11360                if (!PackageHelper.fixSdPermissions(cid,
11361                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11362                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11363                }
11364            }
11365
11366            return PackageManager.INSTALL_SUCCEEDED;
11367        }
11368
11369        @Override
11370        int doPostCopy(int uid) {
11371            if (isFwdLocked()) {
11372                if (uid < Process.FIRST_APPLICATION_UID
11373                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11374                                RES_FILE_NAME)) {
11375                    Slog.e(TAG, "Failed to finalize " + cid);
11376                    PackageHelper.destroySdDir(cid);
11377                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11378                }
11379            }
11380
11381            return PackageManager.INSTALL_SUCCEEDED;
11382        }
11383    }
11384
11385    /**
11386     * Logic to handle movement of existing installed applications.
11387     */
11388    class MoveInstallArgs extends InstallArgs {
11389        private File codeFile;
11390        private File resourceFile;
11391
11392        /** New install */
11393        MoveInstallArgs(InstallParams params) {
11394            super(params.origin, params.move, params.observer, params.installFlags,
11395                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11396                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11397        }
11398
11399        int copyApk(IMediaContainerService imcs, boolean temp) {
11400            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11401                    + move.fromUuid + " to " + move.toUuid);
11402            synchronized (mInstaller) {
11403                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11404                        move.dataAppName, move.appId, move.seinfo) != 0) {
11405                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11406                }
11407            }
11408
11409            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11410            resourceFile = codeFile;
11411            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11412
11413            return PackageManager.INSTALL_SUCCEEDED;
11414        }
11415
11416        int doPreInstall(int status) {
11417            if (status != PackageManager.INSTALL_SUCCEEDED) {
11418                cleanUp(move.toUuid);
11419            }
11420            return status;
11421        }
11422
11423        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11424            if (status != PackageManager.INSTALL_SUCCEEDED) {
11425                cleanUp(move.toUuid);
11426                return false;
11427            }
11428
11429            // Reflect the move in app info
11430            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11431            pkg.applicationInfo.setCodePath(pkg.codePath);
11432            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11433            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11434            pkg.applicationInfo.setResourcePath(pkg.codePath);
11435            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11436            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11437
11438            return true;
11439        }
11440
11441        int doPostInstall(int status, int uid) {
11442            if (status == PackageManager.INSTALL_SUCCEEDED) {
11443                cleanUp(move.fromUuid);
11444            } else {
11445                cleanUp(move.toUuid);
11446            }
11447            return status;
11448        }
11449
11450        @Override
11451        String getCodePath() {
11452            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11453        }
11454
11455        @Override
11456        String getResourcePath() {
11457            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11458        }
11459
11460        private boolean cleanUp(String volumeUuid) {
11461            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11462                    move.dataAppName);
11463            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11464            synchronized (mInstallLock) {
11465                // Clean up both app data and code
11466                removeDataDirsLI(volumeUuid, move.packageName);
11467                if (codeFile.isDirectory()) {
11468                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11469                } else {
11470                    codeFile.delete();
11471                }
11472            }
11473            return true;
11474        }
11475
11476        void cleanUpResourcesLI() {
11477            throw new UnsupportedOperationException();
11478        }
11479
11480        boolean doPostDeleteLI(boolean delete) {
11481            throw new UnsupportedOperationException();
11482        }
11483    }
11484
11485    static String getAsecPackageName(String packageCid) {
11486        int idx = packageCid.lastIndexOf("-");
11487        if (idx == -1) {
11488            return packageCid;
11489        }
11490        return packageCid.substring(0, idx);
11491    }
11492
11493    // Utility method used to create code paths based on package name and available index.
11494    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11495        String idxStr = "";
11496        int idx = 1;
11497        // Fall back to default value of idx=1 if prefix is not
11498        // part of oldCodePath
11499        if (oldCodePath != null) {
11500            String subStr = oldCodePath;
11501            // Drop the suffix right away
11502            if (suffix != null && subStr.endsWith(suffix)) {
11503                subStr = subStr.substring(0, subStr.length() - suffix.length());
11504            }
11505            // If oldCodePath already contains prefix find out the
11506            // ending index to either increment or decrement.
11507            int sidx = subStr.lastIndexOf(prefix);
11508            if (sidx != -1) {
11509                subStr = subStr.substring(sidx + prefix.length());
11510                if (subStr != null) {
11511                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11512                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11513                    }
11514                    try {
11515                        idx = Integer.parseInt(subStr);
11516                        if (idx <= 1) {
11517                            idx++;
11518                        } else {
11519                            idx--;
11520                        }
11521                    } catch(NumberFormatException e) {
11522                    }
11523                }
11524            }
11525        }
11526        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11527        return prefix + idxStr;
11528    }
11529
11530    private File getNextCodePath(File targetDir, String packageName) {
11531        int suffix = 1;
11532        File result;
11533        do {
11534            result = new File(targetDir, packageName + "-" + suffix);
11535            suffix++;
11536        } while (result.exists());
11537        return result;
11538    }
11539
11540    // Utility method that returns the relative package path with respect
11541    // to the installation directory. Like say for /data/data/com.test-1.apk
11542    // string com.test-1 is returned.
11543    static String deriveCodePathName(String codePath) {
11544        if (codePath == null) {
11545            return null;
11546        }
11547        final File codeFile = new File(codePath);
11548        final String name = codeFile.getName();
11549        if (codeFile.isDirectory()) {
11550            return name;
11551        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11552            final int lastDot = name.lastIndexOf('.');
11553            return name.substring(0, lastDot);
11554        } else {
11555            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11556            return null;
11557        }
11558    }
11559
11560    class PackageInstalledInfo {
11561        String name;
11562        int uid;
11563        // The set of users that originally had this package installed.
11564        int[] origUsers;
11565        // The set of users that now have this package installed.
11566        int[] newUsers;
11567        PackageParser.Package pkg;
11568        int returnCode;
11569        String returnMsg;
11570        PackageRemovedInfo removedInfo;
11571
11572        public void setError(int code, String msg) {
11573            returnCode = code;
11574            returnMsg = msg;
11575            Slog.w(TAG, msg);
11576        }
11577
11578        public void setError(String msg, PackageParserException e) {
11579            returnCode = e.error;
11580            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11581            Slog.w(TAG, msg, e);
11582        }
11583
11584        public void setError(String msg, PackageManagerException e) {
11585            returnCode = e.error;
11586            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11587            Slog.w(TAG, msg, e);
11588        }
11589
11590        // In some error cases we want to convey more info back to the observer
11591        String origPackage;
11592        String origPermission;
11593    }
11594
11595    /*
11596     * Install a non-existing package.
11597     */
11598    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11599            UserHandle user, String installerPackageName, String volumeUuid,
11600            PackageInstalledInfo res) {
11601        // Remember this for later, in case we need to rollback this install
11602        String pkgName = pkg.packageName;
11603
11604        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11605        final boolean dataDirExists = Environment
11606                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11607        synchronized(mPackages) {
11608            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11609                // A package with the same name is already installed, though
11610                // it has been renamed to an older name.  The package we
11611                // are trying to install should be installed as an update to
11612                // the existing one, but that has not been requested, so bail.
11613                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11614                        + " without first uninstalling package running as "
11615                        + mSettings.mRenamedPackages.get(pkgName));
11616                return;
11617            }
11618            if (mPackages.containsKey(pkgName)) {
11619                // Don't allow installation over an existing package with the same name.
11620                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11621                        + " without first uninstalling.");
11622                return;
11623            }
11624        }
11625
11626        try {
11627            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11628                    System.currentTimeMillis(), user);
11629
11630            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11631            // delete the partially installed application. the data directory will have to be
11632            // restored if it was already existing
11633            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11634                // remove package from internal structures.  Note that we want deletePackageX to
11635                // delete the package data and cache directories that it created in
11636                // scanPackageLocked, unless those directories existed before we even tried to
11637                // install.
11638                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11639                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11640                                res.removedInfo, true);
11641            }
11642
11643        } catch (PackageManagerException e) {
11644            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11645        }
11646    }
11647
11648    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11649        // Can't rotate keys during boot or if sharedUser.
11650        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11651                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11652            return false;
11653        }
11654        // app is using upgradeKeySets; make sure all are valid
11655        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11656        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11657        for (int i = 0; i < upgradeKeySets.length; i++) {
11658            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11659                Slog.wtf(TAG, "Package "
11660                         + (oldPs.name != null ? oldPs.name : "<null>")
11661                         + " contains upgrade-key-set reference to unknown key-set: "
11662                         + upgradeKeySets[i]
11663                         + " reverting to signatures check.");
11664                return false;
11665            }
11666        }
11667        return true;
11668    }
11669
11670    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11671        // Upgrade keysets are being used.  Determine if new package has a superset of the
11672        // required keys.
11673        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11674        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11675        for (int i = 0; i < upgradeKeySets.length; i++) {
11676            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11677            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11678                return true;
11679            }
11680        }
11681        return false;
11682    }
11683
11684    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11685            UserHandle user, String installerPackageName, String volumeUuid,
11686            PackageInstalledInfo res) {
11687        final PackageParser.Package oldPackage;
11688        final String pkgName = pkg.packageName;
11689        final int[] allUsers;
11690        final boolean[] perUserInstalled;
11691        final boolean weFroze;
11692
11693        // First find the old package info and check signatures
11694        synchronized(mPackages) {
11695            oldPackage = mPackages.get(pkgName);
11696            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11697            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11698            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11699                if(!checkUpgradeKeySetLP(ps, pkg)) {
11700                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11701                            "New package not signed by keys specified by upgrade-keysets: "
11702                            + pkgName);
11703                    return;
11704                }
11705            } else {
11706                // default to original signature matching
11707                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11708                    != PackageManager.SIGNATURE_MATCH) {
11709                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11710                            "New package has a different signature: " + pkgName);
11711                    return;
11712                }
11713            }
11714
11715            // In case of rollback, remember per-user/profile install state
11716            allUsers = sUserManager.getUserIds();
11717            perUserInstalled = new boolean[allUsers.length];
11718            for (int i = 0; i < allUsers.length; i++) {
11719                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11720            }
11721
11722            // Mark the app as frozen to prevent launching during the upgrade
11723            // process, and then kill all running instances
11724            if (!ps.frozen) {
11725                ps.frozen = true;
11726                weFroze = true;
11727            } else {
11728                weFroze = false;
11729            }
11730        }
11731
11732        // Now that we're guarded by frozen state, kill app during upgrade
11733        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11734
11735        try {
11736            boolean sysPkg = (isSystemApp(oldPackage));
11737            if (sysPkg) {
11738                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11739                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11740            } else {
11741                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11742                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11743            }
11744        } finally {
11745            // Regardless of success or failure of upgrade steps above, always
11746            // unfreeze the package if we froze it
11747            if (weFroze) {
11748                unfreezePackage(pkgName);
11749            }
11750        }
11751    }
11752
11753    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11754            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11755            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11756            String volumeUuid, PackageInstalledInfo res) {
11757        String pkgName = deletedPackage.packageName;
11758        boolean deletedPkg = true;
11759        boolean updatedSettings = false;
11760
11761        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11762                + deletedPackage);
11763        long origUpdateTime;
11764        if (pkg.mExtras != null) {
11765            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11766        } else {
11767            origUpdateTime = 0;
11768        }
11769
11770        // First delete the existing package while retaining the data directory
11771        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11772                res.removedInfo, true)) {
11773            // If the existing package wasn't successfully deleted
11774            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11775            deletedPkg = false;
11776        } else {
11777            // Successfully deleted the old package; proceed with replace.
11778
11779            // If deleted package lived in a container, give users a chance to
11780            // relinquish resources before killing.
11781            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11782                if (DEBUG_INSTALL) {
11783                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11784                }
11785                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11786                final ArrayList<String> pkgList = new ArrayList<String>(1);
11787                pkgList.add(deletedPackage.applicationInfo.packageName);
11788                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11789            }
11790
11791            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11792            try {
11793                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11794                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11795                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11796                        perUserInstalled, res, user);
11797                updatedSettings = true;
11798            } catch (PackageManagerException e) {
11799                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11800            }
11801        }
11802
11803        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11804            // remove package from internal structures.  Note that we want deletePackageX to
11805            // delete the package data and cache directories that it created in
11806            // scanPackageLocked, unless those directories existed before we even tried to
11807            // install.
11808            if(updatedSettings) {
11809                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11810                deletePackageLI(
11811                        pkgName, null, true, allUsers, perUserInstalled,
11812                        PackageManager.DELETE_KEEP_DATA,
11813                                res.removedInfo, true);
11814            }
11815            // Since we failed to install the new package we need to restore the old
11816            // package that we deleted.
11817            if (deletedPkg) {
11818                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11819                File restoreFile = new File(deletedPackage.codePath);
11820                // Parse old package
11821                boolean oldExternal = isExternal(deletedPackage);
11822                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11823                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11824                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11825                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11826                try {
11827                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11828                } catch (PackageManagerException e) {
11829                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11830                            + e.getMessage());
11831                    return;
11832                }
11833                // Restore of old package succeeded. Update permissions.
11834                // writer
11835                synchronized (mPackages) {
11836                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11837                            UPDATE_PERMISSIONS_ALL);
11838                    // can downgrade to reader
11839                    mSettings.writeLPr();
11840                }
11841                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11842            }
11843        }
11844    }
11845
11846    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11847            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11848            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11849            String volumeUuid, PackageInstalledInfo res) {
11850        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11851                + ", old=" + deletedPackage);
11852        boolean disabledSystem = false;
11853        boolean updatedSettings = false;
11854        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11855        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11856                != 0) {
11857            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11858        }
11859        String packageName = deletedPackage.packageName;
11860        if (packageName == null) {
11861            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11862                    "Attempt to delete null packageName.");
11863            return;
11864        }
11865        PackageParser.Package oldPkg;
11866        PackageSetting oldPkgSetting;
11867        // reader
11868        synchronized (mPackages) {
11869            oldPkg = mPackages.get(packageName);
11870            oldPkgSetting = mSettings.mPackages.get(packageName);
11871            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11872                    (oldPkgSetting == null)) {
11873                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11874                        "Couldn't find package:" + packageName + " information");
11875                return;
11876            }
11877        }
11878
11879        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11880        res.removedInfo.removedPackage = packageName;
11881        // Remove existing system package
11882        removePackageLI(oldPkgSetting, true);
11883        // writer
11884        synchronized (mPackages) {
11885            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11886            if (!disabledSystem && deletedPackage != null) {
11887                // We didn't need to disable the .apk as a current system package,
11888                // which means we are replacing another update that is already
11889                // installed.  We need to make sure to delete the older one's .apk.
11890                res.removedInfo.args = createInstallArgsForExisting(0,
11891                        deletedPackage.applicationInfo.getCodePath(),
11892                        deletedPackage.applicationInfo.getResourcePath(),
11893                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11894            } else {
11895                res.removedInfo.args = null;
11896            }
11897        }
11898
11899        // Successfully disabled the old package. Now proceed with re-installation
11900        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11901
11902        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11903        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11904
11905        PackageParser.Package newPackage = null;
11906        try {
11907            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11908            if (newPackage.mExtras != null) {
11909                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11910                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11911                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11912
11913                // is the update attempting to change shared user? that isn't going to work...
11914                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11915                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11916                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11917                            + " to " + newPkgSetting.sharedUser);
11918                    updatedSettings = true;
11919                }
11920            }
11921
11922            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11923                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11924                        perUserInstalled, res, user);
11925                updatedSettings = true;
11926            }
11927
11928        } catch (PackageManagerException e) {
11929            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11930        }
11931
11932        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11933            // Re installation failed. Restore old information
11934            // Remove new pkg information
11935            if (newPackage != null) {
11936                removeInstalledPackageLI(newPackage, true);
11937            }
11938            // Add back the old system package
11939            try {
11940                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11941            } catch (PackageManagerException e) {
11942                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11943            }
11944            // Restore the old system information in Settings
11945            synchronized (mPackages) {
11946                if (disabledSystem) {
11947                    mSettings.enableSystemPackageLPw(packageName);
11948                }
11949                if (updatedSettings) {
11950                    mSettings.setInstallerPackageName(packageName,
11951                            oldPkgSetting.installerPackageName);
11952                }
11953                mSettings.writeLPr();
11954            }
11955        }
11956    }
11957
11958    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11959            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11960            UserHandle user) {
11961        String pkgName = newPackage.packageName;
11962        synchronized (mPackages) {
11963            //write settings. the installStatus will be incomplete at this stage.
11964            //note that the new package setting would have already been
11965            //added to mPackages. It hasn't been persisted yet.
11966            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11967            mSettings.writeLPr();
11968        }
11969
11970        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11971
11972        synchronized (mPackages) {
11973            updatePermissionsLPw(newPackage.packageName, newPackage,
11974                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11975                            ? UPDATE_PERMISSIONS_ALL : 0));
11976            // For system-bundled packages, we assume that installing an upgraded version
11977            // of the package implies that the user actually wants to run that new code,
11978            // so we enable the package.
11979            PackageSetting ps = mSettings.mPackages.get(pkgName);
11980            if (ps != null) {
11981                if (isSystemApp(newPackage)) {
11982                    // NB: implicit assumption that system package upgrades apply to all users
11983                    if (DEBUG_INSTALL) {
11984                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11985                    }
11986                    if (res.origUsers != null) {
11987                        for (int userHandle : res.origUsers) {
11988                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11989                                    userHandle, installerPackageName);
11990                        }
11991                    }
11992                    // Also convey the prior install/uninstall state
11993                    if (allUsers != null && perUserInstalled != null) {
11994                        for (int i = 0; i < allUsers.length; i++) {
11995                            if (DEBUG_INSTALL) {
11996                                Slog.d(TAG, "    user " + allUsers[i]
11997                                        + " => " + perUserInstalled[i]);
11998                            }
11999                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12000                        }
12001                        // these install state changes will be persisted in the
12002                        // upcoming call to mSettings.writeLPr().
12003                    }
12004                }
12005                // It's implied that when a user requests installation, they want the app to be
12006                // installed and enabled.
12007                int userId = user.getIdentifier();
12008                if (userId != UserHandle.USER_ALL) {
12009                    ps.setInstalled(true, userId);
12010                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12011                }
12012            }
12013            res.name = pkgName;
12014            res.uid = newPackage.applicationInfo.uid;
12015            res.pkg = newPackage;
12016            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12017            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12018            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12019            //to update install status
12020            mSettings.writeLPr();
12021        }
12022    }
12023
12024    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12025        final int installFlags = args.installFlags;
12026        final String installerPackageName = args.installerPackageName;
12027        final String volumeUuid = args.volumeUuid;
12028        final File tmpPackageFile = new File(args.getCodePath());
12029        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12030        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12031                || (args.volumeUuid != null));
12032        boolean replace = false;
12033        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12034        if (args.move != null) {
12035            // moving a complete application; perfom an initial scan on the new install location
12036            scanFlags |= SCAN_INITIAL;
12037        }
12038        // Result object to be returned
12039        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12040
12041        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12042        // Retrieve PackageSettings and parse package
12043        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12044                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12045                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12046        PackageParser pp = new PackageParser();
12047        pp.setSeparateProcesses(mSeparateProcesses);
12048        pp.setDisplayMetrics(mMetrics);
12049
12050        final PackageParser.Package pkg;
12051        try {
12052            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12053        } catch (PackageParserException e) {
12054            res.setError("Failed parse during installPackageLI", e);
12055            return;
12056        }
12057
12058        // Mark that we have an install time CPU ABI override.
12059        pkg.cpuAbiOverride = args.abiOverride;
12060
12061        String pkgName = res.name = pkg.packageName;
12062        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12063            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12064                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12065                return;
12066            }
12067        }
12068
12069        try {
12070            pp.collectCertificates(pkg, parseFlags);
12071            pp.collectManifestDigest(pkg);
12072        } catch (PackageParserException e) {
12073            res.setError("Failed collect during installPackageLI", e);
12074            return;
12075        }
12076
12077        /* If the installer passed in a manifest digest, compare it now. */
12078        if (args.manifestDigest != null) {
12079            if (DEBUG_INSTALL) {
12080                final String parsedManifest = pkg.manifestDigest == null ? "null"
12081                        : pkg.manifestDigest.toString();
12082                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12083                        + parsedManifest);
12084            }
12085
12086            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12087                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12088                return;
12089            }
12090        } else if (DEBUG_INSTALL) {
12091            final String parsedManifest = pkg.manifestDigest == null
12092                    ? "null" : pkg.manifestDigest.toString();
12093            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12094        }
12095
12096        // Get rid of all references to package scan path via parser.
12097        pp = null;
12098        String oldCodePath = null;
12099        boolean systemApp = false;
12100        synchronized (mPackages) {
12101            // Check if installing already existing package
12102            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12103                String oldName = mSettings.mRenamedPackages.get(pkgName);
12104                if (pkg.mOriginalPackages != null
12105                        && pkg.mOriginalPackages.contains(oldName)
12106                        && mPackages.containsKey(oldName)) {
12107                    // This package is derived from an original package,
12108                    // and this device has been updating from that original
12109                    // name.  We must continue using the original name, so
12110                    // rename the new package here.
12111                    pkg.setPackageName(oldName);
12112                    pkgName = pkg.packageName;
12113                    replace = true;
12114                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12115                            + oldName + " pkgName=" + pkgName);
12116                } else if (mPackages.containsKey(pkgName)) {
12117                    // This package, under its official name, already exists
12118                    // on the device; we should replace it.
12119                    replace = true;
12120                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12121                }
12122
12123                // Prevent apps opting out from runtime permissions
12124                if (replace) {
12125                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12126                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12127                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12128                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12129                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12130                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12131                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12132                                        + " doesn't support runtime permissions but the old"
12133                                        + " target SDK " + oldTargetSdk + " does.");
12134                        return;
12135                    }
12136                }
12137            }
12138
12139            PackageSetting ps = mSettings.mPackages.get(pkgName);
12140            if (ps != null) {
12141                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12142
12143                // Quick sanity check that we're signed correctly if updating;
12144                // we'll check this again later when scanning, but we want to
12145                // bail early here before tripping over redefined permissions.
12146                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12147                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12148                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12149                                + pkg.packageName + " upgrade keys do not match the "
12150                                + "previously installed version");
12151                        return;
12152                    }
12153                } else {
12154                    try {
12155                        verifySignaturesLP(ps, pkg);
12156                    } catch (PackageManagerException e) {
12157                        res.setError(e.error, e.getMessage());
12158                        return;
12159                    }
12160                }
12161
12162                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12163                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12164                    systemApp = (ps.pkg.applicationInfo.flags &
12165                            ApplicationInfo.FLAG_SYSTEM) != 0;
12166                }
12167                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12168            }
12169
12170            // Check whether the newly-scanned package wants to define an already-defined perm
12171            int N = pkg.permissions.size();
12172            for (int i = N-1; i >= 0; i--) {
12173                PackageParser.Permission perm = pkg.permissions.get(i);
12174                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12175                if (bp != null) {
12176                    // If the defining package is signed with our cert, it's okay.  This
12177                    // also includes the "updating the same package" case, of course.
12178                    // "updating same package" could also involve key-rotation.
12179                    final boolean sigsOk;
12180                    if (bp.sourcePackage.equals(pkg.packageName)
12181                            && (bp.packageSetting instanceof PackageSetting)
12182                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12183                                    scanFlags))) {
12184                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12185                    } else {
12186                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12187                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12188                    }
12189                    if (!sigsOk) {
12190                        // If the owning package is the system itself, we log but allow
12191                        // install to proceed; we fail the install on all other permission
12192                        // redefinitions.
12193                        if (!bp.sourcePackage.equals("android")) {
12194                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12195                                    + pkg.packageName + " attempting to redeclare permission "
12196                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12197                            res.origPermission = perm.info.name;
12198                            res.origPackage = bp.sourcePackage;
12199                            return;
12200                        } else {
12201                            Slog.w(TAG, "Package " + pkg.packageName
12202                                    + " attempting to redeclare system permission "
12203                                    + perm.info.name + "; ignoring new declaration");
12204                            pkg.permissions.remove(i);
12205                        }
12206                    }
12207                }
12208            }
12209
12210        }
12211
12212        if (systemApp && onExternal) {
12213            // Disable updates to system apps on sdcard
12214            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12215                    "Cannot install updates to system apps on sdcard");
12216            return;
12217        }
12218
12219        if (args.move != null) {
12220            // We did an in-place move, so dex is ready to roll
12221            scanFlags |= SCAN_NO_DEX;
12222            scanFlags |= SCAN_MOVE;
12223        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12224            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12225            scanFlags |= SCAN_NO_DEX;
12226
12227            try {
12228                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12229                        true /* extract libs */);
12230            } catch (PackageManagerException pme) {
12231                Slog.e(TAG, "Error deriving application ABI", pme);
12232                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12233                return;
12234            }
12235
12236            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12237            int result = mPackageDexOptimizer
12238                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12239                            false /* defer */, false /* inclDependencies */);
12240            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12241                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12242                return;
12243            }
12244        }
12245
12246        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12247            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12248            return;
12249        }
12250
12251        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12252
12253        if (replace) {
12254            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12255                    installerPackageName, volumeUuid, res);
12256        } else {
12257            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12258                    args.user, installerPackageName, volumeUuid, res);
12259        }
12260        synchronized (mPackages) {
12261            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12262            if (ps != null) {
12263                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12264            }
12265        }
12266    }
12267
12268    private void startIntentFilterVerifications(int userId, boolean replacing,
12269            PackageParser.Package pkg) {
12270        if (mIntentFilterVerifierComponent == null) {
12271            Slog.w(TAG, "No IntentFilter verification will not be done as "
12272                    + "there is no IntentFilterVerifier available!");
12273            return;
12274        }
12275
12276        final int verifierUid = getPackageUid(
12277                mIntentFilterVerifierComponent.getPackageName(),
12278                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12279
12280        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12281        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12282        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12283        mHandler.sendMessage(msg);
12284    }
12285
12286    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12287            PackageParser.Package pkg) {
12288        int size = pkg.activities.size();
12289        if (size == 0) {
12290            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12291                    "No activity, so no need to verify any IntentFilter!");
12292            return;
12293        }
12294
12295        final boolean hasDomainURLs = hasDomainURLs(pkg);
12296        if (!hasDomainURLs) {
12297            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12298                    "No domain URLs, so no need to verify any IntentFilter!");
12299            return;
12300        }
12301
12302        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12303                + " if any IntentFilter from the " + size
12304                + " Activities needs verification ...");
12305
12306        int count = 0;
12307        final String packageName = pkg.packageName;
12308
12309        synchronized (mPackages) {
12310            // If this is a new install and we see that we've already run verification for this
12311            // package, we have nothing to do: it means the state was restored from backup.
12312            if (!replacing) {
12313                IntentFilterVerificationInfo ivi =
12314                        mSettings.getIntentFilterVerificationLPr(packageName);
12315                if (ivi != null) {
12316                    if (DEBUG_DOMAIN_VERIFICATION) {
12317                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12318                                + ivi.getStatusString());
12319                    }
12320                    return;
12321                }
12322            }
12323
12324            // If any filters need to be verified, then all need to be.
12325            boolean needToVerify = false;
12326            for (PackageParser.Activity a : pkg.activities) {
12327                for (ActivityIntentInfo filter : a.intents) {
12328                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12329                        if (DEBUG_DOMAIN_VERIFICATION) {
12330                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12331                        }
12332                        needToVerify = true;
12333                        break;
12334                    }
12335                }
12336            }
12337
12338            if (needToVerify) {
12339                final int verificationId = mIntentFilterVerificationToken++;
12340                for (PackageParser.Activity a : pkg.activities) {
12341                    for (ActivityIntentInfo filter : a.intents) {
12342                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12343                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12344                                    "Verification needed for IntentFilter:" + filter.toString());
12345                            mIntentFilterVerifier.addOneIntentFilterVerification(
12346                                    verifierUid, userId, verificationId, filter, packageName);
12347                            count++;
12348                        }
12349                    }
12350                }
12351            }
12352        }
12353
12354        if (count > 0) {
12355            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12356                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12357                    +  " for userId:" + userId);
12358            mIntentFilterVerifier.startVerifications(userId);
12359        } else {
12360            if (DEBUG_DOMAIN_VERIFICATION) {
12361                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12362            }
12363        }
12364    }
12365
12366    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12367        final ComponentName cn  = filter.activity.getComponentName();
12368        final String packageName = cn.getPackageName();
12369
12370        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12371                packageName);
12372        if (ivi == null) {
12373            return true;
12374        }
12375        int status = ivi.getStatus();
12376        switch (status) {
12377            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12378            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12379                return true;
12380
12381            default:
12382                // Nothing to do
12383                return false;
12384        }
12385    }
12386
12387    private static boolean isMultiArch(PackageSetting ps) {
12388        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12389    }
12390
12391    private static boolean isMultiArch(ApplicationInfo info) {
12392        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12393    }
12394
12395    private static boolean isExternal(PackageParser.Package pkg) {
12396        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12397    }
12398
12399    private static boolean isExternal(PackageSetting ps) {
12400        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12401    }
12402
12403    private static boolean isExternal(ApplicationInfo info) {
12404        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12405    }
12406
12407    private static boolean isSystemApp(PackageParser.Package pkg) {
12408        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12409    }
12410
12411    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12412        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12413    }
12414
12415    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12416        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12417    }
12418
12419    private static boolean isSystemApp(PackageSetting ps) {
12420        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12421    }
12422
12423    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12424        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12425    }
12426
12427    private int packageFlagsToInstallFlags(PackageSetting ps) {
12428        int installFlags = 0;
12429        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12430            // This existing package was an external ASEC install when we have
12431            // the external flag without a UUID
12432            installFlags |= PackageManager.INSTALL_EXTERNAL;
12433        }
12434        if (ps.isForwardLocked()) {
12435            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12436        }
12437        return installFlags;
12438    }
12439
12440    private void deleteTempPackageFiles() {
12441        final FilenameFilter filter = new FilenameFilter() {
12442            public boolean accept(File dir, String name) {
12443                return name.startsWith("vmdl") && name.endsWith(".tmp");
12444            }
12445        };
12446        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12447            file.delete();
12448        }
12449    }
12450
12451    @Override
12452    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12453            int flags) {
12454        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12455                flags);
12456    }
12457
12458    @Override
12459    public void deletePackage(final String packageName,
12460            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12461        mContext.enforceCallingOrSelfPermission(
12462                android.Manifest.permission.DELETE_PACKAGES, null);
12463        Preconditions.checkNotNull(packageName);
12464        Preconditions.checkNotNull(observer);
12465        final int uid = Binder.getCallingUid();
12466        if (UserHandle.getUserId(uid) != userId) {
12467            mContext.enforceCallingPermission(
12468                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12469                    "deletePackage for user " + userId);
12470        }
12471        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12472            try {
12473                observer.onPackageDeleted(packageName,
12474                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12475            } catch (RemoteException re) {
12476            }
12477            return;
12478        }
12479
12480        boolean uninstallBlocked = false;
12481        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12482            int[] users = sUserManager.getUserIds();
12483            for (int i = 0; i < users.length; ++i) {
12484                if (getBlockUninstallForUser(packageName, users[i])) {
12485                    uninstallBlocked = true;
12486                    break;
12487                }
12488            }
12489        } else {
12490            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12491        }
12492        if (uninstallBlocked) {
12493            try {
12494                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12495                        null);
12496            } catch (RemoteException re) {
12497            }
12498            return;
12499        }
12500
12501        if (DEBUG_REMOVE) {
12502            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12503        }
12504        // Queue up an async operation since the package deletion may take a little while.
12505        mHandler.post(new Runnable() {
12506            public void run() {
12507                mHandler.removeCallbacks(this);
12508                final int returnCode = deletePackageX(packageName, userId, flags);
12509                if (observer != null) {
12510                    try {
12511                        observer.onPackageDeleted(packageName, returnCode, null);
12512                    } catch (RemoteException e) {
12513                        Log.i(TAG, "Observer no longer exists.");
12514                    } //end catch
12515                } //end if
12516            } //end run
12517        });
12518    }
12519
12520    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12521        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12522                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12523        try {
12524            if (dpm != null) {
12525                if (dpm.isDeviceOwner(packageName)) {
12526                    return true;
12527                }
12528                int[] users;
12529                if (userId == UserHandle.USER_ALL) {
12530                    users = sUserManager.getUserIds();
12531                } else {
12532                    users = new int[]{userId};
12533                }
12534                for (int i = 0; i < users.length; ++i) {
12535                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12536                        return true;
12537                    }
12538                }
12539            }
12540        } catch (RemoteException e) {
12541        }
12542        return false;
12543    }
12544
12545    /**
12546     *  This method is an internal method that could be get invoked either
12547     *  to delete an installed package or to clean up a failed installation.
12548     *  After deleting an installed package, a broadcast is sent to notify any
12549     *  listeners that the package has been installed. For cleaning up a failed
12550     *  installation, the broadcast is not necessary since the package's
12551     *  installation wouldn't have sent the initial broadcast either
12552     *  The key steps in deleting a package are
12553     *  deleting the package information in internal structures like mPackages,
12554     *  deleting the packages base directories through installd
12555     *  updating mSettings to reflect current status
12556     *  persisting settings for later use
12557     *  sending a broadcast if necessary
12558     */
12559    private int deletePackageX(String packageName, int userId, int flags) {
12560        final PackageRemovedInfo info = new PackageRemovedInfo();
12561        final boolean res;
12562
12563        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12564                ? UserHandle.ALL : new UserHandle(userId);
12565
12566        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12567            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12568            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12569        }
12570
12571        boolean removedForAllUsers = false;
12572        boolean systemUpdate = false;
12573
12574        // for the uninstall-updates case and restricted profiles, remember the per-
12575        // userhandle installed state
12576        int[] allUsers;
12577        boolean[] perUserInstalled;
12578        synchronized (mPackages) {
12579            PackageSetting ps = mSettings.mPackages.get(packageName);
12580            allUsers = sUserManager.getUserIds();
12581            perUserInstalled = new boolean[allUsers.length];
12582            for (int i = 0; i < allUsers.length; i++) {
12583                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12584            }
12585        }
12586
12587        synchronized (mInstallLock) {
12588            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12589            res = deletePackageLI(packageName, removeForUser,
12590                    true, allUsers, perUserInstalled,
12591                    flags | REMOVE_CHATTY, info, true);
12592            systemUpdate = info.isRemovedPackageSystemUpdate;
12593            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12594                removedForAllUsers = true;
12595            }
12596            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12597                    + " removedForAllUsers=" + removedForAllUsers);
12598        }
12599
12600        if (res) {
12601            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12602
12603            // If the removed package was a system update, the old system package
12604            // was re-enabled; we need to broadcast this information
12605            if (systemUpdate) {
12606                Bundle extras = new Bundle(1);
12607                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12608                        ? info.removedAppId : info.uid);
12609                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12610
12611                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12612                        extras, null, null, null);
12613                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12614                        extras, null, null, null);
12615                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12616                        null, packageName, null, null);
12617            }
12618        }
12619        // Force a gc here.
12620        Runtime.getRuntime().gc();
12621        // Delete the resources here after sending the broadcast to let
12622        // other processes clean up before deleting resources.
12623        if (info.args != null) {
12624            synchronized (mInstallLock) {
12625                info.args.doPostDeleteLI(true);
12626            }
12627        }
12628
12629        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12630    }
12631
12632    class PackageRemovedInfo {
12633        String removedPackage;
12634        int uid = -1;
12635        int removedAppId = -1;
12636        int[] removedUsers = null;
12637        boolean isRemovedPackageSystemUpdate = false;
12638        // Clean up resources deleted packages.
12639        InstallArgs args = null;
12640
12641        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12642            Bundle extras = new Bundle(1);
12643            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12644            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12645            if (replacing) {
12646                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12647            }
12648            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12649            if (removedPackage != null) {
12650                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12651                        extras, null, null, removedUsers);
12652                if (fullRemove && !replacing) {
12653                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12654                            extras, null, null, removedUsers);
12655                }
12656            }
12657            if (removedAppId >= 0) {
12658                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12659                        removedUsers);
12660            }
12661        }
12662    }
12663
12664    /*
12665     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12666     * flag is not set, the data directory is removed as well.
12667     * make sure this flag is set for partially installed apps. If not its meaningless to
12668     * delete a partially installed application.
12669     */
12670    private void removePackageDataLI(PackageSetting ps,
12671            int[] allUserHandles, boolean[] perUserInstalled,
12672            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12673        String packageName = ps.name;
12674        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12675        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12676        // Retrieve object to delete permissions for shared user later on
12677        final PackageSetting deletedPs;
12678        // reader
12679        synchronized (mPackages) {
12680            deletedPs = mSettings.mPackages.get(packageName);
12681            if (outInfo != null) {
12682                outInfo.removedPackage = packageName;
12683                outInfo.removedUsers = deletedPs != null
12684                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12685                        : null;
12686            }
12687        }
12688        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12689            removeDataDirsLI(ps.volumeUuid, packageName);
12690            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12691        }
12692        // writer
12693        synchronized (mPackages) {
12694            if (deletedPs != null) {
12695                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12696                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12697                    clearDefaultBrowserIfNeeded(packageName);
12698                    if (outInfo != null) {
12699                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12700                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12701                    }
12702                    updatePermissionsLPw(deletedPs.name, null, 0);
12703                    if (deletedPs.sharedUser != null) {
12704                        // Remove permissions associated with package. Since runtime
12705                        // permissions are per user we have to kill the removed package
12706                        // or packages running under the shared user of the removed
12707                        // package if revoking the permissions requested only by the removed
12708                        // package is successful and this causes a change in gids.
12709                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12710                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12711                                    userId);
12712                            if (userIdToKill == UserHandle.USER_ALL
12713                                    || userIdToKill >= UserHandle.USER_OWNER) {
12714                                // If gids changed for this user, kill all affected packages.
12715                                mHandler.post(new Runnable() {
12716                                    @Override
12717                                    public void run() {
12718                                        // This has to happen with no lock held.
12719                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12720                                                KILL_APP_REASON_GIDS_CHANGED);
12721                                    }
12722                                });
12723                                break;
12724                            }
12725                        }
12726                    }
12727                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12728                }
12729                // make sure to preserve per-user disabled state if this removal was just
12730                // a downgrade of a system app to the factory package
12731                if (allUserHandles != null && perUserInstalled != null) {
12732                    if (DEBUG_REMOVE) {
12733                        Slog.d(TAG, "Propagating install state across downgrade");
12734                    }
12735                    for (int i = 0; i < allUserHandles.length; i++) {
12736                        if (DEBUG_REMOVE) {
12737                            Slog.d(TAG, "    user " + allUserHandles[i]
12738                                    + " => " + perUserInstalled[i]);
12739                        }
12740                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12741                    }
12742                }
12743            }
12744            // can downgrade to reader
12745            if (writeSettings) {
12746                // Save settings now
12747                mSettings.writeLPr();
12748            }
12749        }
12750        if (outInfo != null) {
12751            // A user ID was deleted here. Go through all users and remove it
12752            // from KeyStore.
12753            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12754        }
12755    }
12756
12757    static boolean locationIsPrivileged(File path) {
12758        try {
12759            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12760                    .getCanonicalPath();
12761            return path.getCanonicalPath().startsWith(privilegedAppDir);
12762        } catch (IOException e) {
12763            Slog.e(TAG, "Unable to access code path " + path);
12764        }
12765        return false;
12766    }
12767
12768    /*
12769     * Tries to delete system package.
12770     */
12771    private boolean deleteSystemPackageLI(PackageSetting newPs,
12772            int[] allUserHandles, boolean[] perUserInstalled,
12773            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12774        final boolean applyUserRestrictions
12775                = (allUserHandles != null) && (perUserInstalled != null);
12776        PackageSetting disabledPs = null;
12777        // Confirm if the system package has been updated
12778        // An updated system app can be deleted. This will also have to restore
12779        // the system pkg from system partition
12780        // reader
12781        synchronized (mPackages) {
12782            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12783        }
12784        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12785                + " disabledPs=" + disabledPs);
12786        if (disabledPs == null) {
12787            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12788            return false;
12789        } else if (DEBUG_REMOVE) {
12790            Slog.d(TAG, "Deleting system pkg from data partition");
12791        }
12792        if (DEBUG_REMOVE) {
12793            if (applyUserRestrictions) {
12794                Slog.d(TAG, "Remembering install states:");
12795                for (int i = 0; i < allUserHandles.length; i++) {
12796                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12797                }
12798            }
12799        }
12800        // Delete the updated package
12801        outInfo.isRemovedPackageSystemUpdate = true;
12802        if (disabledPs.versionCode < newPs.versionCode) {
12803            // Delete data for downgrades
12804            flags &= ~PackageManager.DELETE_KEEP_DATA;
12805        } else {
12806            // Preserve data by setting flag
12807            flags |= PackageManager.DELETE_KEEP_DATA;
12808        }
12809        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12810                allUserHandles, perUserInstalled, outInfo, writeSettings);
12811        if (!ret) {
12812            return false;
12813        }
12814        // writer
12815        synchronized (mPackages) {
12816            // Reinstate the old system package
12817            mSettings.enableSystemPackageLPw(newPs.name);
12818            // Remove any native libraries from the upgraded package.
12819            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12820        }
12821        // Install the system package
12822        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12823        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12824        if (locationIsPrivileged(disabledPs.codePath)) {
12825            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12826        }
12827
12828        final PackageParser.Package newPkg;
12829        try {
12830            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12831        } catch (PackageManagerException e) {
12832            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12833            return false;
12834        }
12835
12836        // writer
12837        synchronized (mPackages) {
12838            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12839
12840            // Propagate the permissions state as we do want to drop on the floor
12841            // runtime permissions. The update permissions method below will take
12842            // care of removing obsolete permissions and grant install permissions.
12843            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12844            updatePermissionsLPw(newPkg.packageName, newPkg,
12845                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12846
12847            if (applyUserRestrictions) {
12848                if (DEBUG_REMOVE) {
12849                    Slog.d(TAG, "Propagating install state across reinstall");
12850                }
12851                for (int i = 0; i < allUserHandles.length; i++) {
12852                    if (DEBUG_REMOVE) {
12853                        Slog.d(TAG, "    user " + allUserHandles[i]
12854                                + " => " + perUserInstalled[i]);
12855                    }
12856                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12857                }
12858                // Regardless of writeSettings we need to ensure that this restriction
12859                // state propagation is persisted
12860                mSettings.writeAllUsersPackageRestrictionsLPr();
12861            }
12862            // can downgrade to reader here
12863            if (writeSettings) {
12864                mSettings.writeLPr();
12865            }
12866        }
12867        return true;
12868    }
12869
12870    private boolean deleteInstalledPackageLI(PackageSetting ps,
12871            boolean deleteCodeAndResources, int flags,
12872            int[] allUserHandles, boolean[] perUserInstalled,
12873            PackageRemovedInfo outInfo, boolean writeSettings) {
12874        if (outInfo != null) {
12875            outInfo.uid = ps.appId;
12876        }
12877
12878        // Delete package data from internal structures and also remove data if flag is set
12879        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12880
12881        // Delete application code and resources
12882        if (deleteCodeAndResources && (outInfo != null)) {
12883            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12884                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12885            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12886        }
12887        return true;
12888    }
12889
12890    @Override
12891    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12892            int userId) {
12893        mContext.enforceCallingOrSelfPermission(
12894                android.Manifest.permission.DELETE_PACKAGES, null);
12895        synchronized (mPackages) {
12896            PackageSetting ps = mSettings.mPackages.get(packageName);
12897            if (ps == null) {
12898                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12899                return false;
12900            }
12901            if (!ps.getInstalled(userId)) {
12902                // Can't block uninstall for an app that is not installed or enabled.
12903                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12904                return false;
12905            }
12906            ps.setBlockUninstall(blockUninstall, userId);
12907            mSettings.writePackageRestrictionsLPr(userId);
12908        }
12909        return true;
12910    }
12911
12912    @Override
12913    public boolean getBlockUninstallForUser(String packageName, int userId) {
12914        synchronized (mPackages) {
12915            PackageSetting ps = mSettings.mPackages.get(packageName);
12916            if (ps == null) {
12917                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12918                return false;
12919            }
12920            return ps.getBlockUninstall(userId);
12921        }
12922    }
12923
12924    /*
12925     * This method handles package deletion in general
12926     */
12927    private boolean deletePackageLI(String packageName, UserHandle user,
12928            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12929            int flags, PackageRemovedInfo outInfo,
12930            boolean writeSettings) {
12931        if (packageName == null) {
12932            Slog.w(TAG, "Attempt to delete null packageName.");
12933            return false;
12934        }
12935        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12936        PackageSetting ps;
12937        boolean dataOnly = false;
12938        int removeUser = -1;
12939        int appId = -1;
12940        synchronized (mPackages) {
12941            ps = mSettings.mPackages.get(packageName);
12942            if (ps == null) {
12943                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12944                return false;
12945            }
12946            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12947                    && user.getIdentifier() != UserHandle.USER_ALL) {
12948                // The caller is asking that the package only be deleted for a single
12949                // user.  To do this, we just mark its uninstalled state and delete
12950                // its data.  If this is a system app, we only allow this to happen if
12951                // they have set the special DELETE_SYSTEM_APP which requests different
12952                // semantics than normal for uninstalling system apps.
12953                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12954                ps.setUserState(user.getIdentifier(),
12955                        COMPONENT_ENABLED_STATE_DEFAULT,
12956                        false, //installed
12957                        true,  //stopped
12958                        true,  //notLaunched
12959                        false, //hidden
12960                        null, null, null,
12961                        false, // blockUninstall
12962                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12963                if (!isSystemApp(ps)) {
12964                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12965                        // Other user still have this package installed, so all
12966                        // we need to do is clear this user's data and save that
12967                        // it is uninstalled.
12968                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12969                        removeUser = user.getIdentifier();
12970                        appId = ps.appId;
12971                        scheduleWritePackageRestrictionsLocked(removeUser);
12972                    } else {
12973                        // We need to set it back to 'installed' so the uninstall
12974                        // broadcasts will be sent correctly.
12975                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12976                        ps.setInstalled(true, user.getIdentifier());
12977                    }
12978                } else {
12979                    // This is a system app, so we assume that the
12980                    // other users still have this package installed, so all
12981                    // we need to do is clear this user's data and save that
12982                    // it is uninstalled.
12983                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12984                    removeUser = user.getIdentifier();
12985                    appId = ps.appId;
12986                    scheduleWritePackageRestrictionsLocked(removeUser);
12987                }
12988            }
12989        }
12990
12991        if (removeUser >= 0) {
12992            // From above, we determined that we are deleting this only
12993            // for a single user.  Continue the work here.
12994            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12995            if (outInfo != null) {
12996                outInfo.removedPackage = packageName;
12997                outInfo.removedAppId = appId;
12998                outInfo.removedUsers = new int[] {removeUser};
12999            }
13000            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13001            removeKeystoreDataIfNeeded(removeUser, appId);
13002            schedulePackageCleaning(packageName, removeUser, false);
13003            synchronized (mPackages) {
13004                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13005                    scheduleWritePackageRestrictionsLocked(removeUser);
13006                }
13007                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13008            }
13009            return true;
13010        }
13011
13012        if (dataOnly) {
13013            // Delete application data first
13014            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13015            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13016            return true;
13017        }
13018
13019        boolean ret = false;
13020        if (isSystemApp(ps)) {
13021            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13022            // When an updated system application is deleted we delete the existing resources as well and
13023            // fall back to existing code in system partition
13024            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13025                    flags, outInfo, writeSettings);
13026        } else {
13027            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13028            // Kill application pre-emptively especially for apps on sd.
13029            killApplication(packageName, ps.appId, "uninstall pkg");
13030            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13031                    allUserHandles, perUserInstalled,
13032                    outInfo, writeSettings);
13033        }
13034
13035        return ret;
13036    }
13037
13038    private final class ClearStorageConnection implements ServiceConnection {
13039        IMediaContainerService mContainerService;
13040
13041        @Override
13042        public void onServiceConnected(ComponentName name, IBinder service) {
13043            synchronized (this) {
13044                mContainerService = IMediaContainerService.Stub.asInterface(service);
13045                notifyAll();
13046            }
13047        }
13048
13049        @Override
13050        public void onServiceDisconnected(ComponentName name) {
13051        }
13052    }
13053
13054    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13055        final boolean mounted;
13056        if (Environment.isExternalStorageEmulated()) {
13057            mounted = true;
13058        } else {
13059            final String status = Environment.getExternalStorageState();
13060
13061            mounted = status.equals(Environment.MEDIA_MOUNTED)
13062                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13063        }
13064
13065        if (!mounted) {
13066            return;
13067        }
13068
13069        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13070        int[] users;
13071        if (userId == UserHandle.USER_ALL) {
13072            users = sUserManager.getUserIds();
13073        } else {
13074            users = new int[] { userId };
13075        }
13076        final ClearStorageConnection conn = new ClearStorageConnection();
13077        if (mContext.bindServiceAsUser(
13078                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13079            try {
13080                for (int curUser : users) {
13081                    long timeout = SystemClock.uptimeMillis() + 5000;
13082                    synchronized (conn) {
13083                        long now = SystemClock.uptimeMillis();
13084                        while (conn.mContainerService == null && now < timeout) {
13085                            try {
13086                                conn.wait(timeout - now);
13087                            } catch (InterruptedException e) {
13088                            }
13089                        }
13090                    }
13091                    if (conn.mContainerService == null) {
13092                        return;
13093                    }
13094
13095                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13096                    clearDirectory(conn.mContainerService,
13097                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13098                    if (allData) {
13099                        clearDirectory(conn.mContainerService,
13100                                userEnv.buildExternalStorageAppDataDirs(packageName));
13101                        clearDirectory(conn.mContainerService,
13102                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13103                    }
13104                }
13105            } finally {
13106                mContext.unbindService(conn);
13107            }
13108        }
13109    }
13110
13111    @Override
13112    public void clearApplicationUserData(final String packageName,
13113            final IPackageDataObserver observer, final int userId) {
13114        mContext.enforceCallingOrSelfPermission(
13115                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13116        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13117        // Queue up an async operation since the package deletion may take a little while.
13118        mHandler.post(new Runnable() {
13119            public void run() {
13120                mHandler.removeCallbacks(this);
13121                final boolean succeeded;
13122                synchronized (mInstallLock) {
13123                    succeeded = clearApplicationUserDataLI(packageName, userId);
13124                }
13125                clearExternalStorageDataSync(packageName, userId, true);
13126                if (succeeded) {
13127                    // invoke DeviceStorageMonitor's update method to clear any notifications
13128                    DeviceStorageMonitorInternal
13129                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13130                    if (dsm != null) {
13131                        dsm.checkMemory();
13132                    }
13133                }
13134                if(observer != null) {
13135                    try {
13136                        observer.onRemoveCompleted(packageName, succeeded);
13137                    } catch (RemoteException e) {
13138                        Log.i(TAG, "Observer no longer exists.");
13139                    }
13140                } //end if observer
13141            } //end run
13142        });
13143    }
13144
13145    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13146        if (packageName == null) {
13147            Slog.w(TAG, "Attempt to delete null packageName.");
13148            return false;
13149        }
13150
13151        // Try finding details about the requested package
13152        PackageParser.Package pkg;
13153        synchronized (mPackages) {
13154            pkg = mPackages.get(packageName);
13155            if (pkg == null) {
13156                final PackageSetting ps = mSettings.mPackages.get(packageName);
13157                if (ps != null) {
13158                    pkg = ps.pkg;
13159                }
13160            }
13161
13162            if (pkg == null) {
13163                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13164                return false;
13165            }
13166
13167            PackageSetting ps = (PackageSetting) pkg.mExtras;
13168            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13169        }
13170
13171        // Always delete data directories for package, even if we found no other
13172        // record of app. This helps users recover from UID mismatches without
13173        // resorting to a full data wipe.
13174        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13175        if (retCode < 0) {
13176            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13177            return false;
13178        }
13179
13180        final int appId = pkg.applicationInfo.uid;
13181        removeKeystoreDataIfNeeded(userId, appId);
13182
13183        // Create a native library symlink only if we have native libraries
13184        // and if the native libraries are 32 bit libraries. We do not provide
13185        // this symlink for 64 bit libraries.
13186        if (pkg.applicationInfo.primaryCpuAbi != null &&
13187                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13188            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13189            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13190                    nativeLibPath, userId) < 0) {
13191                Slog.w(TAG, "Failed linking native library dir");
13192                return false;
13193            }
13194        }
13195
13196        return true;
13197    }
13198
13199    /**
13200     * Reverts user permission state changes (permissions and flags).
13201     *
13202     * @param ps The package for which to reset.
13203     * @param userId The device user for which to do a reset.
13204     */
13205    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13206            final PackageSetting ps, final int userId) {
13207        if (ps.pkg == null) {
13208            return;
13209        }
13210
13211        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13212                | FLAG_PERMISSION_USER_FIXED
13213                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13214
13215        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13216                | FLAG_PERMISSION_POLICY_FIXED;
13217
13218        boolean writeInstallPermissions = false;
13219        boolean writeRuntimePermissions = false;
13220
13221        final int permissionCount = ps.pkg.requestedPermissions.size();
13222        for (int i = 0; i < permissionCount; i++) {
13223            String permission = ps.pkg.requestedPermissions.get(i);
13224
13225            BasePermission bp = mSettings.mPermissions.get(permission);
13226            if (bp == null) {
13227                continue;
13228            }
13229
13230            // If shared user we just reset the state to which only this app contributed.
13231            if (ps.sharedUser != null) {
13232                boolean used = false;
13233                final int packageCount = ps.sharedUser.packages.size();
13234                for (int j = 0; j < packageCount; j++) {
13235                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13236                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13237                            && pkg.pkg.requestedPermissions.contains(permission)) {
13238                        used = true;
13239                        break;
13240                    }
13241                }
13242                if (used) {
13243                    continue;
13244                }
13245            }
13246
13247            PermissionsState permissionsState = ps.getPermissionsState();
13248
13249            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13250
13251            // Always clear the user settable flags.
13252            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13253                    bp.name) != null;
13254            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13255                if (hasInstallState) {
13256                    writeInstallPermissions = true;
13257                } else {
13258                    writeRuntimePermissions = true;
13259                }
13260            }
13261
13262            // Below is only runtime permission handling.
13263            if (!bp.isRuntime()) {
13264                continue;
13265            }
13266
13267            // Never clobber system or policy.
13268            if ((oldFlags & policyOrSystemFlags) != 0) {
13269                continue;
13270            }
13271
13272            // If this permission was granted by default, make sure it is.
13273            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13274                if (permissionsState.grantRuntimePermission(bp, userId)
13275                        != PERMISSION_OPERATION_FAILURE) {
13276                    writeRuntimePermissions = true;
13277                }
13278            } else {
13279                // Otherwise, reset the permission.
13280                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13281                switch (revokeResult) {
13282                    case PERMISSION_OPERATION_SUCCESS: {
13283                        writeRuntimePermissions = true;
13284                    } break;
13285
13286                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13287                        writeRuntimePermissions = true;
13288                        // If gids changed for this user, kill all affected packages.
13289                        mHandler.post(new Runnable() {
13290                            @Override
13291                            public void run() {
13292                                // This has to happen with no lock held.
13293                                killSettingPackagesForUser(ps, userId,
13294                                        KILL_APP_REASON_GIDS_CHANGED);
13295                            }
13296                        });
13297                    } break;
13298                }
13299            }
13300        }
13301
13302        // Synchronously write as we are taking permissions away.
13303        if (writeRuntimePermissions) {
13304            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13305        }
13306
13307        // Synchronously write as we are taking permissions away.
13308        if (writeInstallPermissions) {
13309            mSettings.writeLPr();
13310        }
13311    }
13312
13313    /**
13314     * Remove entries from the keystore daemon. Will only remove it if the
13315     * {@code appId} is valid.
13316     */
13317    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13318        if (appId < 0) {
13319            return;
13320        }
13321
13322        final KeyStore keyStore = KeyStore.getInstance();
13323        if (keyStore != null) {
13324            if (userId == UserHandle.USER_ALL) {
13325                for (final int individual : sUserManager.getUserIds()) {
13326                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13327                }
13328            } else {
13329                keyStore.clearUid(UserHandle.getUid(userId, appId));
13330            }
13331        } else {
13332            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13333        }
13334    }
13335
13336    @Override
13337    public void deleteApplicationCacheFiles(final String packageName,
13338            final IPackageDataObserver observer) {
13339        mContext.enforceCallingOrSelfPermission(
13340                android.Manifest.permission.DELETE_CACHE_FILES, null);
13341        // Queue up an async operation since the package deletion may take a little while.
13342        final int userId = UserHandle.getCallingUserId();
13343        mHandler.post(new Runnable() {
13344            public void run() {
13345                mHandler.removeCallbacks(this);
13346                final boolean succeded;
13347                synchronized (mInstallLock) {
13348                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13349                }
13350                clearExternalStorageDataSync(packageName, userId, false);
13351                if (observer != null) {
13352                    try {
13353                        observer.onRemoveCompleted(packageName, succeded);
13354                    } catch (RemoteException e) {
13355                        Log.i(TAG, "Observer no longer exists.");
13356                    }
13357                } //end if observer
13358            } //end run
13359        });
13360    }
13361
13362    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13363        if (packageName == null) {
13364            Slog.w(TAG, "Attempt to delete null packageName.");
13365            return false;
13366        }
13367        PackageParser.Package p;
13368        synchronized (mPackages) {
13369            p = mPackages.get(packageName);
13370        }
13371        if (p == null) {
13372            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13373            return false;
13374        }
13375        final ApplicationInfo applicationInfo = p.applicationInfo;
13376        if (applicationInfo == null) {
13377            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13378            return false;
13379        }
13380        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13381        if (retCode < 0) {
13382            Slog.w(TAG, "Couldn't remove cache files for package: "
13383                       + packageName + " u" + userId);
13384            return false;
13385        }
13386        return true;
13387    }
13388
13389    @Override
13390    public void getPackageSizeInfo(final String packageName, int userHandle,
13391            final IPackageStatsObserver observer) {
13392        mContext.enforceCallingOrSelfPermission(
13393                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13394        if (packageName == null) {
13395            throw new IllegalArgumentException("Attempt to get size of null packageName");
13396        }
13397
13398        PackageStats stats = new PackageStats(packageName, userHandle);
13399
13400        /*
13401         * Queue up an async operation since the package measurement may take a
13402         * little while.
13403         */
13404        Message msg = mHandler.obtainMessage(INIT_COPY);
13405        msg.obj = new MeasureParams(stats, observer);
13406        mHandler.sendMessage(msg);
13407    }
13408
13409    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13410            PackageStats pStats) {
13411        if (packageName == null) {
13412            Slog.w(TAG, "Attempt to get size of null packageName.");
13413            return false;
13414        }
13415        PackageParser.Package p;
13416        boolean dataOnly = false;
13417        String libDirRoot = null;
13418        String asecPath = null;
13419        PackageSetting ps = null;
13420        synchronized (mPackages) {
13421            p = mPackages.get(packageName);
13422            ps = mSettings.mPackages.get(packageName);
13423            if(p == null) {
13424                dataOnly = true;
13425                if((ps == null) || (ps.pkg == null)) {
13426                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13427                    return false;
13428                }
13429                p = ps.pkg;
13430            }
13431            if (ps != null) {
13432                libDirRoot = ps.legacyNativeLibraryPathString;
13433            }
13434            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13435                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13436                if (secureContainerId != null) {
13437                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13438                }
13439            }
13440        }
13441        String publicSrcDir = null;
13442        if(!dataOnly) {
13443            final ApplicationInfo applicationInfo = p.applicationInfo;
13444            if (applicationInfo == null) {
13445                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13446                return false;
13447            }
13448            if (p.isForwardLocked()) {
13449                publicSrcDir = applicationInfo.getBaseResourcePath();
13450            }
13451        }
13452        // TODO: extend to measure size of split APKs
13453        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13454        // not just the first level.
13455        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13456        // just the primary.
13457        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13458        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13459                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13460        if (res < 0) {
13461            return false;
13462        }
13463
13464        // Fix-up for forward-locked applications in ASEC containers.
13465        if (!isExternal(p)) {
13466            pStats.codeSize += pStats.externalCodeSize;
13467            pStats.externalCodeSize = 0L;
13468        }
13469
13470        return true;
13471    }
13472
13473
13474    @Override
13475    public void addPackageToPreferred(String packageName) {
13476        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13477    }
13478
13479    @Override
13480    public void removePackageFromPreferred(String packageName) {
13481        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13482    }
13483
13484    @Override
13485    public List<PackageInfo> getPreferredPackages(int flags) {
13486        return new ArrayList<PackageInfo>();
13487    }
13488
13489    private int getUidTargetSdkVersionLockedLPr(int uid) {
13490        Object obj = mSettings.getUserIdLPr(uid);
13491        if (obj instanceof SharedUserSetting) {
13492            final SharedUserSetting sus = (SharedUserSetting) obj;
13493            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13494            final Iterator<PackageSetting> it = sus.packages.iterator();
13495            while (it.hasNext()) {
13496                final PackageSetting ps = it.next();
13497                if (ps.pkg != null) {
13498                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13499                    if (v < vers) vers = v;
13500                }
13501            }
13502            return vers;
13503        } else if (obj instanceof PackageSetting) {
13504            final PackageSetting ps = (PackageSetting) obj;
13505            if (ps.pkg != null) {
13506                return ps.pkg.applicationInfo.targetSdkVersion;
13507            }
13508        }
13509        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13510    }
13511
13512    @Override
13513    public void addPreferredActivity(IntentFilter filter, int match,
13514            ComponentName[] set, ComponentName activity, int userId) {
13515        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13516                "Adding preferred");
13517    }
13518
13519    private void addPreferredActivityInternal(IntentFilter filter, int match,
13520            ComponentName[] set, ComponentName activity, boolean always, int userId,
13521            String opname) {
13522        // writer
13523        int callingUid = Binder.getCallingUid();
13524        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13525        if (filter.countActions() == 0) {
13526            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13527            return;
13528        }
13529        synchronized (mPackages) {
13530            if (mContext.checkCallingOrSelfPermission(
13531                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13532                    != PackageManager.PERMISSION_GRANTED) {
13533                if (getUidTargetSdkVersionLockedLPr(callingUid)
13534                        < Build.VERSION_CODES.FROYO) {
13535                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13536                            + callingUid);
13537                    return;
13538                }
13539                mContext.enforceCallingOrSelfPermission(
13540                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13541            }
13542
13543            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13544            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13545                    + userId + ":");
13546            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13547            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13548            scheduleWritePackageRestrictionsLocked(userId);
13549        }
13550    }
13551
13552    @Override
13553    public void replacePreferredActivity(IntentFilter filter, int match,
13554            ComponentName[] set, ComponentName activity, int userId) {
13555        if (filter.countActions() != 1) {
13556            throw new IllegalArgumentException(
13557                    "replacePreferredActivity expects filter to have only 1 action.");
13558        }
13559        if (filter.countDataAuthorities() != 0
13560                || filter.countDataPaths() != 0
13561                || filter.countDataSchemes() > 1
13562                || filter.countDataTypes() != 0) {
13563            throw new IllegalArgumentException(
13564                    "replacePreferredActivity expects filter to have no data authorities, " +
13565                    "paths, or types; and at most one scheme.");
13566        }
13567
13568        final int callingUid = Binder.getCallingUid();
13569        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13570        synchronized (mPackages) {
13571            if (mContext.checkCallingOrSelfPermission(
13572                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13573                    != PackageManager.PERMISSION_GRANTED) {
13574                if (getUidTargetSdkVersionLockedLPr(callingUid)
13575                        < Build.VERSION_CODES.FROYO) {
13576                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13577                            + Binder.getCallingUid());
13578                    return;
13579                }
13580                mContext.enforceCallingOrSelfPermission(
13581                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13582            }
13583
13584            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13585            if (pir != null) {
13586                // Get all of the existing entries that exactly match this filter.
13587                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13588                if (existing != null && existing.size() == 1) {
13589                    PreferredActivity cur = existing.get(0);
13590                    if (DEBUG_PREFERRED) {
13591                        Slog.i(TAG, "Checking replace of preferred:");
13592                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13593                        if (!cur.mPref.mAlways) {
13594                            Slog.i(TAG, "  -- CUR; not mAlways!");
13595                        } else {
13596                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13597                            Slog.i(TAG, "  -- CUR: mSet="
13598                                    + Arrays.toString(cur.mPref.mSetComponents));
13599                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13600                            Slog.i(TAG, "  -- NEW: mMatch="
13601                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13602                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13603                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13604                        }
13605                    }
13606                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13607                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13608                            && cur.mPref.sameSet(set)) {
13609                        // Setting the preferred activity to what it happens to be already
13610                        if (DEBUG_PREFERRED) {
13611                            Slog.i(TAG, "Replacing with same preferred activity "
13612                                    + cur.mPref.mShortComponent + " for user "
13613                                    + userId + ":");
13614                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13615                        }
13616                        return;
13617                    }
13618                }
13619
13620                if (existing != null) {
13621                    if (DEBUG_PREFERRED) {
13622                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13623                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13624                    }
13625                    for (int i = 0; i < existing.size(); i++) {
13626                        PreferredActivity pa = existing.get(i);
13627                        if (DEBUG_PREFERRED) {
13628                            Slog.i(TAG, "Removing existing preferred activity "
13629                                    + pa.mPref.mComponent + ":");
13630                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13631                        }
13632                        pir.removeFilter(pa);
13633                    }
13634                }
13635            }
13636            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13637                    "Replacing preferred");
13638        }
13639    }
13640
13641    @Override
13642    public void clearPackagePreferredActivities(String packageName) {
13643        final int uid = Binder.getCallingUid();
13644        // writer
13645        synchronized (mPackages) {
13646            PackageParser.Package pkg = mPackages.get(packageName);
13647            if (pkg == null || pkg.applicationInfo.uid != uid) {
13648                if (mContext.checkCallingOrSelfPermission(
13649                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13650                        != PackageManager.PERMISSION_GRANTED) {
13651                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13652                            < Build.VERSION_CODES.FROYO) {
13653                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13654                                + Binder.getCallingUid());
13655                        return;
13656                    }
13657                    mContext.enforceCallingOrSelfPermission(
13658                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13659                }
13660            }
13661
13662            int user = UserHandle.getCallingUserId();
13663            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13664                scheduleWritePackageRestrictionsLocked(user);
13665            }
13666        }
13667    }
13668
13669    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13670    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13671        ArrayList<PreferredActivity> removed = null;
13672        boolean changed = false;
13673        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13674            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13675            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13676            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13677                continue;
13678            }
13679            Iterator<PreferredActivity> it = pir.filterIterator();
13680            while (it.hasNext()) {
13681                PreferredActivity pa = it.next();
13682                // Mark entry for removal only if it matches the package name
13683                // and the entry is of type "always".
13684                if (packageName == null ||
13685                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13686                                && pa.mPref.mAlways)) {
13687                    if (removed == null) {
13688                        removed = new ArrayList<PreferredActivity>();
13689                    }
13690                    removed.add(pa);
13691                }
13692            }
13693            if (removed != null) {
13694                for (int j=0; j<removed.size(); j++) {
13695                    PreferredActivity pa = removed.get(j);
13696                    pir.removeFilter(pa);
13697                }
13698                changed = true;
13699            }
13700        }
13701        return changed;
13702    }
13703
13704    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13705    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13706        if (userId == UserHandle.USER_ALL) {
13707            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13708                    sUserManager.getUserIds())) {
13709                for (int oneUserId : sUserManager.getUserIds()) {
13710                    scheduleWritePackageRestrictionsLocked(oneUserId);
13711                }
13712            }
13713        } else {
13714            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13715                scheduleWritePackageRestrictionsLocked(userId);
13716            }
13717        }
13718    }
13719
13720
13721    void clearDefaultBrowserIfNeeded(String packageName) {
13722        for (int oneUserId : sUserManager.getUserIds()) {
13723            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13724            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13725            if (packageName.equals(defaultBrowserPackageName)) {
13726                setDefaultBrowserPackageName(null, oneUserId);
13727            }
13728        }
13729    }
13730
13731    @Override
13732    public void resetPreferredActivities(int userId) {
13733        mContext.enforceCallingOrSelfPermission(
13734                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13735        // writer
13736        synchronized (mPackages) {
13737            clearPackagePreferredActivitiesLPw(null, userId);
13738            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13739            applyFactoryDefaultBrowserLPw(userId);
13740            primeDomainVerificationsLPw(userId);
13741
13742            scheduleWritePackageRestrictionsLocked(userId);
13743        }
13744    }
13745
13746    @Override
13747    public int getPreferredActivities(List<IntentFilter> outFilters,
13748            List<ComponentName> outActivities, String packageName) {
13749
13750        int num = 0;
13751        final int userId = UserHandle.getCallingUserId();
13752        // reader
13753        synchronized (mPackages) {
13754            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13755            if (pir != null) {
13756                final Iterator<PreferredActivity> it = pir.filterIterator();
13757                while (it.hasNext()) {
13758                    final PreferredActivity pa = it.next();
13759                    if (packageName == null
13760                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13761                                    && pa.mPref.mAlways)) {
13762                        if (outFilters != null) {
13763                            outFilters.add(new IntentFilter(pa));
13764                        }
13765                        if (outActivities != null) {
13766                            outActivities.add(pa.mPref.mComponent);
13767                        }
13768                    }
13769                }
13770            }
13771        }
13772
13773        return num;
13774    }
13775
13776    @Override
13777    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13778            int userId) {
13779        int callingUid = Binder.getCallingUid();
13780        if (callingUid != Process.SYSTEM_UID) {
13781            throw new SecurityException(
13782                    "addPersistentPreferredActivity can only be run by the system");
13783        }
13784        if (filter.countActions() == 0) {
13785            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13786            return;
13787        }
13788        synchronized (mPackages) {
13789            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13790                    " :");
13791            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13792            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13793                    new PersistentPreferredActivity(filter, activity));
13794            scheduleWritePackageRestrictionsLocked(userId);
13795        }
13796    }
13797
13798    @Override
13799    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13800        int callingUid = Binder.getCallingUid();
13801        if (callingUid != Process.SYSTEM_UID) {
13802            throw new SecurityException(
13803                    "clearPackagePersistentPreferredActivities can only be run by the system");
13804        }
13805        ArrayList<PersistentPreferredActivity> removed = null;
13806        boolean changed = false;
13807        synchronized (mPackages) {
13808            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13809                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13810                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13811                        .valueAt(i);
13812                if (userId != thisUserId) {
13813                    continue;
13814                }
13815                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13816                while (it.hasNext()) {
13817                    PersistentPreferredActivity ppa = it.next();
13818                    // Mark entry for removal only if it matches the package name.
13819                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13820                        if (removed == null) {
13821                            removed = new ArrayList<PersistentPreferredActivity>();
13822                        }
13823                        removed.add(ppa);
13824                    }
13825                }
13826                if (removed != null) {
13827                    for (int j=0; j<removed.size(); j++) {
13828                        PersistentPreferredActivity ppa = removed.get(j);
13829                        ppir.removeFilter(ppa);
13830                    }
13831                    changed = true;
13832                }
13833            }
13834
13835            if (changed) {
13836                scheduleWritePackageRestrictionsLocked(userId);
13837            }
13838        }
13839    }
13840
13841    /**
13842     * Common machinery for picking apart a restored XML blob and passing
13843     * it to a caller-supplied functor to be applied to the running system.
13844     */
13845    private void restoreFromXml(XmlPullParser parser, int userId,
13846            String expectedStartTag, BlobXmlRestorer functor)
13847            throws IOException, XmlPullParserException {
13848        int type;
13849        while ((type = parser.next()) != XmlPullParser.START_TAG
13850                && type != XmlPullParser.END_DOCUMENT) {
13851        }
13852        if (type != XmlPullParser.START_TAG) {
13853            // oops didn't find a start tag?!
13854            if (DEBUG_BACKUP) {
13855                Slog.e(TAG, "Didn't find start tag during restore");
13856            }
13857            return;
13858        }
13859
13860        // this is supposed to be TAG_PREFERRED_BACKUP
13861        if (!expectedStartTag.equals(parser.getName())) {
13862            if (DEBUG_BACKUP) {
13863                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13864            }
13865            return;
13866        }
13867
13868        // skip interfering stuff, then we're aligned with the backing implementation
13869        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13870        functor.apply(parser, userId);
13871    }
13872
13873    private interface BlobXmlRestorer {
13874        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13875    }
13876
13877    /**
13878     * Non-Binder method, support for the backup/restore mechanism: write the
13879     * full set of preferred activities in its canonical XML format.  Returns the
13880     * XML output as a byte array, or null if there is none.
13881     */
13882    @Override
13883    public byte[] getPreferredActivityBackup(int userId) {
13884        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13885            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13886        }
13887
13888        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13889        try {
13890            final XmlSerializer serializer = new FastXmlSerializer();
13891            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13892            serializer.startDocument(null, true);
13893            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13894
13895            synchronized (mPackages) {
13896                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13897            }
13898
13899            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13900            serializer.endDocument();
13901            serializer.flush();
13902        } catch (Exception e) {
13903            if (DEBUG_BACKUP) {
13904                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13905            }
13906            return null;
13907        }
13908
13909        return dataStream.toByteArray();
13910    }
13911
13912    @Override
13913    public void restorePreferredActivities(byte[] backup, int userId) {
13914        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13915            throw new SecurityException("Only the system may call restorePreferredActivities()");
13916        }
13917
13918        try {
13919            final XmlPullParser parser = Xml.newPullParser();
13920            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13921            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13922                    new BlobXmlRestorer() {
13923                        @Override
13924                        public void apply(XmlPullParser parser, int userId)
13925                                throws XmlPullParserException, IOException {
13926                            synchronized (mPackages) {
13927                                mSettings.readPreferredActivitiesLPw(parser, userId);
13928                            }
13929                        }
13930                    } );
13931        } catch (Exception e) {
13932            if (DEBUG_BACKUP) {
13933                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13934            }
13935        }
13936    }
13937
13938    /**
13939     * Non-Binder method, support for the backup/restore mechanism: write the
13940     * default browser (etc) settings in its canonical XML format.  Returns the default
13941     * browser XML representation as a byte array, or null if there is none.
13942     */
13943    @Override
13944    public byte[] getDefaultAppsBackup(int userId) {
13945        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13946            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13947        }
13948
13949        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13950        try {
13951            final XmlSerializer serializer = new FastXmlSerializer();
13952            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13953            serializer.startDocument(null, true);
13954            serializer.startTag(null, TAG_DEFAULT_APPS);
13955
13956            synchronized (mPackages) {
13957                mSettings.writeDefaultAppsLPr(serializer, userId);
13958            }
13959
13960            serializer.endTag(null, TAG_DEFAULT_APPS);
13961            serializer.endDocument();
13962            serializer.flush();
13963        } catch (Exception e) {
13964            if (DEBUG_BACKUP) {
13965                Slog.e(TAG, "Unable to write default apps for backup", e);
13966            }
13967            return null;
13968        }
13969
13970        return dataStream.toByteArray();
13971    }
13972
13973    @Override
13974    public void restoreDefaultApps(byte[] backup, int userId) {
13975        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13976            throw new SecurityException("Only the system may call restoreDefaultApps()");
13977        }
13978
13979        try {
13980            final XmlPullParser parser = Xml.newPullParser();
13981            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13982            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13983                    new BlobXmlRestorer() {
13984                        @Override
13985                        public void apply(XmlPullParser parser, int userId)
13986                                throws XmlPullParserException, IOException {
13987                            synchronized (mPackages) {
13988                                mSettings.readDefaultAppsLPw(parser, userId);
13989                            }
13990                        }
13991                    } );
13992        } catch (Exception e) {
13993            if (DEBUG_BACKUP) {
13994                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13995            }
13996        }
13997    }
13998
13999    @Override
14000    public byte[] getIntentFilterVerificationBackup(int userId) {
14001        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14002            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14003        }
14004
14005        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14006        try {
14007            final XmlSerializer serializer = new FastXmlSerializer();
14008            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14009            serializer.startDocument(null, true);
14010            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14011
14012            synchronized (mPackages) {
14013                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14014            }
14015
14016            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14017            serializer.endDocument();
14018            serializer.flush();
14019        } catch (Exception e) {
14020            if (DEBUG_BACKUP) {
14021                Slog.e(TAG, "Unable to write default apps for backup", e);
14022            }
14023            return null;
14024        }
14025
14026        return dataStream.toByteArray();
14027    }
14028
14029    @Override
14030    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14031        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14032            throw new SecurityException("Only the system may call restorePreferredActivities()");
14033        }
14034
14035        try {
14036            final XmlPullParser parser = Xml.newPullParser();
14037            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14038            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14039                    new BlobXmlRestorer() {
14040                        @Override
14041                        public void apply(XmlPullParser parser, int userId)
14042                                throws XmlPullParserException, IOException {
14043                            synchronized (mPackages) {
14044                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14045                                mSettings.writeLPr();
14046                            }
14047                        }
14048                    } );
14049        } catch (Exception e) {
14050            if (DEBUG_BACKUP) {
14051                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14052            }
14053        }
14054    }
14055
14056    @Override
14057    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14058            int sourceUserId, int targetUserId, int flags) {
14059        mContext.enforceCallingOrSelfPermission(
14060                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14061        int callingUid = Binder.getCallingUid();
14062        enforceOwnerRights(ownerPackage, callingUid);
14063        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14064        if (intentFilter.countActions() == 0) {
14065            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14066            return;
14067        }
14068        synchronized (mPackages) {
14069            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14070                    ownerPackage, targetUserId, flags);
14071            CrossProfileIntentResolver resolver =
14072                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14073            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14074            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14075            if (existing != null) {
14076                int size = existing.size();
14077                for (int i = 0; i < size; i++) {
14078                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14079                        return;
14080                    }
14081                }
14082            }
14083            resolver.addFilter(newFilter);
14084            scheduleWritePackageRestrictionsLocked(sourceUserId);
14085        }
14086    }
14087
14088    @Override
14089    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14090        mContext.enforceCallingOrSelfPermission(
14091                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14092        int callingUid = Binder.getCallingUid();
14093        enforceOwnerRights(ownerPackage, callingUid);
14094        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14095        synchronized (mPackages) {
14096            CrossProfileIntentResolver resolver =
14097                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14098            ArraySet<CrossProfileIntentFilter> set =
14099                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14100            for (CrossProfileIntentFilter filter : set) {
14101                if (filter.getOwnerPackage().equals(ownerPackage)) {
14102                    resolver.removeFilter(filter);
14103                }
14104            }
14105            scheduleWritePackageRestrictionsLocked(sourceUserId);
14106        }
14107    }
14108
14109    // Enforcing that callingUid is owning pkg on userId
14110    private void enforceOwnerRights(String pkg, int callingUid) {
14111        // The system owns everything.
14112        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14113            return;
14114        }
14115        int callingUserId = UserHandle.getUserId(callingUid);
14116        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14117        if (pi == null) {
14118            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14119                    + callingUserId);
14120        }
14121        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14122            throw new SecurityException("Calling uid " + callingUid
14123                    + " does not own package " + pkg);
14124        }
14125    }
14126
14127    @Override
14128    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14129        Intent intent = new Intent(Intent.ACTION_MAIN);
14130        intent.addCategory(Intent.CATEGORY_HOME);
14131
14132        final int callingUserId = UserHandle.getCallingUserId();
14133        List<ResolveInfo> list = queryIntentActivities(intent, null,
14134                PackageManager.GET_META_DATA, callingUserId);
14135        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14136                true, false, false, callingUserId);
14137
14138        allHomeCandidates.clear();
14139        if (list != null) {
14140            for (ResolveInfo ri : list) {
14141                allHomeCandidates.add(ri);
14142            }
14143        }
14144        return (preferred == null || preferred.activityInfo == null)
14145                ? null
14146                : new ComponentName(preferred.activityInfo.packageName,
14147                        preferred.activityInfo.name);
14148    }
14149
14150    @Override
14151    public void setApplicationEnabledSetting(String appPackageName,
14152            int newState, int flags, int userId, String callingPackage) {
14153        if (!sUserManager.exists(userId)) return;
14154        if (callingPackage == null) {
14155            callingPackage = Integer.toString(Binder.getCallingUid());
14156        }
14157        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14158    }
14159
14160    @Override
14161    public void setComponentEnabledSetting(ComponentName componentName,
14162            int newState, int flags, int userId) {
14163        if (!sUserManager.exists(userId)) return;
14164        setEnabledSetting(componentName.getPackageName(),
14165                componentName.getClassName(), newState, flags, userId, null);
14166    }
14167
14168    private void setEnabledSetting(final String packageName, String className, int newState,
14169            final int flags, int userId, String callingPackage) {
14170        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14171              || newState == COMPONENT_ENABLED_STATE_ENABLED
14172              || newState == COMPONENT_ENABLED_STATE_DISABLED
14173              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14174              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14175            throw new IllegalArgumentException("Invalid new component state: "
14176                    + newState);
14177        }
14178        PackageSetting pkgSetting;
14179        final int uid = Binder.getCallingUid();
14180        final int permission = mContext.checkCallingOrSelfPermission(
14181                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14182        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14183        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14184        boolean sendNow = false;
14185        boolean isApp = (className == null);
14186        String componentName = isApp ? packageName : className;
14187        int packageUid = -1;
14188        ArrayList<String> components;
14189
14190        // writer
14191        synchronized (mPackages) {
14192            pkgSetting = mSettings.mPackages.get(packageName);
14193            if (pkgSetting == null) {
14194                if (className == null) {
14195                    throw new IllegalArgumentException(
14196                            "Unknown package: " + packageName);
14197                }
14198                throw new IllegalArgumentException(
14199                        "Unknown component: " + packageName
14200                        + "/" + className);
14201            }
14202            // Allow root and verify that userId is not being specified by a different user
14203            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14204                throw new SecurityException(
14205                        "Permission Denial: attempt to change component state from pid="
14206                        + Binder.getCallingPid()
14207                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14208            }
14209            if (className == null) {
14210                // We're dealing with an application/package level state change
14211                if (pkgSetting.getEnabled(userId) == newState) {
14212                    // Nothing to do
14213                    return;
14214                }
14215                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14216                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14217                    // Don't care about who enables an app.
14218                    callingPackage = null;
14219                }
14220                pkgSetting.setEnabled(newState, userId, callingPackage);
14221                // pkgSetting.pkg.mSetEnabled = newState;
14222            } else {
14223                // We're dealing with a component level state change
14224                // First, verify that this is a valid class name.
14225                PackageParser.Package pkg = pkgSetting.pkg;
14226                if (pkg == null || !pkg.hasComponentClassName(className)) {
14227                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14228                        throw new IllegalArgumentException("Component class " + className
14229                                + " does not exist in " + packageName);
14230                    } else {
14231                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14232                                + className + " does not exist in " + packageName);
14233                    }
14234                }
14235                switch (newState) {
14236                case COMPONENT_ENABLED_STATE_ENABLED:
14237                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14238                        return;
14239                    }
14240                    break;
14241                case COMPONENT_ENABLED_STATE_DISABLED:
14242                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14243                        return;
14244                    }
14245                    break;
14246                case COMPONENT_ENABLED_STATE_DEFAULT:
14247                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14248                        return;
14249                    }
14250                    break;
14251                default:
14252                    Slog.e(TAG, "Invalid new component state: " + newState);
14253                    return;
14254                }
14255            }
14256            scheduleWritePackageRestrictionsLocked(userId);
14257            components = mPendingBroadcasts.get(userId, packageName);
14258            final boolean newPackage = components == null;
14259            if (newPackage) {
14260                components = new ArrayList<String>();
14261            }
14262            if (!components.contains(componentName)) {
14263                components.add(componentName);
14264            }
14265            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14266                sendNow = true;
14267                // Purge entry from pending broadcast list if another one exists already
14268                // since we are sending one right away.
14269                mPendingBroadcasts.remove(userId, packageName);
14270            } else {
14271                if (newPackage) {
14272                    mPendingBroadcasts.put(userId, packageName, components);
14273                }
14274                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14275                    // Schedule a message
14276                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14277                }
14278            }
14279        }
14280
14281        long callingId = Binder.clearCallingIdentity();
14282        try {
14283            if (sendNow) {
14284                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14285                sendPackageChangedBroadcast(packageName,
14286                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14287            }
14288        } finally {
14289            Binder.restoreCallingIdentity(callingId);
14290        }
14291    }
14292
14293    private void sendPackageChangedBroadcast(String packageName,
14294            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14295        if (DEBUG_INSTALL)
14296            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14297                    + componentNames);
14298        Bundle extras = new Bundle(4);
14299        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14300        String nameList[] = new String[componentNames.size()];
14301        componentNames.toArray(nameList);
14302        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14303        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14304        extras.putInt(Intent.EXTRA_UID, packageUid);
14305        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14306                new int[] {UserHandle.getUserId(packageUid)});
14307    }
14308
14309    @Override
14310    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14311        if (!sUserManager.exists(userId)) return;
14312        final int uid = Binder.getCallingUid();
14313        final int permission = mContext.checkCallingOrSelfPermission(
14314                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14315        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14316        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14317        // writer
14318        synchronized (mPackages) {
14319            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14320                    allowedByPermission, uid, userId)) {
14321                scheduleWritePackageRestrictionsLocked(userId);
14322            }
14323        }
14324    }
14325
14326    @Override
14327    public String getInstallerPackageName(String packageName) {
14328        // reader
14329        synchronized (mPackages) {
14330            return mSettings.getInstallerPackageNameLPr(packageName);
14331        }
14332    }
14333
14334    @Override
14335    public int getApplicationEnabledSetting(String packageName, int userId) {
14336        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14337        int uid = Binder.getCallingUid();
14338        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14339        // reader
14340        synchronized (mPackages) {
14341            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14342        }
14343    }
14344
14345    @Override
14346    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14347        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14348        int uid = Binder.getCallingUid();
14349        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14350        // reader
14351        synchronized (mPackages) {
14352            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14353        }
14354    }
14355
14356    @Override
14357    public void enterSafeMode() {
14358        enforceSystemOrRoot("Only the system can request entering safe mode");
14359
14360        if (!mSystemReady) {
14361            mSafeMode = true;
14362        }
14363    }
14364
14365    @Override
14366    public void systemReady() {
14367        mSystemReady = true;
14368
14369        // Read the compatibilty setting when the system is ready.
14370        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14371                mContext.getContentResolver(),
14372                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14373        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14374        if (DEBUG_SETTINGS) {
14375            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14376        }
14377
14378        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14379
14380        synchronized (mPackages) {
14381            // Verify that all of the preferred activity components actually
14382            // exist.  It is possible for applications to be updated and at
14383            // that point remove a previously declared activity component that
14384            // had been set as a preferred activity.  We try to clean this up
14385            // the next time we encounter that preferred activity, but it is
14386            // possible for the user flow to never be able to return to that
14387            // situation so here we do a sanity check to make sure we haven't
14388            // left any junk around.
14389            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14390            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14391                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14392                removed.clear();
14393                for (PreferredActivity pa : pir.filterSet()) {
14394                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14395                        removed.add(pa);
14396                    }
14397                }
14398                if (removed.size() > 0) {
14399                    for (int r=0; r<removed.size(); r++) {
14400                        PreferredActivity pa = removed.get(r);
14401                        Slog.w(TAG, "Removing dangling preferred activity: "
14402                                + pa.mPref.mComponent);
14403                        pir.removeFilter(pa);
14404                    }
14405                    mSettings.writePackageRestrictionsLPr(
14406                            mSettings.mPreferredActivities.keyAt(i));
14407                }
14408            }
14409
14410            for (int userId : UserManagerService.getInstance().getUserIds()) {
14411                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14412                    grantPermissionsUserIds = ArrayUtils.appendInt(
14413                            grantPermissionsUserIds, userId);
14414                }
14415            }
14416        }
14417        sUserManager.systemReady();
14418
14419        // If we upgraded grant all default permissions before kicking off.
14420        for (int userId : grantPermissionsUserIds) {
14421            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14422        }
14423
14424        // Kick off any messages waiting for system ready
14425        if (mPostSystemReadyMessages != null) {
14426            for (Message msg : mPostSystemReadyMessages) {
14427                msg.sendToTarget();
14428            }
14429            mPostSystemReadyMessages = null;
14430        }
14431
14432        // Watch for external volumes that come and go over time
14433        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14434        storage.registerListener(mStorageListener);
14435
14436        mInstallerService.systemReady();
14437        mPackageDexOptimizer.systemReady();
14438    }
14439
14440    @Override
14441    public boolean isSafeMode() {
14442        return mSafeMode;
14443    }
14444
14445    @Override
14446    public boolean hasSystemUidErrors() {
14447        return mHasSystemUidErrors;
14448    }
14449
14450    static String arrayToString(int[] array) {
14451        StringBuffer buf = new StringBuffer(128);
14452        buf.append('[');
14453        if (array != null) {
14454            for (int i=0; i<array.length; i++) {
14455                if (i > 0) buf.append(", ");
14456                buf.append(array[i]);
14457            }
14458        }
14459        buf.append(']');
14460        return buf.toString();
14461    }
14462
14463    static class DumpState {
14464        public static final int DUMP_LIBS = 1 << 0;
14465        public static final int DUMP_FEATURES = 1 << 1;
14466        public static final int DUMP_RESOLVERS = 1 << 2;
14467        public static final int DUMP_PERMISSIONS = 1 << 3;
14468        public static final int DUMP_PACKAGES = 1 << 4;
14469        public static final int DUMP_SHARED_USERS = 1 << 5;
14470        public static final int DUMP_MESSAGES = 1 << 6;
14471        public static final int DUMP_PROVIDERS = 1 << 7;
14472        public static final int DUMP_VERIFIERS = 1 << 8;
14473        public static final int DUMP_PREFERRED = 1 << 9;
14474        public static final int DUMP_PREFERRED_XML = 1 << 10;
14475        public static final int DUMP_KEYSETS = 1 << 11;
14476        public static final int DUMP_VERSION = 1 << 12;
14477        public static final int DUMP_INSTALLS = 1 << 13;
14478        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14479        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14480
14481        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14482
14483        private int mTypes;
14484
14485        private int mOptions;
14486
14487        private boolean mTitlePrinted;
14488
14489        private SharedUserSetting mSharedUser;
14490
14491        public boolean isDumping(int type) {
14492            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14493                return true;
14494            }
14495
14496            return (mTypes & type) != 0;
14497        }
14498
14499        public void setDump(int type) {
14500            mTypes |= type;
14501        }
14502
14503        public boolean isOptionEnabled(int option) {
14504            return (mOptions & option) != 0;
14505        }
14506
14507        public void setOptionEnabled(int option) {
14508            mOptions |= option;
14509        }
14510
14511        public boolean onTitlePrinted() {
14512            final boolean printed = mTitlePrinted;
14513            mTitlePrinted = true;
14514            return printed;
14515        }
14516
14517        public boolean getTitlePrinted() {
14518            return mTitlePrinted;
14519        }
14520
14521        public void setTitlePrinted(boolean enabled) {
14522            mTitlePrinted = enabled;
14523        }
14524
14525        public SharedUserSetting getSharedUser() {
14526            return mSharedUser;
14527        }
14528
14529        public void setSharedUser(SharedUserSetting user) {
14530            mSharedUser = user;
14531        }
14532    }
14533
14534    @Override
14535    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14536        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14537                != PackageManager.PERMISSION_GRANTED) {
14538            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14539                    + Binder.getCallingPid()
14540                    + ", uid=" + Binder.getCallingUid()
14541                    + " without permission "
14542                    + android.Manifest.permission.DUMP);
14543            return;
14544        }
14545
14546        DumpState dumpState = new DumpState();
14547        boolean fullPreferred = false;
14548        boolean checkin = false;
14549
14550        String packageName = null;
14551        ArraySet<String> permissionNames = null;
14552
14553        int opti = 0;
14554        while (opti < args.length) {
14555            String opt = args[opti];
14556            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14557                break;
14558            }
14559            opti++;
14560
14561            if ("-a".equals(opt)) {
14562                // Right now we only know how to print all.
14563            } else if ("-h".equals(opt)) {
14564                pw.println("Package manager dump options:");
14565                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14566                pw.println("    --checkin: dump for a checkin");
14567                pw.println("    -f: print details of intent filters");
14568                pw.println("    -h: print this help");
14569                pw.println("  cmd may be one of:");
14570                pw.println("    l[ibraries]: list known shared libraries");
14571                pw.println("    f[ibraries]: list device features");
14572                pw.println("    k[eysets]: print known keysets");
14573                pw.println("    r[esolvers]: dump intent resolvers");
14574                pw.println("    perm[issions]: dump permissions");
14575                pw.println("    permission [name ...]: dump declaration and use of given permission");
14576                pw.println("    pref[erred]: print preferred package settings");
14577                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14578                pw.println("    prov[iders]: dump content providers");
14579                pw.println("    p[ackages]: dump installed packages");
14580                pw.println("    s[hared-users]: dump shared user IDs");
14581                pw.println("    m[essages]: print collected runtime messages");
14582                pw.println("    v[erifiers]: print package verifier info");
14583                pw.println("    version: print database version info");
14584                pw.println("    write: write current settings now");
14585                pw.println("    <package.name>: info about given package");
14586                pw.println("    installs: details about install sessions");
14587                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14588                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14589                return;
14590            } else if ("--checkin".equals(opt)) {
14591                checkin = true;
14592            } else if ("-f".equals(opt)) {
14593                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14594            } else {
14595                pw.println("Unknown argument: " + opt + "; use -h for help");
14596            }
14597        }
14598
14599        // Is the caller requesting to dump a particular piece of data?
14600        if (opti < args.length) {
14601            String cmd = args[opti];
14602            opti++;
14603            // Is this a package name?
14604            if ("android".equals(cmd) || cmd.contains(".")) {
14605                packageName = cmd;
14606                // When dumping a single package, we always dump all of its
14607                // filter information since the amount of data will be reasonable.
14608                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14609            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14610                dumpState.setDump(DumpState.DUMP_LIBS);
14611            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14612                dumpState.setDump(DumpState.DUMP_FEATURES);
14613            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14614                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14615            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14616                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14617            } else if ("permission".equals(cmd)) {
14618                if (opti >= args.length) {
14619                    pw.println("Error: permission requires permission name");
14620                    return;
14621                }
14622                permissionNames = new ArraySet<>();
14623                while (opti < args.length) {
14624                    permissionNames.add(args[opti]);
14625                    opti++;
14626                }
14627                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14628                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14629            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14630                dumpState.setDump(DumpState.DUMP_PREFERRED);
14631            } else if ("preferred-xml".equals(cmd)) {
14632                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14633                if (opti < args.length && "--full".equals(args[opti])) {
14634                    fullPreferred = true;
14635                    opti++;
14636                }
14637            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14638                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14639            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14640                dumpState.setDump(DumpState.DUMP_PACKAGES);
14641            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14642                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14643            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14644                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14645            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14646                dumpState.setDump(DumpState.DUMP_MESSAGES);
14647            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14648                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14649            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14650                    || "intent-filter-verifiers".equals(cmd)) {
14651                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14652            } else if ("version".equals(cmd)) {
14653                dumpState.setDump(DumpState.DUMP_VERSION);
14654            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14655                dumpState.setDump(DumpState.DUMP_KEYSETS);
14656            } else if ("installs".equals(cmd)) {
14657                dumpState.setDump(DumpState.DUMP_INSTALLS);
14658            } else if ("write".equals(cmd)) {
14659                synchronized (mPackages) {
14660                    mSettings.writeLPr();
14661                    pw.println("Settings written.");
14662                    return;
14663                }
14664            }
14665        }
14666
14667        if (checkin) {
14668            pw.println("vers,1");
14669        }
14670
14671        // reader
14672        synchronized (mPackages) {
14673            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14674                if (!checkin) {
14675                    if (dumpState.onTitlePrinted())
14676                        pw.println();
14677                    pw.println("Database versions:");
14678                    pw.print("  SDK Version:");
14679                    pw.print(" internal=");
14680                    pw.print(mSettings.mInternalSdkPlatform);
14681                    pw.print(" external=");
14682                    pw.println(mSettings.mExternalSdkPlatform);
14683                    pw.print("  DB Version:");
14684                    pw.print(" internal=");
14685                    pw.print(mSettings.mInternalDatabaseVersion);
14686                    pw.print(" external=");
14687                    pw.println(mSettings.mExternalDatabaseVersion);
14688                }
14689            }
14690
14691            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14692                if (!checkin) {
14693                    if (dumpState.onTitlePrinted())
14694                        pw.println();
14695                    pw.println("Verifiers:");
14696                    pw.print("  Required: ");
14697                    pw.print(mRequiredVerifierPackage);
14698                    pw.print(" (uid=");
14699                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14700                    pw.println(")");
14701                } else if (mRequiredVerifierPackage != null) {
14702                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14703                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14704                }
14705            }
14706
14707            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14708                    packageName == null) {
14709                if (mIntentFilterVerifierComponent != null) {
14710                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14711                    if (!checkin) {
14712                        if (dumpState.onTitlePrinted())
14713                            pw.println();
14714                        pw.println("Intent Filter Verifier:");
14715                        pw.print("  Using: ");
14716                        pw.print(verifierPackageName);
14717                        pw.print(" (uid=");
14718                        pw.print(getPackageUid(verifierPackageName, 0));
14719                        pw.println(")");
14720                    } else if (verifierPackageName != null) {
14721                        pw.print("ifv,"); pw.print(verifierPackageName);
14722                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14723                    }
14724                } else {
14725                    pw.println();
14726                    pw.println("No Intent Filter Verifier available!");
14727                }
14728            }
14729
14730            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14731                boolean printedHeader = false;
14732                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14733                while (it.hasNext()) {
14734                    String name = it.next();
14735                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14736                    if (!checkin) {
14737                        if (!printedHeader) {
14738                            if (dumpState.onTitlePrinted())
14739                                pw.println();
14740                            pw.println("Libraries:");
14741                            printedHeader = true;
14742                        }
14743                        pw.print("  ");
14744                    } else {
14745                        pw.print("lib,");
14746                    }
14747                    pw.print(name);
14748                    if (!checkin) {
14749                        pw.print(" -> ");
14750                    }
14751                    if (ent.path != null) {
14752                        if (!checkin) {
14753                            pw.print("(jar) ");
14754                            pw.print(ent.path);
14755                        } else {
14756                            pw.print(",jar,");
14757                            pw.print(ent.path);
14758                        }
14759                    } else {
14760                        if (!checkin) {
14761                            pw.print("(apk) ");
14762                            pw.print(ent.apk);
14763                        } else {
14764                            pw.print(",apk,");
14765                            pw.print(ent.apk);
14766                        }
14767                    }
14768                    pw.println();
14769                }
14770            }
14771
14772            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14773                if (dumpState.onTitlePrinted())
14774                    pw.println();
14775                if (!checkin) {
14776                    pw.println("Features:");
14777                }
14778                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14779                while (it.hasNext()) {
14780                    String name = it.next();
14781                    if (!checkin) {
14782                        pw.print("  ");
14783                    } else {
14784                        pw.print("feat,");
14785                    }
14786                    pw.println(name);
14787                }
14788            }
14789
14790            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14791                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14792                        : "Activity Resolver Table:", "  ", packageName,
14793                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14794                    dumpState.setTitlePrinted(true);
14795                }
14796                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14797                        : "Receiver Resolver Table:", "  ", packageName,
14798                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14799                    dumpState.setTitlePrinted(true);
14800                }
14801                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14802                        : "Service Resolver Table:", "  ", packageName,
14803                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14804                    dumpState.setTitlePrinted(true);
14805                }
14806                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14807                        : "Provider Resolver Table:", "  ", packageName,
14808                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14809                    dumpState.setTitlePrinted(true);
14810                }
14811            }
14812
14813            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14814                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14815                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14816                    int user = mSettings.mPreferredActivities.keyAt(i);
14817                    if (pir.dump(pw,
14818                            dumpState.getTitlePrinted()
14819                                ? "\nPreferred Activities User " + user + ":"
14820                                : "Preferred Activities User " + user + ":", "  ",
14821                            packageName, true, false)) {
14822                        dumpState.setTitlePrinted(true);
14823                    }
14824                }
14825            }
14826
14827            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14828                pw.flush();
14829                FileOutputStream fout = new FileOutputStream(fd);
14830                BufferedOutputStream str = new BufferedOutputStream(fout);
14831                XmlSerializer serializer = new FastXmlSerializer();
14832                try {
14833                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14834                    serializer.startDocument(null, true);
14835                    serializer.setFeature(
14836                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14837                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14838                    serializer.endDocument();
14839                    serializer.flush();
14840                } catch (IllegalArgumentException e) {
14841                    pw.println("Failed writing: " + e);
14842                } catch (IllegalStateException e) {
14843                    pw.println("Failed writing: " + e);
14844                } catch (IOException e) {
14845                    pw.println("Failed writing: " + e);
14846                }
14847            }
14848
14849            if (!checkin
14850                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14851                    && packageName == null) {
14852                pw.println();
14853                int count = mSettings.mPackages.size();
14854                if (count == 0) {
14855                    pw.println("No applications!");
14856                    pw.println();
14857                } else {
14858                    final String prefix = "  ";
14859                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14860                    if (allPackageSettings.size() == 0) {
14861                        pw.println("No domain preferred apps!");
14862                        pw.println();
14863                    } else {
14864                        pw.println("App verification status:");
14865                        pw.println();
14866                        count = 0;
14867                        for (PackageSetting ps : allPackageSettings) {
14868                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14869                            if (ivi == null || ivi.getPackageName() == null) continue;
14870                            pw.println(prefix + "Package: " + ivi.getPackageName());
14871                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14872                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14873                            pw.println();
14874                            count++;
14875                        }
14876                        if (count == 0) {
14877                            pw.println(prefix + "No app verification established.");
14878                            pw.println();
14879                        }
14880                        for (int userId : sUserManager.getUserIds()) {
14881                            pw.println("App linkages for user " + userId + ":");
14882                            pw.println();
14883                            count = 0;
14884                            for (PackageSetting ps : allPackageSettings) {
14885                                final int status = ps.getDomainVerificationStatusForUser(userId);
14886                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14887                                    continue;
14888                                }
14889                                pw.println(prefix + "Package: " + ps.name);
14890                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14891                                String statusStr = IntentFilterVerificationInfo.
14892                                        getStatusStringFromValue(status);
14893                                pw.println(prefix + "Status:  " + statusStr);
14894                                pw.println();
14895                                count++;
14896                            }
14897                            if (count == 0) {
14898                                pw.println(prefix + "No configured app linkages.");
14899                                pw.println();
14900                            }
14901                        }
14902                    }
14903                }
14904            }
14905
14906            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14907                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14908                if (packageName == null && permissionNames == null) {
14909                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14910                        if (iperm == 0) {
14911                            if (dumpState.onTitlePrinted())
14912                                pw.println();
14913                            pw.println("AppOp Permissions:");
14914                        }
14915                        pw.print("  AppOp Permission ");
14916                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14917                        pw.println(":");
14918                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14919                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14920                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14921                        }
14922                    }
14923                }
14924            }
14925
14926            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14927                boolean printedSomething = false;
14928                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14929                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14930                        continue;
14931                    }
14932                    if (!printedSomething) {
14933                        if (dumpState.onTitlePrinted())
14934                            pw.println();
14935                        pw.println("Registered ContentProviders:");
14936                        printedSomething = true;
14937                    }
14938                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14939                    pw.print("    "); pw.println(p.toString());
14940                }
14941                printedSomething = false;
14942                for (Map.Entry<String, PackageParser.Provider> entry :
14943                        mProvidersByAuthority.entrySet()) {
14944                    PackageParser.Provider p = entry.getValue();
14945                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14946                        continue;
14947                    }
14948                    if (!printedSomething) {
14949                        if (dumpState.onTitlePrinted())
14950                            pw.println();
14951                        pw.println("ContentProvider Authorities:");
14952                        printedSomething = true;
14953                    }
14954                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14955                    pw.print("    "); pw.println(p.toString());
14956                    if (p.info != null && p.info.applicationInfo != null) {
14957                        final String appInfo = p.info.applicationInfo.toString();
14958                        pw.print("      applicationInfo="); pw.println(appInfo);
14959                    }
14960                }
14961            }
14962
14963            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14964                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14965            }
14966
14967            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14968                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14969            }
14970
14971            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14972                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14973            }
14974
14975            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14976                // XXX should handle packageName != null by dumping only install data that
14977                // the given package is involved with.
14978                if (dumpState.onTitlePrinted()) pw.println();
14979                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14980            }
14981
14982            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14983                if (dumpState.onTitlePrinted()) pw.println();
14984                mSettings.dumpReadMessagesLPr(pw, dumpState);
14985
14986                pw.println();
14987                pw.println("Package warning messages:");
14988                BufferedReader in = null;
14989                String line = null;
14990                try {
14991                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14992                    while ((line = in.readLine()) != null) {
14993                        if (line.contains("ignored: updated version")) continue;
14994                        pw.println(line);
14995                    }
14996                } catch (IOException ignored) {
14997                } finally {
14998                    IoUtils.closeQuietly(in);
14999                }
15000            }
15001
15002            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15003                BufferedReader in = null;
15004                String line = null;
15005                try {
15006                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15007                    while ((line = in.readLine()) != null) {
15008                        if (line.contains("ignored: updated version")) continue;
15009                        pw.print("msg,");
15010                        pw.println(line);
15011                    }
15012                } catch (IOException ignored) {
15013                } finally {
15014                    IoUtils.closeQuietly(in);
15015                }
15016            }
15017        }
15018    }
15019
15020    private String dumpDomainString(String packageName) {
15021        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15022        List<IntentFilter> filters = getAllIntentFilters(packageName);
15023
15024        ArraySet<String> result = new ArraySet<>();
15025        if (iviList.size() > 0) {
15026            for (IntentFilterVerificationInfo ivi : iviList) {
15027                for (String host : ivi.getDomains()) {
15028                    result.add(host);
15029                }
15030            }
15031        }
15032        if (filters != null && filters.size() > 0) {
15033            for (IntentFilter filter : filters) {
15034                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15035                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15036                    result.addAll(filter.getHostsList());
15037                }
15038            }
15039        }
15040
15041        StringBuilder sb = new StringBuilder(result.size() * 16);
15042        for (String domain : result) {
15043            if (sb.length() > 0) sb.append(" ");
15044            sb.append(domain);
15045        }
15046        return sb.toString();
15047    }
15048
15049    // ------- apps on sdcard specific code -------
15050    static final boolean DEBUG_SD_INSTALL = false;
15051
15052    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15053
15054    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15055
15056    private boolean mMediaMounted = false;
15057
15058    static String getEncryptKey() {
15059        try {
15060            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15061                    SD_ENCRYPTION_KEYSTORE_NAME);
15062            if (sdEncKey == null) {
15063                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15064                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15065                if (sdEncKey == null) {
15066                    Slog.e(TAG, "Failed to create encryption keys");
15067                    return null;
15068                }
15069            }
15070            return sdEncKey;
15071        } catch (NoSuchAlgorithmException nsae) {
15072            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15073            return null;
15074        } catch (IOException ioe) {
15075            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15076            return null;
15077        }
15078    }
15079
15080    /*
15081     * Update media status on PackageManager.
15082     */
15083    @Override
15084    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15085        int callingUid = Binder.getCallingUid();
15086        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15087            throw new SecurityException("Media status can only be updated by the system");
15088        }
15089        // reader; this apparently protects mMediaMounted, but should probably
15090        // be a different lock in that case.
15091        synchronized (mPackages) {
15092            Log.i(TAG, "Updating external media status from "
15093                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15094                    + (mediaStatus ? "mounted" : "unmounted"));
15095            if (DEBUG_SD_INSTALL)
15096                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15097                        + ", mMediaMounted=" + mMediaMounted);
15098            if (mediaStatus == mMediaMounted) {
15099                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15100                        : 0, -1);
15101                mHandler.sendMessage(msg);
15102                return;
15103            }
15104            mMediaMounted = mediaStatus;
15105        }
15106        // Queue up an async operation since the package installation may take a
15107        // little while.
15108        mHandler.post(new Runnable() {
15109            public void run() {
15110                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15111            }
15112        });
15113    }
15114
15115    /**
15116     * Called by MountService when the initial ASECs to scan are available.
15117     * Should block until all the ASEC containers are finished being scanned.
15118     */
15119    public void scanAvailableAsecs() {
15120        updateExternalMediaStatusInner(true, false, false);
15121        if (mShouldRestoreconData) {
15122            SELinuxMMAC.setRestoreconDone();
15123            mShouldRestoreconData = false;
15124        }
15125    }
15126
15127    /*
15128     * Collect information of applications on external media, map them against
15129     * existing containers and update information based on current mount status.
15130     * Please note that we always have to report status if reportStatus has been
15131     * set to true especially when unloading packages.
15132     */
15133    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15134            boolean externalStorage) {
15135        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15136        int[] uidArr = EmptyArray.INT;
15137
15138        final String[] list = PackageHelper.getSecureContainerList();
15139        if (ArrayUtils.isEmpty(list)) {
15140            Log.i(TAG, "No secure containers found");
15141        } else {
15142            // Process list of secure containers and categorize them
15143            // as active or stale based on their package internal state.
15144
15145            // reader
15146            synchronized (mPackages) {
15147                for (String cid : list) {
15148                    // Leave stages untouched for now; installer service owns them
15149                    if (PackageInstallerService.isStageName(cid)) continue;
15150
15151                    if (DEBUG_SD_INSTALL)
15152                        Log.i(TAG, "Processing container " + cid);
15153                    String pkgName = getAsecPackageName(cid);
15154                    if (pkgName == null) {
15155                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15156                        continue;
15157                    }
15158                    if (DEBUG_SD_INSTALL)
15159                        Log.i(TAG, "Looking for pkg : " + pkgName);
15160
15161                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15162                    if (ps == null) {
15163                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15164                        continue;
15165                    }
15166
15167                    /*
15168                     * Skip packages that are not external if we're unmounting
15169                     * external storage.
15170                     */
15171                    if (externalStorage && !isMounted && !isExternal(ps)) {
15172                        continue;
15173                    }
15174
15175                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15176                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15177                    // The package status is changed only if the code path
15178                    // matches between settings and the container id.
15179                    if (ps.codePathString != null
15180                            && ps.codePathString.startsWith(args.getCodePath())) {
15181                        if (DEBUG_SD_INSTALL) {
15182                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15183                                    + " at code path: " + ps.codePathString);
15184                        }
15185
15186                        // We do have a valid package installed on sdcard
15187                        processCids.put(args, ps.codePathString);
15188                        final int uid = ps.appId;
15189                        if (uid != -1) {
15190                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15191                        }
15192                    } else {
15193                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15194                                + ps.codePathString);
15195                    }
15196                }
15197            }
15198
15199            Arrays.sort(uidArr);
15200        }
15201
15202        // Process packages with valid entries.
15203        if (isMounted) {
15204            if (DEBUG_SD_INSTALL)
15205                Log.i(TAG, "Loading packages");
15206            loadMediaPackages(processCids, uidArr);
15207            startCleaningPackages();
15208            mInstallerService.onSecureContainersAvailable();
15209        } else {
15210            if (DEBUG_SD_INSTALL)
15211                Log.i(TAG, "Unloading packages");
15212            unloadMediaPackages(processCids, uidArr, reportStatus);
15213        }
15214    }
15215
15216    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15217            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15218        final int size = infos.size();
15219        final String[] packageNames = new String[size];
15220        final int[] packageUids = new int[size];
15221        for (int i = 0; i < size; i++) {
15222            final ApplicationInfo info = infos.get(i);
15223            packageNames[i] = info.packageName;
15224            packageUids[i] = info.uid;
15225        }
15226        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15227                finishedReceiver);
15228    }
15229
15230    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15231            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15232        sendResourcesChangedBroadcast(mediaStatus, replacing,
15233                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15234    }
15235
15236    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15237            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15238        int size = pkgList.length;
15239        if (size > 0) {
15240            // Send broadcasts here
15241            Bundle extras = new Bundle();
15242            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15243            if (uidArr != null) {
15244                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15245            }
15246            if (replacing) {
15247                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15248            }
15249            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15250                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15251            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15252        }
15253    }
15254
15255   /*
15256     * Look at potentially valid container ids from processCids If package
15257     * information doesn't match the one on record or package scanning fails,
15258     * the cid is added to list of removeCids. We currently don't delete stale
15259     * containers.
15260     */
15261    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15262        ArrayList<String> pkgList = new ArrayList<String>();
15263        Set<AsecInstallArgs> keys = processCids.keySet();
15264
15265        for (AsecInstallArgs args : keys) {
15266            String codePath = processCids.get(args);
15267            if (DEBUG_SD_INSTALL)
15268                Log.i(TAG, "Loading container : " + args.cid);
15269            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15270            try {
15271                // Make sure there are no container errors first.
15272                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15273                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15274                            + " when installing from sdcard");
15275                    continue;
15276                }
15277                // Check code path here.
15278                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15279                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15280                            + " does not match one in settings " + codePath);
15281                    continue;
15282                }
15283                // Parse package
15284                int parseFlags = mDefParseFlags;
15285                if (args.isExternalAsec()) {
15286                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15287                }
15288                if (args.isFwdLocked()) {
15289                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15290                }
15291
15292                synchronized (mInstallLock) {
15293                    PackageParser.Package pkg = null;
15294                    try {
15295                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15296                    } catch (PackageManagerException e) {
15297                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15298                    }
15299                    // Scan the package
15300                    if (pkg != null) {
15301                        /*
15302                         * TODO why is the lock being held? doPostInstall is
15303                         * called in other places without the lock. This needs
15304                         * to be straightened out.
15305                         */
15306                        // writer
15307                        synchronized (mPackages) {
15308                            retCode = PackageManager.INSTALL_SUCCEEDED;
15309                            pkgList.add(pkg.packageName);
15310                            // Post process args
15311                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15312                                    pkg.applicationInfo.uid);
15313                        }
15314                    } else {
15315                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15316                    }
15317                }
15318
15319            } finally {
15320                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15321                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15322                }
15323            }
15324        }
15325        // writer
15326        synchronized (mPackages) {
15327            // If the platform SDK has changed since the last time we booted,
15328            // we need to re-grant app permission to catch any new ones that
15329            // appear. This is really a hack, and means that apps can in some
15330            // cases get permissions that the user didn't initially explicitly
15331            // allow... it would be nice to have some better way to handle
15332            // this situation.
15333            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15334            if (regrantPermissions)
15335                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15336                        + mSdkVersion + "; regranting permissions for external storage");
15337            mSettings.mExternalSdkPlatform = mSdkVersion;
15338
15339            // Make sure group IDs have been assigned, and any permission
15340            // changes in other apps are accounted for
15341            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15342                    | (regrantPermissions
15343                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15344                            : 0));
15345
15346            mSettings.updateExternalDatabaseVersion();
15347
15348            // can downgrade to reader
15349            // Persist settings
15350            mSettings.writeLPr();
15351        }
15352        // Send a broadcast to let everyone know we are done processing
15353        if (pkgList.size() > 0) {
15354            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15355        }
15356    }
15357
15358   /*
15359     * Utility method to unload a list of specified containers
15360     */
15361    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15362        // Just unmount all valid containers.
15363        for (AsecInstallArgs arg : cidArgs) {
15364            synchronized (mInstallLock) {
15365                arg.doPostDeleteLI(false);
15366           }
15367       }
15368   }
15369
15370    /*
15371     * Unload packages mounted on external media. This involves deleting package
15372     * data from internal structures, sending broadcasts about diabled packages,
15373     * gc'ing to free up references, unmounting all secure containers
15374     * corresponding to packages on external media, and posting a
15375     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15376     * that we always have to post this message if status has been requested no
15377     * matter what.
15378     */
15379    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15380            final boolean reportStatus) {
15381        if (DEBUG_SD_INSTALL)
15382            Log.i(TAG, "unloading media packages");
15383        ArrayList<String> pkgList = new ArrayList<String>();
15384        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15385        final Set<AsecInstallArgs> keys = processCids.keySet();
15386        for (AsecInstallArgs args : keys) {
15387            String pkgName = args.getPackageName();
15388            if (DEBUG_SD_INSTALL)
15389                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15390            // Delete package internally
15391            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15392            synchronized (mInstallLock) {
15393                boolean res = deletePackageLI(pkgName, null, false, null, null,
15394                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15395                if (res) {
15396                    pkgList.add(pkgName);
15397                } else {
15398                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15399                    failedList.add(args);
15400                }
15401            }
15402        }
15403
15404        // reader
15405        synchronized (mPackages) {
15406            // We didn't update the settings after removing each package;
15407            // write them now for all packages.
15408            mSettings.writeLPr();
15409        }
15410
15411        // We have to absolutely send UPDATED_MEDIA_STATUS only
15412        // after confirming that all the receivers processed the ordered
15413        // broadcast when packages get disabled, force a gc to clean things up.
15414        // and unload all the containers.
15415        if (pkgList.size() > 0) {
15416            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15417                    new IIntentReceiver.Stub() {
15418                public void performReceive(Intent intent, int resultCode, String data,
15419                        Bundle extras, boolean ordered, boolean sticky,
15420                        int sendingUser) throws RemoteException {
15421                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15422                            reportStatus ? 1 : 0, 1, keys);
15423                    mHandler.sendMessage(msg);
15424                }
15425            });
15426        } else {
15427            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15428                    keys);
15429            mHandler.sendMessage(msg);
15430        }
15431    }
15432
15433    private void loadPrivatePackages(VolumeInfo vol) {
15434        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15435        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15436        synchronized (mInstallLock) {
15437        synchronized (mPackages) {
15438            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15439            for (PackageSetting ps : packages) {
15440                final PackageParser.Package pkg;
15441                try {
15442                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15443                    loaded.add(pkg.applicationInfo);
15444                } catch (PackageManagerException e) {
15445                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15446                }
15447            }
15448
15449            // TODO: regrant any permissions that changed based since original install
15450
15451            mSettings.writeLPr();
15452        }
15453        }
15454
15455        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15456        sendResourcesChangedBroadcast(true, false, loaded, null);
15457    }
15458
15459    private void unloadPrivatePackages(VolumeInfo vol) {
15460        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15461        synchronized (mInstallLock) {
15462        synchronized (mPackages) {
15463            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15464            for (PackageSetting ps : packages) {
15465                if (ps.pkg == null) continue;
15466
15467                final ApplicationInfo info = ps.pkg.applicationInfo;
15468                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15469                if (deletePackageLI(ps.name, null, false, null, null,
15470                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15471                    unloaded.add(info);
15472                } else {
15473                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15474                }
15475            }
15476
15477            mSettings.writeLPr();
15478        }
15479        }
15480
15481        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15482        sendResourcesChangedBroadcast(false, false, unloaded, null);
15483    }
15484
15485    /**
15486     * Examine all users present on given mounted volume, and destroy data
15487     * belonging to users that are no longer valid, or whose user ID has been
15488     * recycled.
15489     */
15490    private void reconcileUsers(String volumeUuid) {
15491        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15492        if (ArrayUtils.isEmpty(files)) {
15493            Slog.d(TAG, "No users found on " + volumeUuid);
15494            return;
15495        }
15496
15497        for (File file : files) {
15498            if (!file.isDirectory()) continue;
15499
15500            final int userId;
15501            final UserInfo info;
15502            try {
15503                userId = Integer.parseInt(file.getName());
15504                info = sUserManager.getUserInfo(userId);
15505            } catch (NumberFormatException e) {
15506                Slog.w(TAG, "Invalid user directory " + file);
15507                continue;
15508            }
15509
15510            boolean destroyUser = false;
15511            if (info == null) {
15512                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15513                        + " because no matching user was found");
15514                destroyUser = true;
15515            } else {
15516                try {
15517                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15518                } catch (IOException e) {
15519                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15520                            + " because we failed to enforce serial number: " + e);
15521                    destroyUser = true;
15522                }
15523            }
15524
15525            if (destroyUser) {
15526                synchronized (mInstallLock) {
15527                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15528                }
15529            }
15530        }
15531
15532        final UserManager um = mContext.getSystemService(UserManager.class);
15533        for (UserInfo user : um.getUsers()) {
15534            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15535            if (userDir.exists()) continue;
15536
15537            try {
15538                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15539                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15540            } catch (IOException e) {
15541                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15542            }
15543        }
15544    }
15545
15546    /**
15547     * Examine all apps present on given mounted volume, and destroy apps that
15548     * aren't expected, either due to uninstallation or reinstallation on
15549     * another volume.
15550     */
15551    private void reconcileApps(String volumeUuid) {
15552        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15553        if (ArrayUtils.isEmpty(files)) {
15554            Slog.d(TAG, "No apps found on " + volumeUuid);
15555            return;
15556        }
15557
15558        for (File file : files) {
15559            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15560                    && !PackageInstallerService.isStageName(file.getName());
15561            if (!isPackage) {
15562                // Ignore entries which are not packages
15563                continue;
15564            }
15565
15566            boolean destroyApp = false;
15567            String packageName = null;
15568            try {
15569                final PackageLite pkg = PackageParser.parsePackageLite(file,
15570                        PackageParser.PARSE_MUST_BE_APK);
15571                packageName = pkg.packageName;
15572
15573                synchronized (mPackages) {
15574                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15575                    if (ps == null) {
15576                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15577                                + volumeUuid + " because we found no install record");
15578                        destroyApp = true;
15579                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15580                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15581                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15582                        destroyApp = true;
15583                    }
15584                }
15585
15586            } catch (PackageParserException e) {
15587                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15588                destroyApp = true;
15589            }
15590
15591            if (destroyApp) {
15592                synchronized (mInstallLock) {
15593                    if (packageName != null) {
15594                        removeDataDirsLI(volumeUuid, packageName);
15595                    }
15596                    if (file.isDirectory()) {
15597                        mInstaller.rmPackageDir(file.getAbsolutePath());
15598                    } else {
15599                        file.delete();
15600                    }
15601                }
15602            }
15603        }
15604    }
15605
15606    private void unfreezePackage(String packageName) {
15607        synchronized (mPackages) {
15608            final PackageSetting ps = mSettings.mPackages.get(packageName);
15609            if (ps != null) {
15610                ps.frozen = false;
15611            }
15612        }
15613    }
15614
15615    @Override
15616    public int movePackage(final String packageName, final String volumeUuid) {
15617        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15618
15619        final int moveId = mNextMoveId.getAndIncrement();
15620        try {
15621            movePackageInternal(packageName, volumeUuid, moveId);
15622        } catch (PackageManagerException e) {
15623            Slog.w(TAG, "Failed to move " + packageName, e);
15624            mMoveCallbacks.notifyStatusChanged(moveId,
15625                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15626        }
15627        return moveId;
15628    }
15629
15630    private void movePackageInternal(final String packageName, final String volumeUuid,
15631            final int moveId) throws PackageManagerException {
15632        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15633        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15634        final PackageManager pm = mContext.getPackageManager();
15635
15636        final boolean currentAsec;
15637        final String currentVolumeUuid;
15638        final File codeFile;
15639        final String installerPackageName;
15640        final String packageAbiOverride;
15641        final int appId;
15642        final String seinfo;
15643        final String label;
15644
15645        // reader
15646        synchronized (mPackages) {
15647            final PackageParser.Package pkg = mPackages.get(packageName);
15648            final PackageSetting ps = mSettings.mPackages.get(packageName);
15649            if (pkg == null || ps == null) {
15650                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15651            }
15652
15653            if (pkg.applicationInfo.isSystemApp()) {
15654                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15655                        "Cannot move system application");
15656            }
15657
15658            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15659                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15660                        "Package already moved to " + volumeUuid);
15661            }
15662
15663            final File probe = new File(pkg.codePath);
15664            final File probeOat = new File(probe, "oat");
15665            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15666                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15667                        "Move only supported for modern cluster style installs");
15668            }
15669
15670            if (ps.frozen) {
15671                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15672                        "Failed to move already frozen package");
15673            }
15674            ps.frozen = true;
15675
15676            currentAsec = pkg.applicationInfo.isForwardLocked()
15677                    || pkg.applicationInfo.isExternalAsec();
15678            currentVolumeUuid = ps.volumeUuid;
15679            codeFile = new File(pkg.codePath);
15680            installerPackageName = ps.installerPackageName;
15681            packageAbiOverride = ps.cpuAbiOverrideString;
15682            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15683            seinfo = pkg.applicationInfo.seinfo;
15684            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15685        }
15686
15687        // Now that we're guarded by frozen state, kill app during move
15688        killApplication(packageName, appId, "move pkg");
15689
15690        final Bundle extras = new Bundle();
15691        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15692        extras.putString(Intent.EXTRA_TITLE, label);
15693        mMoveCallbacks.notifyCreated(moveId, extras);
15694
15695        int installFlags;
15696        final boolean moveCompleteApp;
15697        final File measurePath;
15698
15699        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15700            installFlags = INSTALL_INTERNAL;
15701            moveCompleteApp = !currentAsec;
15702            measurePath = Environment.getDataAppDirectory(volumeUuid);
15703        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15704            installFlags = INSTALL_EXTERNAL;
15705            moveCompleteApp = false;
15706            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15707        } else {
15708            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15709            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15710                    || !volume.isMountedWritable()) {
15711                unfreezePackage(packageName);
15712                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15713                        "Move location not mounted private volume");
15714            }
15715
15716            Preconditions.checkState(!currentAsec);
15717
15718            installFlags = INSTALL_INTERNAL;
15719            moveCompleteApp = true;
15720            measurePath = Environment.getDataAppDirectory(volumeUuid);
15721        }
15722
15723        final PackageStats stats = new PackageStats(null, -1);
15724        synchronized (mInstaller) {
15725            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15726                unfreezePackage(packageName);
15727                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15728                        "Failed to measure package size");
15729            }
15730        }
15731
15732        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15733                + stats.dataSize);
15734
15735        final long startFreeBytes = measurePath.getFreeSpace();
15736        final long sizeBytes;
15737        if (moveCompleteApp) {
15738            sizeBytes = stats.codeSize + stats.dataSize;
15739        } else {
15740            sizeBytes = stats.codeSize;
15741        }
15742
15743        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15744            unfreezePackage(packageName);
15745            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15746                    "Not enough free space to move");
15747        }
15748
15749        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15750
15751        final CountDownLatch installedLatch = new CountDownLatch(1);
15752        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15753            @Override
15754            public void onUserActionRequired(Intent intent) throws RemoteException {
15755                throw new IllegalStateException();
15756            }
15757
15758            @Override
15759            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15760                    Bundle extras) throws RemoteException {
15761                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15762                        + PackageManager.installStatusToString(returnCode, msg));
15763
15764                installedLatch.countDown();
15765
15766                // Regardless of success or failure of the move operation,
15767                // always unfreeze the package
15768                unfreezePackage(packageName);
15769
15770                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15771                switch (status) {
15772                    case PackageInstaller.STATUS_SUCCESS:
15773                        mMoveCallbacks.notifyStatusChanged(moveId,
15774                                PackageManager.MOVE_SUCCEEDED);
15775                        break;
15776                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15777                        mMoveCallbacks.notifyStatusChanged(moveId,
15778                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15779                        break;
15780                    default:
15781                        mMoveCallbacks.notifyStatusChanged(moveId,
15782                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15783                        break;
15784                }
15785            }
15786        };
15787
15788        final MoveInfo move;
15789        if (moveCompleteApp) {
15790            // Kick off a thread to report progress estimates
15791            new Thread() {
15792                @Override
15793                public void run() {
15794                    while (true) {
15795                        try {
15796                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15797                                break;
15798                            }
15799                        } catch (InterruptedException ignored) {
15800                        }
15801
15802                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15803                        final int progress = 10 + (int) MathUtils.constrain(
15804                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15805                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15806                    }
15807                }
15808            }.start();
15809
15810            final String dataAppName = codeFile.getName();
15811            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15812                    dataAppName, appId, seinfo);
15813        } else {
15814            move = null;
15815        }
15816
15817        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15818
15819        final Message msg = mHandler.obtainMessage(INIT_COPY);
15820        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15821        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15822                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15823        mHandler.sendMessage(msg);
15824    }
15825
15826    @Override
15827    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15828        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15829
15830        final int realMoveId = mNextMoveId.getAndIncrement();
15831        final Bundle extras = new Bundle();
15832        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15833        mMoveCallbacks.notifyCreated(realMoveId, extras);
15834
15835        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15836            @Override
15837            public void onCreated(int moveId, Bundle extras) {
15838                // Ignored
15839            }
15840
15841            @Override
15842            public void onStatusChanged(int moveId, int status, long estMillis) {
15843                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15844            }
15845        };
15846
15847        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15848        storage.setPrimaryStorageUuid(volumeUuid, callback);
15849        return realMoveId;
15850    }
15851
15852    @Override
15853    public int getMoveStatus(int moveId) {
15854        mContext.enforceCallingOrSelfPermission(
15855                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15856        return mMoveCallbacks.mLastStatus.get(moveId);
15857    }
15858
15859    @Override
15860    public void registerMoveCallback(IPackageMoveObserver callback) {
15861        mContext.enforceCallingOrSelfPermission(
15862                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15863        mMoveCallbacks.register(callback);
15864    }
15865
15866    @Override
15867    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15868        mContext.enforceCallingOrSelfPermission(
15869                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15870        mMoveCallbacks.unregister(callback);
15871    }
15872
15873    @Override
15874    public boolean setInstallLocation(int loc) {
15875        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15876                null);
15877        if (getInstallLocation() == loc) {
15878            return true;
15879        }
15880        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15881                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15882            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15883                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15884            return true;
15885        }
15886        return false;
15887   }
15888
15889    @Override
15890    public int getInstallLocation() {
15891        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15892                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15893                PackageHelper.APP_INSTALL_AUTO);
15894    }
15895
15896    /** Called by UserManagerService */
15897    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15898        mDirtyUsers.remove(userHandle);
15899        mSettings.removeUserLPw(userHandle);
15900        mPendingBroadcasts.remove(userHandle);
15901        if (mInstaller != null) {
15902            // Technically, we shouldn't be doing this with the package lock
15903            // held.  However, this is very rare, and there is already so much
15904            // other disk I/O going on, that we'll let it slide for now.
15905            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15906            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15907                final String volumeUuid = vol.getFsUuid();
15908                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15909                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15910            }
15911        }
15912        mUserNeedsBadging.delete(userHandle);
15913        removeUnusedPackagesLILPw(userManager, userHandle);
15914    }
15915
15916    /**
15917     * We're removing userHandle and would like to remove any downloaded packages
15918     * that are no longer in use by any other user.
15919     * @param userHandle the user being removed
15920     */
15921    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15922        final boolean DEBUG_CLEAN_APKS = false;
15923        int [] users = userManager.getUserIdsLPr();
15924        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15925        while (psit.hasNext()) {
15926            PackageSetting ps = psit.next();
15927            if (ps.pkg == null) {
15928                continue;
15929            }
15930            final String packageName = ps.pkg.packageName;
15931            // Skip over if system app
15932            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15933                continue;
15934            }
15935            if (DEBUG_CLEAN_APKS) {
15936                Slog.i(TAG, "Checking package " + packageName);
15937            }
15938            boolean keep = false;
15939            for (int i = 0; i < users.length; i++) {
15940                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15941                    keep = true;
15942                    if (DEBUG_CLEAN_APKS) {
15943                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15944                                + users[i]);
15945                    }
15946                    break;
15947                }
15948            }
15949            if (!keep) {
15950                if (DEBUG_CLEAN_APKS) {
15951                    Slog.i(TAG, "  Removing package " + packageName);
15952                }
15953                mHandler.post(new Runnable() {
15954                    public void run() {
15955                        deletePackageX(packageName, userHandle, 0);
15956                    } //end run
15957                });
15958            }
15959        }
15960    }
15961
15962    /** Called by UserManagerService */
15963    void createNewUserLILPw(int userHandle) {
15964        if (mInstaller != null) {
15965            mInstaller.createUserConfig(userHandle);
15966            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15967            applyFactoryDefaultBrowserLPw(userHandle);
15968            primeDomainVerificationsLPw(userHandle);
15969        }
15970    }
15971
15972    void newUserCreated(final int userHandle) {
15973        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15974    }
15975
15976    @Override
15977    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15978        mContext.enforceCallingOrSelfPermission(
15979                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15980                "Only package verification agents can read the verifier device identity");
15981
15982        synchronized (mPackages) {
15983            return mSettings.getVerifierDeviceIdentityLPw();
15984        }
15985    }
15986
15987    @Override
15988    public void setPermissionEnforced(String permission, boolean enforced) {
15989        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15990        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15991            synchronized (mPackages) {
15992                if (mSettings.mReadExternalStorageEnforced == null
15993                        || mSettings.mReadExternalStorageEnforced != enforced) {
15994                    mSettings.mReadExternalStorageEnforced = enforced;
15995                    mSettings.writeLPr();
15996                }
15997            }
15998            // kill any non-foreground processes so we restart them and
15999            // grant/revoke the GID.
16000            final IActivityManager am = ActivityManagerNative.getDefault();
16001            if (am != null) {
16002                final long token = Binder.clearCallingIdentity();
16003                try {
16004                    am.killProcessesBelowForeground("setPermissionEnforcement");
16005                } catch (RemoteException e) {
16006                } finally {
16007                    Binder.restoreCallingIdentity(token);
16008                }
16009            }
16010        } else {
16011            throw new IllegalArgumentException("No selective enforcement for " + permission);
16012        }
16013    }
16014
16015    @Override
16016    @Deprecated
16017    public boolean isPermissionEnforced(String permission) {
16018        return true;
16019    }
16020
16021    @Override
16022    public boolean isStorageLow() {
16023        final long token = Binder.clearCallingIdentity();
16024        try {
16025            final DeviceStorageMonitorInternal
16026                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16027            if (dsm != null) {
16028                return dsm.isMemoryLow();
16029            } else {
16030                return false;
16031            }
16032        } finally {
16033            Binder.restoreCallingIdentity(token);
16034        }
16035    }
16036
16037    @Override
16038    public IPackageInstaller getPackageInstaller() {
16039        return mInstallerService;
16040    }
16041
16042    private boolean userNeedsBadging(int userId) {
16043        int index = mUserNeedsBadging.indexOfKey(userId);
16044        if (index < 0) {
16045            final UserInfo userInfo;
16046            final long token = Binder.clearCallingIdentity();
16047            try {
16048                userInfo = sUserManager.getUserInfo(userId);
16049            } finally {
16050                Binder.restoreCallingIdentity(token);
16051            }
16052            final boolean b;
16053            if (userInfo != null && userInfo.isManagedProfile()) {
16054                b = true;
16055            } else {
16056                b = false;
16057            }
16058            mUserNeedsBadging.put(userId, b);
16059            return b;
16060        }
16061        return mUserNeedsBadging.valueAt(index);
16062    }
16063
16064    @Override
16065    public KeySet getKeySetByAlias(String packageName, String alias) {
16066        if (packageName == null || alias == null) {
16067            return null;
16068        }
16069        synchronized(mPackages) {
16070            final PackageParser.Package pkg = mPackages.get(packageName);
16071            if (pkg == null) {
16072                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16073                throw new IllegalArgumentException("Unknown package: " + packageName);
16074            }
16075            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16076            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16077        }
16078    }
16079
16080    @Override
16081    public KeySet getSigningKeySet(String packageName) {
16082        if (packageName == null) {
16083            return null;
16084        }
16085        synchronized(mPackages) {
16086            final PackageParser.Package pkg = mPackages.get(packageName);
16087            if (pkg == null) {
16088                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16089                throw new IllegalArgumentException("Unknown package: " + packageName);
16090            }
16091            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16092                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16093                throw new SecurityException("May not access signing KeySet of other apps.");
16094            }
16095            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16096            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16097        }
16098    }
16099
16100    @Override
16101    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16102        if (packageName == null || ks == null) {
16103            return false;
16104        }
16105        synchronized(mPackages) {
16106            final PackageParser.Package pkg = mPackages.get(packageName);
16107            if (pkg == null) {
16108                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16109                throw new IllegalArgumentException("Unknown package: " + packageName);
16110            }
16111            IBinder ksh = ks.getToken();
16112            if (ksh instanceof KeySetHandle) {
16113                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16114                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16115            }
16116            return false;
16117        }
16118    }
16119
16120    @Override
16121    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16122        if (packageName == null || ks == null) {
16123            return false;
16124        }
16125        synchronized(mPackages) {
16126            final PackageParser.Package pkg = mPackages.get(packageName);
16127            if (pkg == null) {
16128                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16129                throw new IllegalArgumentException("Unknown package: " + packageName);
16130            }
16131            IBinder ksh = ks.getToken();
16132            if (ksh instanceof KeySetHandle) {
16133                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16134                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16135            }
16136            return false;
16137        }
16138    }
16139
16140    public void getUsageStatsIfNoPackageUsageInfo() {
16141        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16142            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16143            if (usm == null) {
16144                throw new IllegalStateException("UsageStatsManager must be initialized");
16145            }
16146            long now = System.currentTimeMillis();
16147            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16148            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16149                String packageName = entry.getKey();
16150                PackageParser.Package pkg = mPackages.get(packageName);
16151                if (pkg == null) {
16152                    continue;
16153                }
16154                UsageStats usage = entry.getValue();
16155                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16156                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16157            }
16158        }
16159    }
16160
16161    /**
16162     * Check and throw if the given before/after packages would be considered a
16163     * downgrade.
16164     */
16165    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16166            throws PackageManagerException {
16167        if (after.versionCode < before.mVersionCode) {
16168            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16169                    "Update version code " + after.versionCode + " is older than current "
16170                    + before.mVersionCode);
16171        } else if (after.versionCode == before.mVersionCode) {
16172            if (after.baseRevisionCode < before.baseRevisionCode) {
16173                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16174                        "Update base revision code " + after.baseRevisionCode
16175                        + " is older than current " + before.baseRevisionCode);
16176            }
16177
16178            if (!ArrayUtils.isEmpty(after.splitNames)) {
16179                for (int i = 0; i < after.splitNames.length; i++) {
16180                    final String splitName = after.splitNames[i];
16181                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16182                    if (j != -1) {
16183                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16184                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16185                                    "Update split " + splitName + " revision code "
16186                                    + after.splitRevisionCodes[i] + " is older than current "
16187                                    + before.splitRevisionCodes[j]);
16188                        }
16189                    }
16190                }
16191            }
16192        }
16193    }
16194
16195    private static class MoveCallbacks extends Handler {
16196        private static final int MSG_CREATED = 1;
16197        private static final int MSG_STATUS_CHANGED = 2;
16198
16199        private final RemoteCallbackList<IPackageMoveObserver>
16200                mCallbacks = new RemoteCallbackList<>();
16201
16202        private final SparseIntArray mLastStatus = new SparseIntArray();
16203
16204        public MoveCallbacks(Looper looper) {
16205            super(looper);
16206        }
16207
16208        public void register(IPackageMoveObserver callback) {
16209            mCallbacks.register(callback);
16210        }
16211
16212        public void unregister(IPackageMoveObserver callback) {
16213            mCallbacks.unregister(callback);
16214        }
16215
16216        @Override
16217        public void handleMessage(Message msg) {
16218            final SomeArgs args = (SomeArgs) msg.obj;
16219            final int n = mCallbacks.beginBroadcast();
16220            for (int i = 0; i < n; i++) {
16221                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16222                try {
16223                    invokeCallback(callback, msg.what, args);
16224                } catch (RemoteException ignored) {
16225                }
16226            }
16227            mCallbacks.finishBroadcast();
16228            args.recycle();
16229        }
16230
16231        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16232                throws RemoteException {
16233            switch (what) {
16234                case MSG_CREATED: {
16235                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16236                    break;
16237                }
16238                case MSG_STATUS_CHANGED: {
16239                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16240                    break;
16241                }
16242            }
16243        }
16244
16245        private void notifyCreated(int moveId, Bundle extras) {
16246            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16247
16248            final SomeArgs args = SomeArgs.obtain();
16249            args.argi1 = moveId;
16250            args.arg2 = extras;
16251            obtainMessage(MSG_CREATED, args).sendToTarget();
16252        }
16253
16254        private void notifyStatusChanged(int moveId, int status) {
16255            notifyStatusChanged(moveId, status, -1);
16256        }
16257
16258        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16259            Slog.v(TAG, "Move " + moveId + " status " + status);
16260
16261            final SomeArgs args = SomeArgs.obtain();
16262            args.argi1 = moveId;
16263            args.argi2 = status;
16264            args.arg3 = estMillis;
16265            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16266
16267            synchronized (mLastStatus) {
16268                mLastStatus.put(moveId, status);
16269            }
16270        }
16271    }
16272
16273    private final class OnPermissionChangeListeners extends Handler {
16274        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16275
16276        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16277                new RemoteCallbackList<>();
16278
16279        public OnPermissionChangeListeners(Looper looper) {
16280            super(looper);
16281        }
16282
16283        @Override
16284        public void handleMessage(Message msg) {
16285            switch (msg.what) {
16286                case MSG_ON_PERMISSIONS_CHANGED: {
16287                    final int uid = msg.arg1;
16288                    handleOnPermissionsChanged(uid);
16289                } break;
16290            }
16291        }
16292
16293        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16294            mPermissionListeners.register(listener);
16295
16296        }
16297
16298        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16299            mPermissionListeners.unregister(listener);
16300        }
16301
16302        public void onPermissionsChanged(int uid) {
16303            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16304                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16305            }
16306        }
16307
16308        private void handleOnPermissionsChanged(int uid) {
16309            final int count = mPermissionListeners.beginBroadcast();
16310            try {
16311                for (int i = 0; i < count; i++) {
16312                    IOnPermissionsChangeListener callback = mPermissionListeners
16313                            .getBroadcastItem(i);
16314                    try {
16315                        callback.onPermissionsChanged(uid);
16316                    } catch (RemoteException e) {
16317                        Log.e(TAG, "Permission listener is dead", e);
16318                    }
16319                }
16320            } finally {
16321                mPermissionListeners.finishBroadcast();
16322            }
16323        }
16324    }
16325
16326    private class PackageManagerInternalImpl extends PackageManagerInternal {
16327        @Override
16328        public void setLocationPackagesProvider(PackagesProvider provider) {
16329            synchronized (mPackages) {
16330                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16331            }
16332        }
16333
16334        @Override
16335        public void setImePackagesProvider(PackagesProvider provider) {
16336            synchronized (mPackages) {
16337                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16338            }
16339        }
16340
16341        @Override
16342        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16343            synchronized (mPackages) {
16344                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16345            }
16346        }
16347
16348        @Override
16349        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16350            synchronized (mPackages) {
16351                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16352            }
16353        }
16354
16355        @Override
16356        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16357            synchronized (mPackages) {
16358                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16359            }
16360        }
16361
16362        @Override
16363        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16364            synchronized (mPackages) {
16365                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16366            }
16367        }
16368
16369        @Override
16370        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16371            synchronized (mPackages) {
16372                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16373                        packageName, userId);
16374            }
16375        }
16376
16377        @Override
16378        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16379            synchronized (mPackages) {
16380                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16381                        packageName, userId);
16382            }
16383        }
16384    }
16385
16386    @Override
16387    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16388        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16389        synchronized (mPackages) {
16390            final long identity = Binder.clearCallingIdentity();
16391            try {
16392                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16393                        packageNames, userId);
16394            } finally {
16395                Binder.restoreCallingIdentity(identity);
16396            }
16397        }
16398    }
16399
16400    private static void enforceSystemOrPhoneCaller(String tag) {
16401        int callingUid = Binder.getCallingUid();
16402        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16403            throw new SecurityException(
16404                    "Cannot call " + tag + " from UID " + callingUid);
16405        }
16406    }
16407}
16408