PackageManagerService.java revision 2d42d5f41eefc5550b6750cb86a5324c8f28959f
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            final long token = Binder.clearCallingIdentity();
3467            try {
3468                if (sUserManager.isInitialized(userId)) {
3469                    final StorageManager storage = mContext.getSystemService(StorageManager.class);
3470                    storage.remountUid(uid);
3471                }
3472            } finally {
3473                Binder.restoreCallingIdentity(token);
3474            }
3475        }
3476    }
3477
3478    @Override
3479    public void revokeRuntimePermission(String packageName, String name, int userId) {
3480        if (!sUserManager.exists(userId)) {
3481            Log.e(TAG, "No such user:" + userId);
3482            return;
3483        }
3484
3485        mContext.enforceCallingOrSelfPermission(
3486                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3487                "revokeRuntimePermission");
3488
3489        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3490                "revokeRuntimePermission");
3491
3492        final SettingBase sb;
3493
3494        synchronized (mPackages) {
3495            final PackageParser.Package pkg = mPackages.get(packageName);
3496            if (pkg == null) {
3497                throw new IllegalArgumentException("Unknown package: " + packageName);
3498            }
3499
3500            final BasePermission bp = mSettings.mPermissions.get(name);
3501            if (bp == null) {
3502                throw new IllegalArgumentException("Unknown permission: " + name);
3503            }
3504
3505            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3506
3507            sb = (SettingBase) pkg.mExtras;
3508            if (sb == null) {
3509                throw new IllegalArgumentException("Unknown package: " + packageName);
3510            }
3511
3512            final PermissionsState permissionsState = sb.getPermissionsState();
3513
3514            final int flags = permissionsState.getPermissionFlags(name, userId);
3515            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3516                throw new SecurityException("Cannot revoke system fixed permission: "
3517                        + name + " for package: " + packageName);
3518            }
3519
3520            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3521                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3522                return;
3523            }
3524
3525            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3526
3527            // Critical, after this call app should never have the permission.
3528            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3529        }
3530
3531        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3532    }
3533
3534    @Override
3535    public void resetRuntimePermissions() {
3536        mContext.enforceCallingOrSelfPermission(
3537                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3538                "revokeRuntimePermission");
3539
3540        int callingUid = Binder.getCallingUid();
3541        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3542            mContext.enforceCallingOrSelfPermission(
3543                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3544                    "resetRuntimePermissions");
3545        }
3546
3547        final int[] userIds;
3548
3549        synchronized (mPackages) {
3550            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3551            final int userCount = UserManagerService.getInstance().getUserIds().length;
3552            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3553        }
3554
3555        for (int userId : userIds) {
3556            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3557        }
3558    }
3559
3560    @Override
3561    public int getPermissionFlags(String name, String packageName, int userId) {
3562        if (!sUserManager.exists(userId)) {
3563            return 0;
3564        }
3565
3566        mContext.enforceCallingOrSelfPermission(
3567                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3568                "getPermissionFlags");
3569
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3571                "getPermissionFlags");
3572
3573        synchronized (mPackages) {
3574            final PackageParser.Package pkg = mPackages.get(packageName);
3575            if (pkg == null) {
3576                throw new IllegalArgumentException("Unknown package: " + packageName);
3577            }
3578
3579            final BasePermission bp = mSettings.mPermissions.get(name);
3580            if (bp == null) {
3581                throw new IllegalArgumentException("Unknown permission: " + name);
3582            }
3583
3584            SettingBase sb = (SettingBase) pkg.mExtras;
3585            if (sb == null) {
3586                throw new IllegalArgumentException("Unknown package: " + packageName);
3587            }
3588
3589            PermissionsState permissionsState = sb.getPermissionsState();
3590            return permissionsState.getPermissionFlags(name, userId);
3591        }
3592    }
3593
3594    @Override
3595    public void updatePermissionFlags(String name, String packageName, int flagMask,
3596            int flagValues, int userId) {
3597        if (!sUserManager.exists(userId)) {
3598            return;
3599        }
3600
3601        mContext.enforceCallingOrSelfPermission(
3602                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3603                "updatePermissionFlags");
3604
3605        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3606                "updatePermissionFlags");
3607
3608        // Only the system can change system fixed flags.
3609        if (getCallingUid() != Process.SYSTEM_UID) {
3610            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3611            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3612        }
3613
3614        synchronized (mPackages) {
3615            final PackageParser.Package pkg = mPackages.get(packageName);
3616            if (pkg == null) {
3617                throw new IllegalArgumentException("Unknown package: " + packageName);
3618            }
3619
3620            final BasePermission bp = mSettings.mPermissions.get(name);
3621            if (bp == null) {
3622                throw new IllegalArgumentException("Unknown permission: " + name);
3623            }
3624
3625            SettingBase sb = (SettingBase) pkg.mExtras;
3626            if (sb == null) {
3627                throw new IllegalArgumentException("Unknown package: " + packageName);
3628            }
3629
3630            PermissionsState permissionsState = sb.getPermissionsState();
3631
3632            // Only the package manager can change flags for system component permissions.
3633            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3634            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3635                return;
3636            }
3637
3638            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3639
3640            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3641                // Install and runtime permissions are stored in different places,
3642                // so figure out what permission changed and persist the change.
3643                if (permissionsState.getInstallPermissionState(name) != null) {
3644                    scheduleWriteSettingsLocked();
3645                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3646                        || hadState) {
3647                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3648                }
3649            }
3650        }
3651    }
3652
3653    /**
3654     * Update the permission flags for all packages and runtime permissions of a user in order
3655     * to allow device or profile owner to remove POLICY_FIXED.
3656     */
3657    @Override
3658    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3659        if (!sUserManager.exists(userId)) {
3660            return;
3661        }
3662
3663        mContext.enforceCallingOrSelfPermission(
3664                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3665                "updatePermissionFlagsForAllApps");
3666
3667        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3668                "updatePermissionFlagsForAllApps");
3669
3670        // Only the system can change system fixed flags.
3671        if (getCallingUid() != Process.SYSTEM_UID) {
3672            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3673            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3674        }
3675
3676        synchronized (mPackages) {
3677            boolean changed = false;
3678            final int packageCount = mPackages.size();
3679            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3680                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3681                SettingBase sb = (SettingBase) pkg.mExtras;
3682                if (sb == null) {
3683                    continue;
3684                }
3685                PermissionsState permissionsState = sb.getPermissionsState();
3686                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3687                        userId, flagMask, flagValues);
3688            }
3689            if (changed) {
3690                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3691            }
3692        }
3693    }
3694
3695    @Override
3696    public boolean shouldShowRequestPermissionRationale(String permissionName,
3697            String packageName, int userId) {
3698        if (UserHandle.getCallingUserId() != userId) {
3699            mContext.enforceCallingPermission(
3700                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3701                    "canShowRequestPermissionRationale for user " + userId);
3702        }
3703
3704        final int uid = getPackageUid(packageName, userId);
3705        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3706            return false;
3707        }
3708
3709        if (checkPermission(permissionName, packageName, userId)
3710                == PackageManager.PERMISSION_GRANTED) {
3711            return false;
3712        }
3713
3714        final int flags;
3715
3716        final long identity = Binder.clearCallingIdentity();
3717        try {
3718            flags = getPermissionFlags(permissionName,
3719                    packageName, userId);
3720        } finally {
3721            Binder.restoreCallingIdentity(identity);
3722        }
3723
3724        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3725                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3726                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3727
3728        if ((flags & fixedFlags) != 0) {
3729            return false;
3730        }
3731
3732        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3733    }
3734
3735    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3736        BasePermission bp = mSettings.mPermissions.get(permission);
3737        if (bp == null) {
3738            throw new SecurityException("Missing " + permission + " permission");
3739        }
3740
3741        SettingBase sb = (SettingBase) pkg.mExtras;
3742        PermissionsState permissionsState = sb.getPermissionsState();
3743
3744        if (permissionsState.grantInstallPermission(bp) !=
3745                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3746            scheduleWriteSettingsLocked();
3747        }
3748    }
3749
3750    @Override
3751    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3752        mContext.enforceCallingOrSelfPermission(
3753                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3754                "addOnPermissionsChangeListener");
3755
3756        synchronized (mPackages) {
3757            mOnPermissionChangeListeners.addListenerLocked(listener);
3758        }
3759    }
3760
3761    @Override
3762    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3763        synchronized (mPackages) {
3764            mOnPermissionChangeListeners.removeListenerLocked(listener);
3765        }
3766    }
3767
3768    @Override
3769    public boolean isProtectedBroadcast(String actionName) {
3770        synchronized (mPackages) {
3771            return mProtectedBroadcasts.contains(actionName);
3772        }
3773    }
3774
3775    @Override
3776    public int checkSignatures(String pkg1, String pkg2) {
3777        synchronized (mPackages) {
3778            final PackageParser.Package p1 = mPackages.get(pkg1);
3779            final PackageParser.Package p2 = mPackages.get(pkg2);
3780            if (p1 == null || p1.mExtras == null
3781                    || p2 == null || p2.mExtras == null) {
3782                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3783            }
3784            return compareSignatures(p1.mSignatures, p2.mSignatures);
3785        }
3786    }
3787
3788    @Override
3789    public int checkUidSignatures(int uid1, int uid2) {
3790        // Map to base uids.
3791        uid1 = UserHandle.getAppId(uid1);
3792        uid2 = UserHandle.getAppId(uid2);
3793        // reader
3794        synchronized (mPackages) {
3795            Signature[] s1;
3796            Signature[] s2;
3797            Object obj = mSettings.getUserIdLPr(uid1);
3798            if (obj != null) {
3799                if (obj instanceof SharedUserSetting) {
3800                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3801                } else if (obj instanceof PackageSetting) {
3802                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3803                } else {
3804                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3805                }
3806            } else {
3807                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3808            }
3809            obj = mSettings.getUserIdLPr(uid2);
3810            if (obj != null) {
3811                if (obj instanceof SharedUserSetting) {
3812                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3813                } else if (obj instanceof PackageSetting) {
3814                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3815                } else {
3816                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3817                }
3818            } else {
3819                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3820            }
3821            return compareSignatures(s1, s2);
3822        }
3823    }
3824
3825    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3826        final long identity = Binder.clearCallingIdentity();
3827        try {
3828            if (sb instanceof SharedUserSetting) {
3829                SharedUserSetting sus = (SharedUserSetting) sb;
3830                final int packageCount = sus.packages.size();
3831                for (int i = 0; i < packageCount; i++) {
3832                    PackageSetting susPs = sus.packages.valueAt(i);
3833                    if (userId == UserHandle.USER_ALL) {
3834                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3835                    } else {
3836                        final int uid = UserHandle.getUid(userId, susPs.appId);
3837                        killUid(uid, reason);
3838                    }
3839                }
3840            } else if (sb instanceof PackageSetting) {
3841                PackageSetting ps = (PackageSetting) sb;
3842                if (userId == UserHandle.USER_ALL) {
3843                    killApplication(ps.pkg.packageName, ps.appId, reason);
3844                } else {
3845                    final int uid = UserHandle.getUid(userId, ps.appId);
3846                    killUid(uid, reason);
3847                }
3848            }
3849        } finally {
3850            Binder.restoreCallingIdentity(identity);
3851        }
3852    }
3853
3854    private static void killUid(int uid, String reason) {
3855        IActivityManager am = ActivityManagerNative.getDefault();
3856        if (am != null) {
3857            try {
3858                am.killUid(uid, reason);
3859            } catch (RemoteException e) {
3860                /* ignore - same process */
3861            }
3862        }
3863    }
3864
3865    /**
3866     * Compares two sets of signatures. Returns:
3867     * <br />
3868     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3869     * <br />
3870     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3871     * <br />
3872     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3873     * <br />
3874     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3875     * <br />
3876     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3877     */
3878    static int compareSignatures(Signature[] s1, Signature[] s2) {
3879        if (s1 == null) {
3880            return s2 == null
3881                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3882                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3883        }
3884
3885        if (s2 == null) {
3886            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3887        }
3888
3889        if (s1.length != s2.length) {
3890            return PackageManager.SIGNATURE_NO_MATCH;
3891        }
3892
3893        // Since both signature sets are of size 1, we can compare without HashSets.
3894        if (s1.length == 1) {
3895            return s1[0].equals(s2[0]) ?
3896                    PackageManager.SIGNATURE_MATCH :
3897                    PackageManager.SIGNATURE_NO_MATCH;
3898        }
3899
3900        ArraySet<Signature> set1 = new ArraySet<Signature>();
3901        for (Signature sig : s1) {
3902            set1.add(sig);
3903        }
3904        ArraySet<Signature> set2 = new ArraySet<Signature>();
3905        for (Signature sig : s2) {
3906            set2.add(sig);
3907        }
3908        // Make sure s2 contains all signatures in s1.
3909        if (set1.equals(set2)) {
3910            return PackageManager.SIGNATURE_MATCH;
3911        }
3912        return PackageManager.SIGNATURE_NO_MATCH;
3913    }
3914
3915    /**
3916     * If the database version for this type of package (internal storage or
3917     * external storage) is less than the version where package signatures
3918     * were updated, return true.
3919     */
3920    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3921        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3922                DatabaseVersion.SIGNATURE_END_ENTITY))
3923                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3924                        DatabaseVersion.SIGNATURE_END_ENTITY));
3925    }
3926
3927    /**
3928     * Used for backward compatibility to make sure any packages with
3929     * certificate chains get upgraded to the new style. {@code existingSigs}
3930     * will be in the old format (since they were stored on disk from before the
3931     * system upgrade) and {@code scannedSigs} will be in the newer format.
3932     */
3933    private int compareSignaturesCompat(PackageSignatures existingSigs,
3934            PackageParser.Package scannedPkg) {
3935        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3936            return PackageManager.SIGNATURE_NO_MATCH;
3937        }
3938
3939        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3940        for (Signature sig : existingSigs.mSignatures) {
3941            existingSet.add(sig);
3942        }
3943        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3944        for (Signature sig : scannedPkg.mSignatures) {
3945            try {
3946                Signature[] chainSignatures = sig.getChainSignatures();
3947                for (Signature chainSig : chainSignatures) {
3948                    scannedCompatSet.add(chainSig);
3949                }
3950            } catch (CertificateEncodingException e) {
3951                scannedCompatSet.add(sig);
3952            }
3953        }
3954        /*
3955         * Make sure the expanded scanned set contains all signatures in the
3956         * existing one.
3957         */
3958        if (scannedCompatSet.equals(existingSet)) {
3959            // Migrate the old signatures to the new scheme.
3960            existingSigs.assignSignatures(scannedPkg.mSignatures);
3961            // The new KeySets will be re-added later in the scanning process.
3962            synchronized (mPackages) {
3963                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3964            }
3965            return PackageManager.SIGNATURE_MATCH;
3966        }
3967        return PackageManager.SIGNATURE_NO_MATCH;
3968    }
3969
3970    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3971        if (isExternal(scannedPkg)) {
3972            return mSettings.isExternalDatabaseVersionOlderThan(
3973                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3974        } else {
3975            return mSettings.isInternalDatabaseVersionOlderThan(
3976                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3977        }
3978    }
3979
3980    private int compareSignaturesRecover(PackageSignatures existingSigs,
3981            PackageParser.Package scannedPkg) {
3982        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3983            return PackageManager.SIGNATURE_NO_MATCH;
3984        }
3985
3986        String msg = null;
3987        try {
3988            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3989                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3990                        + scannedPkg.packageName);
3991                return PackageManager.SIGNATURE_MATCH;
3992            }
3993        } catch (CertificateException e) {
3994            msg = e.getMessage();
3995        }
3996
3997        logCriticalInfo(Log.INFO,
3998                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3999        return PackageManager.SIGNATURE_NO_MATCH;
4000    }
4001
4002    @Override
4003    public String[] getPackagesForUid(int uid) {
4004        uid = UserHandle.getAppId(uid);
4005        // reader
4006        synchronized (mPackages) {
4007            Object obj = mSettings.getUserIdLPr(uid);
4008            if (obj instanceof SharedUserSetting) {
4009                final SharedUserSetting sus = (SharedUserSetting) obj;
4010                final int N = sus.packages.size();
4011                final String[] res = new String[N];
4012                final Iterator<PackageSetting> it = sus.packages.iterator();
4013                int i = 0;
4014                while (it.hasNext()) {
4015                    res[i++] = it.next().name;
4016                }
4017                return res;
4018            } else if (obj instanceof PackageSetting) {
4019                final PackageSetting ps = (PackageSetting) obj;
4020                return new String[] { ps.name };
4021            }
4022        }
4023        return null;
4024    }
4025
4026    @Override
4027    public String getNameForUid(int uid) {
4028        // reader
4029        synchronized (mPackages) {
4030            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4031            if (obj instanceof SharedUserSetting) {
4032                final SharedUserSetting sus = (SharedUserSetting) obj;
4033                return sus.name + ":" + sus.userId;
4034            } else if (obj instanceof PackageSetting) {
4035                final PackageSetting ps = (PackageSetting) obj;
4036                return ps.name;
4037            }
4038        }
4039        return null;
4040    }
4041
4042    @Override
4043    public int getUidForSharedUser(String sharedUserName) {
4044        if(sharedUserName == null) {
4045            return -1;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4050            if (suid == null) {
4051                return -1;
4052            }
4053            return suid.userId;
4054        }
4055    }
4056
4057    @Override
4058    public int getFlagsForUid(int uid) {
4059        synchronized (mPackages) {
4060            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4061            if (obj instanceof SharedUserSetting) {
4062                final SharedUserSetting sus = (SharedUserSetting) obj;
4063                return sus.pkgFlags;
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return ps.pkgFlags;
4067            }
4068        }
4069        return 0;
4070    }
4071
4072    @Override
4073    public int getPrivateFlagsForUid(int uid) {
4074        synchronized (mPackages) {
4075            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4076            if (obj instanceof SharedUserSetting) {
4077                final SharedUserSetting sus = (SharedUserSetting) obj;
4078                return sus.pkgPrivateFlags;
4079            } else if (obj instanceof PackageSetting) {
4080                final PackageSetting ps = (PackageSetting) obj;
4081                return ps.pkgPrivateFlags;
4082            }
4083        }
4084        return 0;
4085    }
4086
4087    @Override
4088    public boolean isUidPrivileged(int uid) {
4089        uid = UserHandle.getAppId(uid);
4090        // reader
4091        synchronized (mPackages) {
4092            Object obj = mSettings.getUserIdLPr(uid);
4093            if (obj instanceof SharedUserSetting) {
4094                final SharedUserSetting sus = (SharedUserSetting) obj;
4095                final Iterator<PackageSetting> it = sus.packages.iterator();
4096                while (it.hasNext()) {
4097                    if (it.next().isPrivileged()) {
4098                        return true;
4099                    }
4100                }
4101            } else if (obj instanceof PackageSetting) {
4102                final PackageSetting ps = (PackageSetting) obj;
4103                return ps.isPrivileged();
4104            }
4105        }
4106        return false;
4107    }
4108
4109    @Override
4110    public String[] getAppOpPermissionPackages(String permissionName) {
4111        synchronized (mPackages) {
4112            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4113            if (pkgs == null) {
4114                return null;
4115            }
4116            return pkgs.toArray(new String[pkgs.size()]);
4117        }
4118    }
4119
4120    @Override
4121    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4122            int flags, int userId) {
4123        if (!sUserManager.exists(userId)) return null;
4124        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4125        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4126        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4127    }
4128
4129    @Override
4130    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4131            IntentFilter filter, int match, ComponentName activity) {
4132        final int userId = UserHandle.getCallingUserId();
4133        if (DEBUG_PREFERRED) {
4134            Log.v(TAG, "setLastChosenActivity intent=" + intent
4135                + " resolvedType=" + resolvedType
4136                + " flags=" + flags
4137                + " filter=" + filter
4138                + " match=" + match
4139                + " activity=" + activity);
4140            filter.dump(new PrintStreamPrinter(System.out), "    ");
4141        }
4142        intent.setComponent(null);
4143        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4144        // Find any earlier preferred or last chosen entries and nuke them
4145        findPreferredActivity(intent, resolvedType,
4146                flags, query, 0, false, true, false, userId);
4147        // Add the new activity as the last chosen for this filter
4148        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4149                "Setting last chosen");
4150    }
4151
4152    @Override
4153    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4154        final int userId = UserHandle.getCallingUserId();
4155        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4156        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4157        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4158                false, false, false, userId);
4159    }
4160
4161    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4162            int flags, List<ResolveInfo> query, int userId) {
4163        if (query != null) {
4164            final int N = query.size();
4165            if (N == 1) {
4166                return query.get(0);
4167            } else if (N > 1) {
4168                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4169                // If there is more than one activity with the same priority,
4170                // then let the user decide between them.
4171                ResolveInfo r0 = query.get(0);
4172                ResolveInfo r1 = query.get(1);
4173                if (DEBUG_INTENT_MATCHING || debug) {
4174                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4175                            + r1.activityInfo.name + "=" + r1.priority);
4176                }
4177                // If the first activity has a higher priority, or a different
4178                // default, then it is always desireable to pick it.
4179                if (r0.priority != r1.priority
4180                        || r0.preferredOrder != r1.preferredOrder
4181                        || r0.isDefault != r1.isDefault) {
4182                    return query.get(0);
4183                }
4184                // If we have saved a preference for a preferred activity for
4185                // this Intent, use that.
4186                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4187                        flags, query, r0.priority, true, false, debug, userId);
4188                if (ri != null) {
4189                    return ri;
4190                }
4191                if (userId != 0) {
4192                    ri = new ResolveInfo(mResolveInfo);
4193                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4194                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4195                            ri.activityInfo.applicationInfo);
4196                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4197                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4198                    return ri;
4199                }
4200                return mResolveInfo;
4201            }
4202        }
4203        return null;
4204    }
4205
4206    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4207            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4208        final int N = query.size();
4209        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4210                .get(userId);
4211        // Get the list of persistent preferred activities that handle the intent
4212        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4213        List<PersistentPreferredActivity> pprefs = ppir != null
4214                ? ppir.queryIntent(intent, resolvedType,
4215                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4216                : null;
4217        if (pprefs != null && pprefs.size() > 0) {
4218            final int M = pprefs.size();
4219            for (int i=0; i<M; i++) {
4220                final PersistentPreferredActivity ppa = pprefs.get(i);
4221                if (DEBUG_PREFERRED || debug) {
4222                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4223                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4224                            + "\n  component=" + ppa.mComponent);
4225                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4226                }
4227                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4228                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4229                if (DEBUG_PREFERRED || debug) {
4230                    Slog.v(TAG, "Found persistent preferred activity:");
4231                    if (ai != null) {
4232                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4233                    } else {
4234                        Slog.v(TAG, "  null");
4235                    }
4236                }
4237                if (ai == null) {
4238                    // This previously registered persistent preferred activity
4239                    // component is no longer known. Ignore it and do NOT remove it.
4240                    continue;
4241                }
4242                for (int j=0; j<N; j++) {
4243                    final ResolveInfo ri = query.get(j);
4244                    if (!ri.activityInfo.applicationInfo.packageName
4245                            .equals(ai.applicationInfo.packageName)) {
4246                        continue;
4247                    }
4248                    if (!ri.activityInfo.name.equals(ai.name)) {
4249                        continue;
4250                    }
4251                    //  Found a persistent preference that can handle the intent.
4252                    if (DEBUG_PREFERRED || debug) {
4253                        Slog.v(TAG, "Returning persistent preferred activity: " +
4254                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4255                    }
4256                    return ri;
4257                }
4258            }
4259        }
4260        return null;
4261    }
4262
4263    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4264            List<ResolveInfo> query, int priority, boolean always,
4265            boolean removeMatches, boolean debug, int userId) {
4266        if (!sUserManager.exists(userId)) return null;
4267        // writer
4268        synchronized (mPackages) {
4269            if (intent.getSelector() != null) {
4270                intent = intent.getSelector();
4271            }
4272            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4273
4274            // Try to find a matching persistent preferred activity.
4275            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4276                    debug, userId);
4277
4278            // If a persistent preferred activity matched, use it.
4279            if (pri != null) {
4280                return pri;
4281            }
4282
4283            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4284            // Get the list of preferred activities that handle the intent
4285            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4286            List<PreferredActivity> prefs = pir != null
4287                    ? pir.queryIntent(intent, resolvedType,
4288                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4289                    : null;
4290            if (prefs != null && prefs.size() > 0) {
4291                boolean changed = false;
4292                try {
4293                    // First figure out how good the original match set is.
4294                    // We will only allow preferred activities that came
4295                    // from the same match quality.
4296                    int match = 0;
4297
4298                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4299
4300                    final int N = query.size();
4301                    for (int j=0; j<N; j++) {
4302                        final ResolveInfo ri = query.get(j);
4303                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4304                                + ": 0x" + Integer.toHexString(match));
4305                        if (ri.match > match) {
4306                            match = ri.match;
4307                        }
4308                    }
4309
4310                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4311                            + Integer.toHexString(match));
4312
4313                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4314                    final int M = prefs.size();
4315                    for (int i=0; i<M; i++) {
4316                        final PreferredActivity pa = prefs.get(i);
4317                        if (DEBUG_PREFERRED || debug) {
4318                            Slog.v(TAG, "Checking PreferredActivity ds="
4319                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4320                                    + "\n  component=" + pa.mPref.mComponent);
4321                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4322                        }
4323                        if (pa.mPref.mMatch != match) {
4324                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4325                                    + Integer.toHexString(pa.mPref.mMatch));
4326                            continue;
4327                        }
4328                        // If it's not an "always" type preferred activity and that's what we're
4329                        // looking for, skip it.
4330                        if (always && !pa.mPref.mAlways) {
4331                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4332                            continue;
4333                        }
4334                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4335                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4336                        if (DEBUG_PREFERRED || debug) {
4337                            Slog.v(TAG, "Found preferred activity:");
4338                            if (ai != null) {
4339                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4340                            } else {
4341                                Slog.v(TAG, "  null");
4342                            }
4343                        }
4344                        if (ai == null) {
4345                            // This previously registered preferred activity
4346                            // component is no longer known.  Most likely an update
4347                            // to the app was installed and in the new version this
4348                            // component no longer exists.  Clean it up by removing
4349                            // it from the preferred activities list, and skip it.
4350                            Slog.w(TAG, "Removing dangling preferred activity: "
4351                                    + pa.mPref.mComponent);
4352                            pir.removeFilter(pa);
4353                            changed = true;
4354                            continue;
4355                        }
4356                        for (int j=0; j<N; j++) {
4357                            final ResolveInfo ri = query.get(j);
4358                            if (!ri.activityInfo.applicationInfo.packageName
4359                                    .equals(ai.applicationInfo.packageName)) {
4360                                continue;
4361                            }
4362                            if (!ri.activityInfo.name.equals(ai.name)) {
4363                                continue;
4364                            }
4365
4366                            if (removeMatches) {
4367                                pir.removeFilter(pa);
4368                                changed = true;
4369                                if (DEBUG_PREFERRED) {
4370                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4371                                }
4372                                break;
4373                            }
4374
4375                            // Okay we found a previously set preferred or last chosen app.
4376                            // If the result set is different from when this
4377                            // was created, we need to clear it and re-ask the
4378                            // user their preference, if we're looking for an "always" type entry.
4379                            if (always && !pa.mPref.sameSet(query)) {
4380                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4381                                        + intent + " type " + resolvedType);
4382                                if (DEBUG_PREFERRED) {
4383                                    Slog.v(TAG, "Removing preferred activity since set changed "
4384                                            + pa.mPref.mComponent);
4385                                }
4386                                pir.removeFilter(pa);
4387                                // Re-add the filter as a "last chosen" entry (!always)
4388                                PreferredActivity lastChosen = new PreferredActivity(
4389                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4390                                pir.addFilter(lastChosen);
4391                                changed = true;
4392                                return null;
4393                            }
4394
4395                            // Yay! Either the set matched or we're looking for the last chosen
4396                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4397                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4398                            return ri;
4399                        }
4400                    }
4401                } finally {
4402                    if (changed) {
4403                        if (DEBUG_PREFERRED) {
4404                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4405                        }
4406                        scheduleWritePackageRestrictionsLocked(userId);
4407                    }
4408                }
4409            }
4410        }
4411        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4412        return null;
4413    }
4414
4415    /*
4416     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4417     */
4418    @Override
4419    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4420            int targetUserId) {
4421        mContext.enforceCallingOrSelfPermission(
4422                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4423        List<CrossProfileIntentFilter> matches =
4424                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4425        if (matches != null) {
4426            int size = matches.size();
4427            for (int i = 0; i < size; i++) {
4428                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4429            }
4430        }
4431        if (hasWebURI(intent)) {
4432            // cross-profile app linking works only towards the parent.
4433            final UserInfo parent = getProfileParent(sourceUserId);
4434            synchronized(mPackages) {
4435                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4436                        parent.id) != null;
4437            }
4438        }
4439        return false;
4440    }
4441
4442    private UserInfo getProfileParent(int userId) {
4443        final long identity = Binder.clearCallingIdentity();
4444        try {
4445            return sUserManager.getProfileParent(userId);
4446        } finally {
4447            Binder.restoreCallingIdentity(identity);
4448        }
4449    }
4450
4451    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4452            String resolvedType, int userId) {
4453        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4454        if (resolver != null) {
4455            return resolver.queryIntent(intent, resolvedType, false, userId);
4456        }
4457        return null;
4458    }
4459
4460    @Override
4461    public List<ResolveInfo> queryIntentActivities(Intent intent,
4462            String resolvedType, int flags, int userId) {
4463        if (!sUserManager.exists(userId)) return Collections.emptyList();
4464        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4465        ComponentName comp = intent.getComponent();
4466        if (comp == null) {
4467            if (intent.getSelector() != null) {
4468                intent = intent.getSelector();
4469                comp = intent.getComponent();
4470            }
4471        }
4472
4473        if (comp != null) {
4474            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4475            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4476            if (ai != null) {
4477                final ResolveInfo ri = new ResolveInfo();
4478                ri.activityInfo = ai;
4479                list.add(ri);
4480            }
4481            return list;
4482        }
4483
4484        // reader
4485        synchronized (mPackages) {
4486            final String pkgName = intent.getPackage();
4487            if (pkgName == null) {
4488                List<CrossProfileIntentFilter> matchingFilters =
4489                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4490                // Check for results that need to skip the current profile.
4491                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4492                        resolvedType, flags, userId);
4493                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4494                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4495                    result.add(xpResolveInfo);
4496                    return filterIfNotPrimaryUser(result, userId);
4497                }
4498
4499                // Check for results in the current profile.
4500                List<ResolveInfo> result = mActivities.queryIntent(
4501                        intent, resolvedType, flags, userId);
4502
4503                // Check for cross profile results.
4504                xpResolveInfo = queryCrossProfileIntents(
4505                        matchingFilters, intent, resolvedType, flags, userId);
4506                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4507                    result.add(xpResolveInfo);
4508                    Collections.sort(result, mResolvePrioritySorter);
4509                }
4510                result = filterIfNotPrimaryUser(result, userId);
4511                if (hasWebURI(intent)) {
4512                    CrossProfileDomainInfo xpDomainInfo = null;
4513                    final UserInfo parent = getProfileParent(userId);
4514                    if (parent != null) {
4515                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4516                                flags, userId, parent.id);
4517                    }
4518                    if (xpDomainInfo != null) {
4519                        if (xpResolveInfo != null) {
4520                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4521                            // in the result.
4522                            result.remove(xpResolveInfo);
4523                        }
4524                        if (result.size() == 0) {
4525                            result.add(xpDomainInfo.resolveInfo);
4526                            return result;
4527                        }
4528                    } else if (result.size() <= 1) {
4529                        return result;
4530                    }
4531                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4532                            xpDomainInfo);
4533                    Collections.sort(result, mResolvePrioritySorter);
4534                }
4535                return result;
4536            }
4537            final PackageParser.Package pkg = mPackages.get(pkgName);
4538            if (pkg != null) {
4539                return filterIfNotPrimaryUser(
4540                        mActivities.queryIntentForPackage(
4541                                intent, resolvedType, flags, pkg.activities, userId),
4542                        userId);
4543            }
4544            return new ArrayList<ResolveInfo>();
4545        }
4546    }
4547
4548    private static class CrossProfileDomainInfo {
4549        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4550        ResolveInfo resolveInfo;
4551        /* Best domain verification status of the activities found in the other profile */
4552        int bestDomainVerificationStatus;
4553    }
4554
4555    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4556            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4557        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4558                sourceUserId)) {
4559            return null;
4560        }
4561        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4562                resolvedType, flags, parentUserId);
4563
4564        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4565            return null;
4566        }
4567        CrossProfileDomainInfo result = null;
4568        int size = resultTargetUser.size();
4569        for (int i = 0; i < size; i++) {
4570            ResolveInfo riTargetUser = resultTargetUser.get(i);
4571            // Intent filter verification is only for filters that specify a host. So don't return
4572            // those that handle all web uris.
4573            if (riTargetUser.handleAllWebDataURI) {
4574                continue;
4575            }
4576            String packageName = riTargetUser.activityInfo.packageName;
4577            PackageSetting ps = mSettings.mPackages.get(packageName);
4578            if (ps == null) {
4579                continue;
4580            }
4581            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4582            if (result == null) {
4583                result = new CrossProfileDomainInfo();
4584                result.resolveInfo =
4585                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4586                result.bestDomainVerificationStatus = status;
4587            } else {
4588                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4589                        result.bestDomainVerificationStatus);
4590            }
4591        }
4592        return result;
4593    }
4594
4595    /**
4596     * Verification statuses are ordered from the worse to the best, except for
4597     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4598     */
4599    private int bestDomainVerificationStatus(int status1, int status2) {
4600        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4601            return status2;
4602        }
4603        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4604            return status1;
4605        }
4606        return (int) MathUtils.max(status1, status2);
4607    }
4608
4609    private boolean isUserEnabled(int userId) {
4610        long callingId = Binder.clearCallingIdentity();
4611        try {
4612            UserInfo userInfo = sUserManager.getUserInfo(userId);
4613            return userInfo != null && userInfo.isEnabled();
4614        } finally {
4615            Binder.restoreCallingIdentity(callingId);
4616        }
4617    }
4618
4619    /**
4620     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4621     *
4622     * @return filtered list
4623     */
4624    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4625        if (userId == UserHandle.USER_OWNER) {
4626            return resolveInfos;
4627        }
4628        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4629            ResolveInfo info = resolveInfos.get(i);
4630            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4631                resolveInfos.remove(i);
4632            }
4633        }
4634        return resolveInfos;
4635    }
4636
4637    private static boolean hasWebURI(Intent intent) {
4638        if (intent.getData() == null) {
4639            return false;
4640        }
4641        final String scheme = intent.getScheme();
4642        if (TextUtils.isEmpty(scheme)) {
4643            return false;
4644        }
4645        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4646    }
4647
4648    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4649            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4650        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4651            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4652                    candidates.size());
4653        }
4654
4655        final int userId = UserHandle.getCallingUserId();
4656        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4657        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4658        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4659        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4660        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4661
4662        synchronized (mPackages) {
4663            final int count = candidates.size();
4664            // First, try to use linked apps. Partition the candidates into four lists:
4665            // one for the final results, one for the "do not use ever", one for "undefined status"
4666            // and finally one for "browser app type".
4667            for (int n=0; n<count; n++) {
4668                ResolveInfo info = candidates.get(n);
4669                String packageName = info.activityInfo.packageName;
4670                PackageSetting ps = mSettings.mPackages.get(packageName);
4671                if (ps != null) {
4672                    // Add to the special match all list (Browser use case)
4673                    if (info.handleAllWebDataURI) {
4674                        matchAllList.add(info);
4675                        continue;
4676                    }
4677                    // Try to get the status from User settings first
4678                    int status = getDomainVerificationStatusLPr(ps, userId);
4679                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4680                        if (DEBUG_DOMAIN_VERIFICATION) {
4681                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4682                        }
4683                        alwaysList.add(info);
4684                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4685                        if (DEBUG_DOMAIN_VERIFICATION) {
4686                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4687                        }
4688                        neverList.add(info);
4689                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4690                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4691                        if (DEBUG_DOMAIN_VERIFICATION) {
4692                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4693                        }
4694                        undefinedList.add(info);
4695                    }
4696                }
4697            }
4698            // First try to add the "always" resolution for the current user if there is any
4699            if (alwaysList.size() > 0) {
4700                result.addAll(alwaysList);
4701            // if there is an "always" for the parent user, add it.
4702            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4703                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4704                result.add(xpDomainInfo.resolveInfo);
4705            } else {
4706                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4707                result.addAll(undefinedList);
4708                if (xpDomainInfo != null && (
4709                        xpDomainInfo.bestDomainVerificationStatus
4710                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4711                        || xpDomainInfo.bestDomainVerificationStatus
4712                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4713                    result.add(xpDomainInfo.resolveInfo);
4714                }
4715                // Also add Browsers (all of them or only the default one)
4716                if ((flags & MATCH_ALL) != 0) {
4717                    result.addAll(matchAllList);
4718                } else {
4719                    // Try to add the Default Browser if we can
4720                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4721                            UserHandle.myUserId());
4722                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4723                        boolean defaultBrowserFound = false;
4724                        final int browserCount = matchAllList.size();
4725                        for (int n=0; n<browserCount; n++) {
4726                            ResolveInfo browser = matchAllList.get(n);
4727                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4728                                result.add(browser);
4729                                defaultBrowserFound = true;
4730                                break;
4731                            }
4732                        }
4733                        if (!defaultBrowserFound) {
4734                            result.addAll(matchAllList);
4735                        }
4736                    } else {
4737                        result.addAll(matchAllList);
4738                    }
4739                }
4740
4741                // If there is nothing selected, add all candidates and remove the ones that the user
4742                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4743                if (result.size() == 0) {
4744                    result.addAll(candidates);
4745                    result.removeAll(neverList);
4746                }
4747            }
4748        }
4749        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4750            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4751                    result.size());
4752            for (ResolveInfo info : result) {
4753                Slog.v(TAG, "  + " + info.activityInfo);
4754            }
4755        }
4756        return result;
4757    }
4758
4759    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4760        int status = ps.getDomainVerificationStatusForUser(userId);
4761        // if none available, get the master status
4762        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4763            if (ps.getIntentFilterVerificationInfo() != null) {
4764                status = ps.getIntentFilterVerificationInfo().getStatus();
4765            }
4766        }
4767        return status;
4768    }
4769
4770    private ResolveInfo querySkipCurrentProfileIntents(
4771            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4772            int flags, int sourceUserId) {
4773        if (matchingFilters != null) {
4774            int size = matchingFilters.size();
4775            for (int i = 0; i < size; i ++) {
4776                CrossProfileIntentFilter filter = matchingFilters.get(i);
4777                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4778                    // Checking if there are activities in the target user that can handle the
4779                    // intent.
4780                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4781                            flags, sourceUserId);
4782                    if (resolveInfo != null) {
4783                        return resolveInfo;
4784                    }
4785                }
4786            }
4787        }
4788        return null;
4789    }
4790
4791    // Return matching ResolveInfo if any for skip current profile intent filters.
4792    private ResolveInfo queryCrossProfileIntents(
4793            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4794            int flags, int sourceUserId) {
4795        if (matchingFilters != null) {
4796            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4797            // match the same intent. For performance reasons, it is better not to
4798            // run queryIntent twice for the same userId
4799            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4800            int size = matchingFilters.size();
4801            for (int i = 0; i < size; i++) {
4802                CrossProfileIntentFilter filter = matchingFilters.get(i);
4803                int targetUserId = filter.getTargetUserId();
4804                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4805                        && !alreadyTriedUserIds.get(targetUserId)) {
4806                    // Checking if there are activities in the target user that can handle the
4807                    // intent.
4808                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4809                            flags, sourceUserId);
4810                    if (resolveInfo != null) return resolveInfo;
4811                    alreadyTriedUserIds.put(targetUserId, true);
4812                }
4813            }
4814        }
4815        return null;
4816    }
4817
4818    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4819            String resolvedType, int flags, int sourceUserId) {
4820        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4821                resolvedType, flags, filter.getTargetUserId());
4822        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4823            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4824        }
4825        return null;
4826    }
4827
4828    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4829            int sourceUserId, int targetUserId) {
4830        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4831        String className;
4832        if (targetUserId == UserHandle.USER_OWNER) {
4833            className = FORWARD_INTENT_TO_USER_OWNER;
4834        } else {
4835            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4836        }
4837        ComponentName forwardingActivityComponentName = new ComponentName(
4838                mAndroidApplication.packageName, className);
4839        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4840                sourceUserId);
4841        if (targetUserId == UserHandle.USER_OWNER) {
4842            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4843            forwardingResolveInfo.noResourceId = true;
4844        }
4845        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4846        forwardingResolveInfo.priority = 0;
4847        forwardingResolveInfo.preferredOrder = 0;
4848        forwardingResolveInfo.match = 0;
4849        forwardingResolveInfo.isDefault = true;
4850        forwardingResolveInfo.filter = filter;
4851        forwardingResolveInfo.targetUserId = targetUserId;
4852        return forwardingResolveInfo;
4853    }
4854
4855    @Override
4856    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4857            Intent[] specifics, String[] specificTypes, Intent intent,
4858            String resolvedType, int flags, int userId) {
4859        if (!sUserManager.exists(userId)) return Collections.emptyList();
4860        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4861                false, "query intent activity options");
4862        final String resultsAction = intent.getAction();
4863
4864        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4865                | PackageManager.GET_RESOLVED_FILTER, userId);
4866
4867        if (DEBUG_INTENT_MATCHING) {
4868            Log.v(TAG, "Query " + intent + ": " + results);
4869        }
4870
4871        int specificsPos = 0;
4872        int N;
4873
4874        // todo: note that the algorithm used here is O(N^2).  This
4875        // isn't a problem in our current environment, but if we start running
4876        // into situations where we have more than 5 or 10 matches then this
4877        // should probably be changed to something smarter...
4878
4879        // First we go through and resolve each of the specific items
4880        // that were supplied, taking care of removing any corresponding
4881        // duplicate items in the generic resolve list.
4882        if (specifics != null) {
4883            for (int i=0; i<specifics.length; i++) {
4884                final Intent sintent = specifics[i];
4885                if (sintent == null) {
4886                    continue;
4887                }
4888
4889                if (DEBUG_INTENT_MATCHING) {
4890                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4891                }
4892
4893                String action = sintent.getAction();
4894                if (resultsAction != null && resultsAction.equals(action)) {
4895                    // If this action was explicitly requested, then don't
4896                    // remove things that have it.
4897                    action = null;
4898                }
4899
4900                ResolveInfo ri = null;
4901                ActivityInfo ai = null;
4902
4903                ComponentName comp = sintent.getComponent();
4904                if (comp == null) {
4905                    ri = resolveIntent(
4906                        sintent,
4907                        specificTypes != null ? specificTypes[i] : null,
4908                            flags, userId);
4909                    if (ri == null) {
4910                        continue;
4911                    }
4912                    if (ri == mResolveInfo) {
4913                        // ACK!  Must do something better with this.
4914                    }
4915                    ai = ri.activityInfo;
4916                    comp = new ComponentName(ai.applicationInfo.packageName,
4917                            ai.name);
4918                } else {
4919                    ai = getActivityInfo(comp, flags, userId);
4920                    if (ai == null) {
4921                        continue;
4922                    }
4923                }
4924
4925                // Look for any generic query activities that are duplicates
4926                // of this specific one, and remove them from the results.
4927                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4928                N = results.size();
4929                int j;
4930                for (j=specificsPos; j<N; j++) {
4931                    ResolveInfo sri = results.get(j);
4932                    if ((sri.activityInfo.name.equals(comp.getClassName())
4933                            && sri.activityInfo.applicationInfo.packageName.equals(
4934                                    comp.getPackageName()))
4935                        || (action != null && sri.filter.matchAction(action))) {
4936                        results.remove(j);
4937                        if (DEBUG_INTENT_MATCHING) Log.v(
4938                            TAG, "Removing duplicate item from " + j
4939                            + " due to specific " + specificsPos);
4940                        if (ri == null) {
4941                            ri = sri;
4942                        }
4943                        j--;
4944                        N--;
4945                    }
4946                }
4947
4948                // Add this specific item to its proper place.
4949                if (ri == null) {
4950                    ri = new ResolveInfo();
4951                    ri.activityInfo = ai;
4952                }
4953                results.add(specificsPos, ri);
4954                ri.specificIndex = i;
4955                specificsPos++;
4956            }
4957        }
4958
4959        // Now we go through the remaining generic results and remove any
4960        // duplicate actions that are found here.
4961        N = results.size();
4962        for (int i=specificsPos; i<N-1; i++) {
4963            final ResolveInfo rii = results.get(i);
4964            if (rii.filter == null) {
4965                continue;
4966            }
4967
4968            // Iterate over all of the actions of this result's intent
4969            // filter...  typically this should be just one.
4970            final Iterator<String> it = rii.filter.actionsIterator();
4971            if (it == null) {
4972                continue;
4973            }
4974            while (it.hasNext()) {
4975                final String action = it.next();
4976                if (resultsAction != null && resultsAction.equals(action)) {
4977                    // If this action was explicitly requested, then don't
4978                    // remove things that have it.
4979                    continue;
4980                }
4981                for (int j=i+1; j<N; j++) {
4982                    final ResolveInfo rij = results.get(j);
4983                    if (rij.filter != null && rij.filter.hasAction(action)) {
4984                        results.remove(j);
4985                        if (DEBUG_INTENT_MATCHING) Log.v(
4986                            TAG, "Removing duplicate item from " + j
4987                            + " due to action " + action + " at " + i);
4988                        j--;
4989                        N--;
4990                    }
4991                }
4992            }
4993
4994            // If the caller didn't request filter information, drop it now
4995            // so we don't have to marshall/unmarshall it.
4996            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4997                rii.filter = null;
4998            }
4999        }
5000
5001        // Filter out the caller activity if so requested.
5002        if (caller != null) {
5003            N = results.size();
5004            for (int i=0; i<N; i++) {
5005                ActivityInfo ainfo = results.get(i).activityInfo;
5006                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5007                        && caller.getClassName().equals(ainfo.name)) {
5008                    results.remove(i);
5009                    break;
5010                }
5011            }
5012        }
5013
5014        // If the caller didn't request filter information,
5015        // drop them now so we don't have to
5016        // marshall/unmarshall it.
5017        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5018            N = results.size();
5019            for (int i=0; i<N; i++) {
5020                results.get(i).filter = null;
5021            }
5022        }
5023
5024        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5025        return results;
5026    }
5027
5028    @Override
5029    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5030            int userId) {
5031        if (!sUserManager.exists(userId)) return Collections.emptyList();
5032        ComponentName comp = intent.getComponent();
5033        if (comp == null) {
5034            if (intent.getSelector() != null) {
5035                intent = intent.getSelector();
5036                comp = intent.getComponent();
5037            }
5038        }
5039        if (comp != null) {
5040            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5041            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5042            if (ai != null) {
5043                ResolveInfo ri = new ResolveInfo();
5044                ri.activityInfo = ai;
5045                list.add(ri);
5046            }
5047            return list;
5048        }
5049
5050        // reader
5051        synchronized (mPackages) {
5052            String pkgName = intent.getPackage();
5053            if (pkgName == null) {
5054                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5055            }
5056            final PackageParser.Package pkg = mPackages.get(pkgName);
5057            if (pkg != null) {
5058                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5059                        userId);
5060            }
5061            return null;
5062        }
5063    }
5064
5065    @Override
5066    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5067        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5068        if (!sUserManager.exists(userId)) return null;
5069        if (query != null) {
5070            if (query.size() >= 1) {
5071                // If there is more than one service with the same priority,
5072                // just arbitrarily pick the first one.
5073                return query.get(0);
5074            }
5075        }
5076        return null;
5077    }
5078
5079    @Override
5080    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5081            int userId) {
5082        if (!sUserManager.exists(userId)) return Collections.emptyList();
5083        ComponentName comp = intent.getComponent();
5084        if (comp == null) {
5085            if (intent.getSelector() != null) {
5086                intent = intent.getSelector();
5087                comp = intent.getComponent();
5088            }
5089        }
5090        if (comp != null) {
5091            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5092            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5093            if (si != null) {
5094                final ResolveInfo ri = new ResolveInfo();
5095                ri.serviceInfo = si;
5096                list.add(ri);
5097            }
5098            return list;
5099        }
5100
5101        // reader
5102        synchronized (mPackages) {
5103            String pkgName = intent.getPackage();
5104            if (pkgName == null) {
5105                return mServices.queryIntent(intent, resolvedType, flags, userId);
5106            }
5107            final PackageParser.Package pkg = mPackages.get(pkgName);
5108            if (pkg != null) {
5109                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5110                        userId);
5111            }
5112            return null;
5113        }
5114    }
5115
5116    @Override
5117    public List<ResolveInfo> queryIntentContentProviders(
5118            Intent intent, String resolvedType, int flags, int userId) {
5119        if (!sUserManager.exists(userId)) return Collections.emptyList();
5120        ComponentName comp = intent.getComponent();
5121        if (comp == null) {
5122            if (intent.getSelector() != null) {
5123                intent = intent.getSelector();
5124                comp = intent.getComponent();
5125            }
5126        }
5127        if (comp != null) {
5128            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5129            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5130            if (pi != null) {
5131                final ResolveInfo ri = new ResolveInfo();
5132                ri.providerInfo = pi;
5133                list.add(ri);
5134            }
5135            return list;
5136        }
5137
5138        // reader
5139        synchronized (mPackages) {
5140            String pkgName = intent.getPackage();
5141            if (pkgName == null) {
5142                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5143            }
5144            final PackageParser.Package pkg = mPackages.get(pkgName);
5145            if (pkg != null) {
5146                return mProviders.queryIntentForPackage(
5147                        intent, resolvedType, flags, pkg.providers, userId);
5148            }
5149            return null;
5150        }
5151    }
5152
5153    @Override
5154    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5155        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5156
5157        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5158
5159        // writer
5160        synchronized (mPackages) {
5161            ArrayList<PackageInfo> list;
5162            if (listUninstalled) {
5163                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5164                for (PackageSetting ps : mSettings.mPackages.values()) {
5165                    PackageInfo pi;
5166                    if (ps.pkg != null) {
5167                        pi = generatePackageInfo(ps.pkg, flags, userId);
5168                    } else {
5169                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5170                    }
5171                    if (pi != null) {
5172                        list.add(pi);
5173                    }
5174                }
5175            } else {
5176                list = new ArrayList<PackageInfo>(mPackages.size());
5177                for (PackageParser.Package p : mPackages.values()) {
5178                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5179                    if (pi != null) {
5180                        list.add(pi);
5181                    }
5182                }
5183            }
5184
5185            return new ParceledListSlice<PackageInfo>(list);
5186        }
5187    }
5188
5189    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5190            String[] permissions, boolean[] tmp, int flags, int userId) {
5191        int numMatch = 0;
5192        final PermissionsState permissionsState = ps.getPermissionsState();
5193        for (int i=0; i<permissions.length; i++) {
5194            final String permission = permissions[i];
5195            if (permissionsState.hasPermission(permission, userId)) {
5196                tmp[i] = true;
5197                numMatch++;
5198            } else {
5199                tmp[i] = false;
5200            }
5201        }
5202        if (numMatch == 0) {
5203            return;
5204        }
5205        PackageInfo pi;
5206        if (ps.pkg != null) {
5207            pi = generatePackageInfo(ps.pkg, flags, userId);
5208        } else {
5209            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5210        }
5211        // The above might return null in cases of uninstalled apps or install-state
5212        // skew across users/profiles.
5213        if (pi != null) {
5214            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5215                if (numMatch == permissions.length) {
5216                    pi.requestedPermissions = permissions;
5217                } else {
5218                    pi.requestedPermissions = new String[numMatch];
5219                    numMatch = 0;
5220                    for (int i=0; i<permissions.length; i++) {
5221                        if (tmp[i]) {
5222                            pi.requestedPermissions[numMatch] = permissions[i];
5223                            numMatch++;
5224                        }
5225                    }
5226                }
5227            }
5228            list.add(pi);
5229        }
5230    }
5231
5232    @Override
5233    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5234            String[] permissions, int flags, int userId) {
5235        if (!sUserManager.exists(userId)) return null;
5236        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5237
5238        // writer
5239        synchronized (mPackages) {
5240            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5241            boolean[] tmpBools = new boolean[permissions.length];
5242            if (listUninstalled) {
5243                for (PackageSetting ps : mSettings.mPackages.values()) {
5244                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5245                }
5246            } else {
5247                for (PackageParser.Package pkg : mPackages.values()) {
5248                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5249                    if (ps != null) {
5250                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5251                                userId);
5252                    }
5253                }
5254            }
5255
5256            return new ParceledListSlice<PackageInfo>(list);
5257        }
5258    }
5259
5260    @Override
5261    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5262        if (!sUserManager.exists(userId)) return null;
5263        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5264
5265        // writer
5266        synchronized (mPackages) {
5267            ArrayList<ApplicationInfo> list;
5268            if (listUninstalled) {
5269                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5270                for (PackageSetting ps : mSettings.mPackages.values()) {
5271                    ApplicationInfo ai;
5272                    if (ps.pkg != null) {
5273                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5274                                ps.readUserState(userId), userId);
5275                    } else {
5276                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5277                    }
5278                    if (ai != null) {
5279                        list.add(ai);
5280                    }
5281                }
5282            } else {
5283                list = new ArrayList<ApplicationInfo>(mPackages.size());
5284                for (PackageParser.Package p : mPackages.values()) {
5285                    if (p.mExtras != null) {
5286                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5287                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5288                        if (ai != null) {
5289                            list.add(ai);
5290                        }
5291                    }
5292                }
5293            }
5294
5295            return new ParceledListSlice<ApplicationInfo>(list);
5296        }
5297    }
5298
5299    public List<ApplicationInfo> getPersistentApplications(int flags) {
5300        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5301
5302        // reader
5303        synchronized (mPackages) {
5304            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5305            final int userId = UserHandle.getCallingUserId();
5306            while (i.hasNext()) {
5307                final PackageParser.Package p = i.next();
5308                if (p.applicationInfo != null
5309                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5310                        && (!mSafeMode || isSystemApp(p))) {
5311                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5312                    if (ps != null) {
5313                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5314                                ps.readUserState(userId), userId);
5315                        if (ai != null) {
5316                            finalList.add(ai);
5317                        }
5318                    }
5319                }
5320            }
5321        }
5322
5323        return finalList;
5324    }
5325
5326    @Override
5327    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5328        if (!sUserManager.exists(userId)) return null;
5329        // reader
5330        synchronized (mPackages) {
5331            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5332            PackageSetting ps = provider != null
5333                    ? mSettings.mPackages.get(provider.owner.packageName)
5334                    : null;
5335            return ps != null
5336                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5337                    && (!mSafeMode || (provider.info.applicationInfo.flags
5338                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5339                    ? PackageParser.generateProviderInfo(provider, flags,
5340                            ps.readUserState(userId), userId)
5341                    : null;
5342        }
5343    }
5344
5345    /**
5346     * @deprecated
5347     */
5348    @Deprecated
5349    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5350        // reader
5351        synchronized (mPackages) {
5352            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5353                    .entrySet().iterator();
5354            final int userId = UserHandle.getCallingUserId();
5355            while (i.hasNext()) {
5356                Map.Entry<String, PackageParser.Provider> entry = i.next();
5357                PackageParser.Provider p = entry.getValue();
5358                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5359
5360                if (ps != null && p.syncable
5361                        && (!mSafeMode || (p.info.applicationInfo.flags
5362                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5363                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5364                            ps.readUserState(userId), userId);
5365                    if (info != null) {
5366                        outNames.add(entry.getKey());
5367                        outInfo.add(info);
5368                    }
5369                }
5370            }
5371        }
5372    }
5373
5374    @Override
5375    public List<ProviderInfo> queryContentProviders(String processName,
5376            int uid, int flags) {
5377        ArrayList<ProviderInfo> finalList = null;
5378        // reader
5379        synchronized (mPackages) {
5380            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5381            final int userId = processName != null ?
5382                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5383            while (i.hasNext()) {
5384                final PackageParser.Provider p = i.next();
5385                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5386                if (ps != null && p.info.authority != null
5387                        && (processName == null
5388                                || (p.info.processName.equals(processName)
5389                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5390                        && mSettings.isEnabledLPr(p.info, flags, userId)
5391                        && (!mSafeMode
5392                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5393                    if (finalList == null) {
5394                        finalList = new ArrayList<ProviderInfo>(3);
5395                    }
5396                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5397                            ps.readUserState(userId), userId);
5398                    if (info != null) {
5399                        finalList.add(info);
5400                    }
5401                }
5402            }
5403        }
5404
5405        if (finalList != null) {
5406            Collections.sort(finalList, mProviderInitOrderSorter);
5407        }
5408
5409        return finalList;
5410    }
5411
5412    @Override
5413    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5414            int flags) {
5415        // reader
5416        synchronized (mPackages) {
5417            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5418            return PackageParser.generateInstrumentationInfo(i, flags);
5419        }
5420    }
5421
5422    @Override
5423    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5424            int flags) {
5425        ArrayList<InstrumentationInfo> finalList =
5426            new ArrayList<InstrumentationInfo>();
5427
5428        // reader
5429        synchronized (mPackages) {
5430            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5431            while (i.hasNext()) {
5432                final PackageParser.Instrumentation p = i.next();
5433                if (targetPackage == null
5434                        || targetPackage.equals(p.info.targetPackage)) {
5435                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5436                            flags);
5437                    if (ii != null) {
5438                        finalList.add(ii);
5439                    }
5440                }
5441            }
5442        }
5443
5444        return finalList;
5445    }
5446
5447    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5448        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5449        if (overlays == null) {
5450            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5451            return;
5452        }
5453        for (PackageParser.Package opkg : overlays.values()) {
5454            // Not much to do if idmap fails: we already logged the error
5455            // and we certainly don't want to abort installation of pkg simply
5456            // because an overlay didn't fit properly. For these reasons,
5457            // ignore the return value of createIdmapForPackagePairLI.
5458            createIdmapForPackagePairLI(pkg, opkg);
5459        }
5460    }
5461
5462    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5463            PackageParser.Package opkg) {
5464        if (!opkg.mTrustedOverlay) {
5465            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5466                    opkg.baseCodePath + ": overlay not trusted");
5467            return false;
5468        }
5469        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5470        if (overlaySet == null) {
5471            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5472                    opkg.baseCodePath + " but target package has no known overlays");
5473            return false;
5474        }
5475        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5476        // TODO: generate idmap for split APKs
5477        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5478            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5479                    + opkg.baseCodePath);
5480            return false;
5481        }
5482        PackageParser.Package[] overlayArray =
5483            overlaySet.values().toArray(new PackageParser.Package[0]);
5484        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5485            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5486                return p1.mOverlayPriority - p2.mOverlayPriority;
5487            }
5488        };
5489        Arrays.sort(overlayArray, cmp);
5490
5491        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5492        int i = 0;
5493        for (PackageParser.Package p : overlayArray) {
5494            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5495        }
5496        return true;
5497    }
5498
5499    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5500        final File[] files = dir.listFiles();
5501        if (ArrayUtils.isEmpty(files)) {
5502            Log.d(TAG, "No files in app dir " + dir);
5503            return;
5504        }
5505
5506        if (DEBUG_PACKAGE_SCANNING) {
5507            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5508                    + " flags=0x" + Integer.toHexString(parseFlags));
5509        }
5510
5511        for (File file : files) {
5512            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5513                    && !PackageInstallerService.isStageName(file.getName());
5514            if (!isPackage) {
5515                // Ignore entries which are not packages
5516                continue;
5517            }
5518            try {
5519                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5520                        scanFlags, currentTime, null);
5521            } catch (PackageManagerException e) {
5522                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5523
5524                // Delete invalid userdata apps
5525                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5526                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5527                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5528                    if (file.isDirectory()) {
5529                        mInstaller.rmPackageDir(file.getAbsolutePath());
5530                    } else {
5531                        file.delete();
5532                    }
5533                }
5534            }
5535        }
5536    }
5537
5538    private static File getSettingsProblemFile() {
5539        File dataDir = Environment.getDataDirectory();
5540        File systemDir = new File(dataDir, "system");
5541        File fname = new File(systemDir, "uiderrors.txt");
5542        return fname;
5543    }
5544
5545    static void reportSettingsProblem(int priority, String msg) {
5546        logCriticalInfo(priority, msg);
5547    }
5548
5549    static void logCriticalInfo(int priority, String msg) {
5550        Slog.println(priority, TAG, msg);
5551        EventLogTags.writePmCriticalInfo(msg);
5552        try {
5553            File fname = getSettingsProblemFile();
5554            FileOutputStream out = new FileOutputStream(fname, true);
5555            PrintWriter pw = new FastPrintWriter(out);
5556            SimpleDateFormat formatter = new SimpleDateFormat();
5557            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5558            pw.println(dateString + ": " + msg);
5559            pw.close();
5560            FileUtils.setPermissions(
5561                    fname.toString(),
5562                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5563                    -1, -1);
5564        } catch (java.io.IOException e) {
5565        }
5566    }
5567
5568    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5569            PackageParser.Package pkg, File srcFile, int parseFlags)
5570            throws PackageManagerException {
5571        if (ps != null
5572                && ps.codePath.equals(srcFile)
5573                && ps.timeStamp == srcFile.lastModified()
5574                && !isCompatSignatureUpdateNeeded(pkg)
5575                && !isRecoverSignatureUpdateNeeded(pkg)) {
5576            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5577            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5578            ArraySet<PublicKey> signingKs;
5579            synchronized (mPackages) {
5580                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5581            }
5582            if (ps.signatures.mSignatures != null
5583                    && ps.signatures.mSignatures.length != 0
5584                    && signingKs != null) {
5585                // Optimization: reuse the existing cached certificates
5586                // if the package appears to be unchanged.
5587                pkg.mSignatures = ps.signatures.mSignatures;
5588                pkg.mSigningKeys = signingKs;
5589                return;
5590            }
5591
5592            Slog.w(TAG, "PackageSetting for " + ps.name
5593                    + " is missing signatures.  Collecting certs again to recover them.");
5594        } else {
5595            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5596        }
5597
5598        try {
5599            pp.collectCertificates(pkg, parseFlags);
5600            pp.collectManifestDigest(pkg);
5601        } catch (PackageParserException e) {
5602            throw PackageManagerException.from(e);
5603        }
5604    }
5605
5606    /*
5607     *  Scan a package and return the newly parsed package.
5608     *  Returns null in case of errors and the error code is stored in mLastScanError
5609     */
5610    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5611            long currentTime, UserHandle user) throws PackageManagerException {
5612        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5613        parseFlags |= mDefParseFlags;
5614        PackageParser pp = new PackageParser();
5615        pp.setSeparateProcesses(mSeparateProcesses);
5616        pp.setOnlyCoreApps(mOnlyCore);
5617        pp.setDisplayMetrics(mMetrics);
5618
5619        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5620            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5621        }
5622
5623        final PackageParser.Package pkg;
5624        try {
5625            pkg = pp.parsePackage(scanFile, parseFlags);
5626        } catch (PackageParserException e) {
5627            throw PackageManagerException.from(e);
5628        }
5629
5630        PackageSetting ps = null;
5631        PackageSetting updatedPkg;
5632        // reader
5633        synchronized (mPackages) {
5634            // Look to see if we already know about this package.
5635            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5636            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5637                // This package has been renamed to its original name.  Let's
5638                // use that.
5639                ps = mSettings.peekPackageLPr(oldName);
5640            }
5641            // If there was no original package, see one for the real package name.
5642            if (ps == null) {
5643                ps = mSettings.peekPackageLPr(pkg.packageName);
5644            }
5645            // Check to see if this package could be hiding/updating a system
5646            // package.  Must look for it either under the original or real
5647            // package name depending on our state.
5648            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5649            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5650        }
5651        boolean updatedPkgBetter = false;
5652        // First check if this is a system package that may involve an update
5653        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5654            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5655            // it needs to drop FLAG_PRIVILEGED.
5656            if (locationIsPrivileged(scanFile)) {
5657                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5658            } else {
5659                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5660            }
5661
5662            if (ps != null && !ps.codePath.equals(scanFile)) {
5663                // The path has changed from what was last scanned...  check the
5664                // version of the new path against what we have stored to determine
5665                // what to do.
5666                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5667                if (pkg.mVersionCode <= ps.versionCode) {
5668                    // The system package has been updated and the code path does not match
5669                    // Ignore entry. Skip it.
5670                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5671                            + " ignored: updated version " + ps.versionCode
5672                            + " better than this " + pkg.mVersionCode);
5673                    if (!updatedPkg.codePath.equals(scanFile)) {
5674                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5675                                + ps.name + " changing from " + updatedPkg.codePathString
5676                                + " to " + scanFile);
5677                        updatedPkg.codePath = scanFile;
5678                        updatedPkg.codePathString = scanFile.toString();
5679                        updatedPkg.resourcePath = scanFile;
5680                        updatedPkg.resourcePathString = scanFile.toString();
5681                    }
5682                    updatedPkg.pkg = pkg;
5683                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5684                            "Package " + ps.name + " at " + scanFile
5685                                    + " ignored: updated version " + ps.versionCode
5686                                    + " better than this " + pkg.mVersionCode);
5687                } else {
5688                    // The current app on the system partition is better than
5689                    // what we have updated to on the data partition; switch
5690                    // back to the system partition version.
5691                    // At this point, its safely assumed that package installation for
5692                    // apps in system partition will go through. If not there won't be a working
5693                    // version of the app
5694                    // writer
5695                    synchronized (mPackages) {
5696                        // Just remove the loaded entries from package lists.
5697                        mPackages.remove(ps.name);
5698                    }
5699
5700                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5701                            + " reverting from " + ps.codePathString
5702                            + ": new version " + pkg.mVersionCode
5703                            + " better than installed " + ps.versionCode);
5704
5705                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5706                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5707                    synchronized (mInstallLock) {
5708                        args.cleanUpResourcesLI();
5709                    }
5710                    synchronized (mPackages) {
5711                        mSettings.enableSystemPackageLPw(ps.name);
5712                    }
5713                    updatedPkgBetter = true;
5714                }
5715            }
5716        }
5717
5718        if (updatedPkg != null) {
5719            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5720            // initially
5721            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5722
5723            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5724            // flag set initially
5725            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5726                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5727            }
5728        }
5729
5730        // Verify certificates against what was last scanned
5731        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5732
5733        /*
5734         * A new system app appeared, but we already had a non-system one of the
5735         * same name installed earlier.
5736         */
5737        boolean shouldHideSystemApp = false;
5738        if (updatedPkg == null && ps != null
5739                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5740            /*
5741             * Check to make sure the signatures match first. If they don't,
5742             * wipe the installed application and its data.
5743             */
5744            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5745                    != PackageManager.SIGNATURE_MATCH) {
5746                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5747                        + " signatures don't match existing userdata copy; removing");
5748                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5749                ps = null;
5750            } else {
5751                /*
5752                 * If the newly-added system app is an older version than the
5753                 * already installed version, hide it. It will be scanned later
5754                 * and re-added like an update.
5755                 */
5756                if (pkg.mVersionCode <= ps.versionCode) {
5757                    shouldHideSystemApp = true;
5758                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5759                            + " but new version " + pkg.mVersionCode + " better than installed "
5760                            + ps.versionCode + "; hiding system");
5761                } else {
5762                    /*
5763                     * The newly found system app is a newer version that the
5764                     * one previously installed. Simply remove the
5765                     * already-installed application and replace it with our own
5766                     * while keeping the application data.
5767                     */
5768                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5769                            + " reverting from " + ps.codePathString + ": new version "
5770                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5771                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5772                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5773                    synchronized (mInstallLock) {
5774                        args.cleanUpResourcesLI();
5775                    }
5776                }
5777            }
5778        }
5779
5780        // The apk is forward locked (not public) if its code and resources
5781        // are kept in different files. (except for app in either system or
5782        // vendor path).
5783        // TODO grab this value from PackageSettings
5784        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5785            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5786                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5787            }
5788        }
5789
5790        // TODO: extend to support forward-locked splits
5791        String resourcePath = null;
5792        String baseResourcePath = null;
5793        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5794            if (ps != null && ps.resourcePathString != null) {
5795                resourcePath = ps.resourcePathString;
5796                baseResourcePath = ps.resourcePathString;
5797            } else {
5798                // Should not happen at all. Just log an error.
5799                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5800            }
5801        } else {
5802            resourcePath = pkg.codePath;
5803            baseResourcePath = pkg.baseCodePath;
5804        }
5805
5806        // Set application objects path explicitly.
5807        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5808        pkg.applicationInfo.setCodePath(pkg.codePath);
5809        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5810        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5811        pkg.applicationInfo.setResourcePath(resourcePath);
5812        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5813        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5814
5815        // Note that we invoke the following method only if we are about to unpack an application
5816        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5817                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5818
5819        /*
5820         * If the system app should be overridden by a previously installed
5821         * data, hide the system app now and let the /data/app scan pick it up
5822         * again.
5823         */
5824        if (shouldHideSystemApp) {
5825            synchronized (mPackages) {
5826                /*
5827                 * We have to grant systems permissions before we hide, because
5828                 * grantPermissions will assume the package update is trying to
5829                 * expand its permissions.
5830                 */
5831                grantPermissionsLPw(pkg, true, pkg.packageName);
5832                mSettings.disableSystemPackageLPw(pkg.packageName);
5833            }
5834        }
5835
5836        return scannedPkg;
5837    }
5838
5839    private static String fixProcessName(String defProcessName,
5840            String processName, int uid) {
5841        if (processName == null) {
5842            return defProcessName;
5843        }
5844        return processName;
5845    }
5846
5847    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5848            throws PackageManagerException {
5849        if (pkgSetting.signatures.mSignatures != null) {
5850            // Already existing package. Make sure signatures match
5851            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5852                    == PackageManager.SIGNATURE_MATCH;
5853            if (!match) {
5854                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5855                        == PackageManager.SIGNATURE_MATCH;
5856            }
5857            if (!match) {
5858                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5859                        == PackageManager.SIGNATURE_MATCH;
5860            }
5861            if (!match) {
5862                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5863                        + pkg.packageName + " signatures do not match the "
5864                        + "previously installed version; ignoring!");
5865            }
5866        }
5867
5868        // Check for shared user signatures
5869        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5870            // Already existing package. Make sure signatures match
5871            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5872                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5873            if (!match) {
5874                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5875                        == PackageManager.SIGNATURE_MATCH;
5876            }
5877            if (!match) {
5878                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5879                        == PackageManager.SIGNATURE_MATCH;
5880            }
5881            if (!match) {
5882                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5883                        "Package " + pkg.packageName
5884                        + " has no signatures that match those in shared user "
5885                        + pkgSetting.sharedUser.name + "; ignoring!");
5886            }
5887        }
5888    }
5889
5890    /**
5891     * Enforces that only the system UID or root's UID can call a method exposed
5892     * via Binder.
5893     *
5894     * @param message used as message if SecurityException is thrown
5895     * @throws SecurityException if the caller is not system or root
5896     */
5897    private static final void enforceSystemOrRoot(String message) {
5898        final int uid = Binder.getCallingUid();
5899        if (uid != Process.SYSTEM_UID && uid != 0) {
5900            throw new SecurityException(message);
5901        }
5902    }
5903
5904    @Override
5905    public void performBootDexOpt() {
5906        enforceSystemOrRoot("Only the system can request dexopt be performed");
5907
5908        // Before everything else, see whether we need to fstrim.
5909        try {
5910            IMountService ms = PackageHelper.getMountService();
5911            if (ms != null) {
5912                final boolean isUpgrade = isUpgrade();
5913                boolean doTrim = isUpgrade;
5914                if (doTrim) {
5915                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5916                } else {
5917                    final long interval = android.provider.Settings.Global.getLong(
5918                            mContext.getContentResolver(),
5919                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5920                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5921                    if (interval > 0) {
5922                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5923                        if (timeSinceLast > interval) {
5924                            doTrim = true;
5925                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5926                                    + "; running immediately");
5927                        }
5928                    }
5929                }
5930                if (doTrim) {
5931                    if (!isFirstBoot()) {
5932                        try {
5933                            ActivityManagerNative.getDefault().showBootMessage(
5934                                    mContext.getResources().getString(
5935                                            R.string.android_upgrading_fstrim), true);
5936                        } catch (RemoteException e) {
5937                        }
5938                    }
5939                    ms.runMaintenance();
5940                }
5941            } else {
5942                Slog.e(TAG, "Mount service unavailable!");
5943            }
5944        } catch (RemoteException e) {
5945            // Can't happen; MountService is local
5946        }
5947
5948        final ArraySet<PackageParser.Package> pkgs;
5949        synchronized (mPackages) {
5950            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5951        }
5952
5953        if (pkgs != null) {
5954            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5955            // in case the device runs out of space.
5956            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5957            // Give priority to core apps.
5958            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5959                PackageParser.Package pkg = it.next();
5960                if (pkg.coreApp) {
5961                    if (DEBUG_DEXOPT) {
5962                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5963                    }
5964                    sortedPkgs.add(pkg);
5965                    it.remove();
5966                }
5967            }
5968            // Give priority to system apps that listen for pre boot complete.
5969            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5970            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5971            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5972                PackageParser.Package pkg = it.next();
5973                if (pkgNames.contains(pkg.packageName)) {
5974                    if (DEBUG_DEXOPT) {
5975                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5976                    }
5977                    sortedPkgs.add(pkg);
5978                    it.remove();
5979                }
5980            }
5981            // Give priority to system apps.
5982            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5983                PackageParser.Package pkg = it.next();
5984                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5985                    if (DEBUG_DEXOPT) {
5986                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5987                    }
5988                    sortedPkgs.add(pkg);
5989                    it.remove();
5990                }
5991            }
5992            // Give priority to updated system apps.
5993            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5994                PackageParser.Package pkg = it.next();
5995                if (pkg.isUpdatedSystemApp()) {
5996                    if (DEBUG_DEXOPT) {
5997                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5998                    }
5999                    sortedPkgs.add(pkg);
6000                    it.remove();
6001                }
6002            }
6003            // Give priority to apps that listen for boot complete.
6004            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6005            pkgNames = getPackageNamesForIntent(intent);
6006            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6007                PackageParser.Package pkg = it.next();
6008                if (pkgNames.contains(pkg.packageName)) {
6009                    if (DEBUG_DEXOPT) {
6010                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6011                    }
6012                    sortedPkgs.add(pkg);
6013                    it.remove();
6014                }
6015            }
6016            // Filter out packages that aren't recently used.
6017            filterRecentlyUsedApps(pkgs);
6018            // Add all remaining apps.
6019            for (PackageParser.Package pkg : pkgs) {
6020                if (DEBUG_DEXOPT) {
6021                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6022                }
6023                sortedPkgs.add(pkg);
6024            }
6025
6026            // If we want to be lazy, filter everything that wasn't recently used.
6027            if (mLazyDexOpt) {
6028                filterRecentlyUsedApps(sortedPkgs);
6029            }
6030
6031            int i = 0;
6032            int total = sortedPkgs.size();
6033            File dataDir = Environment.getDataDirectory();
6034            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6035            if (lowThreshold == 0) {
6036                throw new IllegalStateException("Invalid low memory threshold");
6037            }
6038            for (PackageParser.Package pkg : sortedPkgs) {
6039                long usableSpace = dataDir.getUsableSpace();
6040                if (usableSpace < lowThreshold) {
6041                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6042                    break;
6043                }
6044                performBootDexOpt(pkg, ++i, total);
6045            }
6046        }
6047    }
6048
6049    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6050        // Filter out packages that aren't recently used.
6051        //
6052        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6053        // should do a full dexopt.
6054        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6055            int total = pkgs.size();
6056            int skipped = 0;
6057            long now = System.currentTimeMillis();
6058            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6059                PackageParser.Package pkg = i.next();
6060                long then = pkg.mLastPackageUsageTimeInMills;
6061                if (then + mDexOptLRUThresholdInMills < now) {
6062                    if (DEBUG_DEXOPT) {
6063                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6064                              ((then == 0) ? "never" : new Date(then)));
6065                    }
6066                    i.remove();
6067                    skipped++;
6068                }
6069            }
6070            if (DEBUG_DEXOPT) {
6071                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6072            }
6073        }
6074    }
6075
6076    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6077        List<ResolveInfo> ris = null;
6078        try {
6079            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6080                    intent, null, 0, UserHandle.USER_OWNER);
6081        } catch (RemoteException e) {
6082        }
6083        ArraySet<String> pkgNames = new ArraySet<String>();
6084        if (ris != null) {
6085            for (ResolveInfo ri : ris) {
6086                pkgNames.add(ri.activityInfo.packageName);
6087            }
6088        }
6089        return pkgNames;
6090    }
6091
6092    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6093        if (DEBUG_DEXOPT) {
6094            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6095        }
6096        if (!isFirstBoot()) {
6097            try {
6098                ActivityManagerNative.getDefault().showBootMessage(
6099                        mContext.getResources().getString(R.string.android_upgrading_apk,
6100                                curr, total), true);
6101            } catch (RemoteException e) {
6102            }
6103        }
6104        PackageParser.Package p = pkg;
6105        synchronized (mInstallLock) {
6106            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6107                    false /* force dex */, false /* defer */, true /* include dependencies */);
6108        }
6109    }
6110
6111    @Override
6112    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6113        return performDexOpt(packageName, instructionSet, false);
6114    }
6115
6116    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6117        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6118        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6119        if (!dexopt && !updateUsage) {
6120            // We aren't going to dexopt or update usage, so bail early.
6121            return false;
6122        }
6123        PackageParser.Package p;
6124        final String targetInstructionSet;
6125        synchronized (mPackages) {
6126            p = mPackages.get(packageName);
6127            if (p == null) {
6128                return false;
6129            }
6130            if (updateUsage) {
6131                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6132            }
6133            mPackageUsage.write(false);
6134            if (!dexopt) {
6135                // We aren't going to dexopt, so bail early.
6136                return false;
6137            }
6138
6139            targetInstructionSet = instructionSet != null ? instructionSet :
6140                    getPrimaryInstructionSet(p.applicationInfo);
6141            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6142                return false;
6143            }
6144        }
6145
6146        synchronized (mInstallLock) {
6147            final String[] instructionSets = new String[] { targetInstructionSet };
6148            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6149                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6150            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6151        }
6152    }
6153
6154    public ArraySet<String> getPackagesThatNeedDexOpt() {
6155        ArraySet<String> pkgs = null;
6156        synchronized (mPackages) {
6157            for (PackageParser.Package p : mPackages.values()) {
6158                if (DEBUG_DEXOPT) {
6159                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6160                }
6161                if (!p.mDexOptPerformed.isEmpty()) {
6162                    continue;
6163                }
6164                if (pkgs == null) {
6165                    pkgs = new ArraySet<String>();
6166                }
6167                pkgs.add(p.packageName);
6168            }
6169        }
6170        return pkgs;
6171    }
6172
6173    public void shutdown() {
6174        mPackageUsage.write(true);
6175    }
6176
6177    @Override
6178    public void forceDexOpt(String packageName) {
6179        enforceSystemOrRoot("forceDexOpt");
6180
6181        PackageParser.Package pkg;
6182        synchronized (mPackages) {
6183            pkg = mPackages.get(packageName);
6184            if (pkg == null) {
6185                throw new IllegalArgumentException("Missing package: " + packageName);
6186            }
6187        }
6188
6189        synchronized (mInstallLock) {
6190            final String[] instructionSets = new String[] {
6191                    getPrimaryInstructionSet(pkg.applicationInfo) };
6192            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6193                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6194            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6195                throw new IllegalStateException("Failed to dexopt: " + res);
6196            }
6197        }
6198    }
6199
6200    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6201        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6202            Slog.w(TAG, "Unable to update from " + oldPkg.name
6203                    + " to " + newPkg.packageName
6204                    + ": old package not in system partition");
6205            return false;
6206        } else if (mPackages.get(oldPkg.name) != null) {
6207            Slog.w(TAG, "Unable to update from " + oldPkg.name
6208                    + " to " + newPkg.packageName
6209                    + ": old package still exists");
6210            return false;
6211        }
6212        return true;
6213    }
6214
6215    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6216        int[] users = sUserManager.getUserIds();
6217        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6218        if (res < 0) {
6219            return res;
6220        }
6221        for (int user : users) {
6222            if (user != 0) {
6223                res = mInstaller.createUserData(volumeUuid, packageName,
6224                        UserHandle.getUid(user, uid), user, seinfo);
6225                if (res < 0) {
6226                    return res;
6227                }
6228            }
6229        }
6230        return res;
6231    }
6232
6233    private int removeDataDirsLI(String volumeUuid, String packageName) {
6234        int[] users = sUserManager.getUserIds();
6235        int res = 0;
6236        for (int user : users) {
6237            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6238            if (resInner < 0) {
6239                res = resInner;
6240            }
6241        }
6242
6243        return res;
6244    }
6245
6246    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6247        int[] users = sUserManager.getUserIds();
6248        int res = 0;
6249        for (int user : users) {
6250            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6251            if (resInner < 0) {
6252                res = resInner;
6253            }
6254        }
6255        return res;
6256    }
6257
6258    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6259            PackageParser.Package changingLib) {
6260        if (file.path != null) {
6261            usesLibraryFiles.add(file.path);
6262            return;
6263        }
6264        PackageParser.Package p = mPackages.get(file.apk);
6265        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6266            // If we are doing this while in the middle of updating a library apk,
6267            // then we need to make sure to use that new apk for determining the
6268            // dependencies here.  (We haven't yet finished committing the new apk
6269            // to the package manager state.)
6270            if (p == null || p.packageName.equals(changingLib.packageName)) {
6271                p = changingLib;
6272            }
6273        }
6274        if (p != null) {
6275            usesLibraryFiles.addAll(p.getAllCodePaths());
6276        }
6277    }
6278
6279    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6280            PackageParser.Package changingLib) throws PackageManagerException {
6281        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6282            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6283            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6284            for (int i=0; i<N; i++) {
6285                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6286                if (file == null) {
6287                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6288                            "Package " + pkg.packageName + " requires unavailable shared library "
6289                            + pkg.usesLibraries.get(i) + "; failing!");
6290                }
6291                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6292            }
6293            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6294            for (int i=0; i<N; i++) {
6295                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6296                if (file == null) {
6297                    Slog.w(TAG, "Package " + pkg.packageName
6298                            + " desires unavailable shared library "
6299                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6300                } else {
6301                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6302                }
6303            }
6304            N = usesLibraryFiles.size();
6305            if (N > 0) {
6306                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6307            } else {
6308                pkg.usesLibraryFiles = null;
6309            }
6310        }
6311    }
6312
6313    private static boolean hasString(List<String> list, List<String> which) {
6314        if (list == null) {
6315            return false;
6316        }
6317        for (int i=list.size()-1; i>=0; i--) {
6318            for (int j=which.size()-1; j>=0; j--) {
6319                if (which.get(j).equals(list.get(i))) {
6320                    return true;
6321                }
6322            }
6323        }
6324        return false;
6325    }
6326
6327    private void updateAllSharedLibrariesLPw() {
6328        for (PackageParser.Package pkg : mPackages.values()) {
6329            try {
6330                updateSharedLibrariesLPw(pkg, null);
6331            } catch (PackageManagerException e) {
6332                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6333            }
6334        }
6335    }
6336
6337    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6338            PackageParser.Package changingPkg) {
6339        ArrayList<PackageParser.Package> res = null;
6340        for (PackageParser.Package pkg : mPackages.values()) {
6341            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6342                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6343                if (res == null) {
6344                    res = new ArrayList<PackageParser.Package>();
6345                }
6346                res.add(pkg);
6347                try {
6348                    updateSharedLibrariesLPw(pkg, changingPkg);
6349                } catch (PackageManagerException e) {
6350                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6351                }
6352            }
6353        }
6354        return res;
6355    }
6356
6357    /**
6358     * Derive the value of the {@code cpuAbiOverride} based on the provided
6359     * value and an optional stored value from the package settings.
6360     */
6361    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6362        String cpuAbiOverride = null;
6363
6364        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6365            cpuAbiOverride = null;
6366        } else if (abiOverride != null) {
6367            cpuAbiOverride = abiOverride;
6368        } else if (settings != null) {
6369            cpuAbiOverride = settings.cpuAbiOverrideString;
6370        }
6371
6372        return cpuAbiOverride;
6373    }
6374
6375    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6376            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6377        boolean success = false;
6378        try {
6379            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6380                    currentTime, user);
6381            success = true;
6382            return res;
6383        } finally {
6384            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6385                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6386            }
6387        }
6388    }
6389
6390    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6391            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6392        final File scanFile = new File(pkg.codePath);
6393        if (pkg.applicationInfo.getCodePath() == null ||
6394                pkg.applicationInfo.getResourcePath() == null) {
6395            // Bail out. The resource and code paths haven't been set.
6396            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6397                    "Code and resource paths haven't been set correctly");
6398        }
6399
6400        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6401            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6402        } else {
6403            // Only allow system apps to be flagged as core apps.
6404            pkg.coreApp = false;
6405        }
6406
6407        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6408            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6409        }
6410
6411        if (mCustomResolverComponentName != null &&
6412                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6413            setUpCustomResolverActivity(pkg);
6414        }
6415
6416        if (pkg.packageName.equals("android")) {
6417            synchronized (mPackages) {
6418                if (mAndroidApplication != null) {
6419                    Slog.w(TAG, "*************************************************");
6420                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6421                    Slog.w(TAG, " file=" + scanFile);
6422                    Slog.w(TAG, "*************************************************");
6423                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6424                            "Core android package being redefined.  Skipping.");
6425                }
6426
6427                // Set up information for our fall-back user intent resolution activity.
6428                mPlatformPackage = pkg;
6429                pkg.mVersionCode = mSdkVersion;
6430                mAndroidApplication = pkg.applicationInfo;
6431
6432                if (!mResolverReplaced) {
6433                    mResolveActivity.applicationInfo = mAndroidApplication;
6434                    mResolveActivity.name = ResolverActivity.class.getName();
6435                    mResolveActivity.packageName = mAndroidApplication.packageName;
6436                    mResolveActivity.processName = "system:ui";
6437                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6438                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6439                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6440                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6441                    mResolveActivity.exported = true;
6442                    mResolveActivity.enabled = true;
6443                    mResolveInfo.activityInfo = mResolveActivity;
6444                    mResolveInfo.priority = 0;
6445                    mResolveInfo.preferredOrder = 0;
6446                    mResolveInfo.match = 0;
6447                    mResolveComponentName = new ComponentName(
6448                            mAndroidApplication.packageName, mResolveActivity.name);
6449                }
6450            }
6451        }
6452
6453        if (DEBUG_PACKAGE_SCANNING) {
6454            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6455                Log.d(TAG, "Scanning package " + pkg.packageName);
6456        }
6457
6458        if (mPackages.containsKey(pkg.packageName)
6459                || mSharedLibraries.containsKey(pkg.packageName)) {
6460            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6461                    "Application package " + pkg.packageName
6462                    + " already installed.  Skipping duplicate.");
6463        }
6464
6465        // If we're only installing presumed-existing packages, require that the
6466        // scanned APK is both already known and at the path previously established
6467        // for it.  Previously unknown packages we pick up normally, but if we have an
6468        // a priori expectation about this package's install presence, enforce it.
6469        // With a singular exception for new system packages. When an OTA contains
6470        // a new system package, we allow the codepath to change from a system location
6471        // to the user-installed location. If we don't allow this change, any newer,
6472        // user-installed version of the application will be ignored.
6473        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6474            if (mExpectingBetter.containsKey(pkg.packageName)) {
6475                logCriticalInfo(Log.WARN,
6476                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6477            } else {
6478                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6479                if (known != null) {
6480                    if (DEBUG_PACKAGE_SCANNING) {
6481                        Log.d(TAG, "Examining " + pkg.codePath
6482                                + " and requiring known paths " + known.codePathString
6483                                + " & " + known.resourcePathString);
6484                    }
6485                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6486                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6487                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6488                                "Application package " + pkg.packageName
6489                                + " found at " + pkg.applicationInfo.getCodePath()
6490                                + " but expected at " + known.codePathString + "; ignoring.");
6491                    }
6492                }
6493            }
6494        }
6495
6496        // Initialize package source and resource directories
6497        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6498        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6499
6500        SharedUserSetting suid = null;
6501        PackageSetting pkgSetting = null;
6502
6503        if (!isSystemApp(pkg)) {
6504            // Only system apps can use these features.
6505            pkg.mOriginalPackages = null;
6506            pkg.mRealPackage = null;
6507            pkg.mAdoptPermissions = null;
6508        }
6509
6510        // writer
6511        synchronized (mPackages) {
6512            if (pkg.mSharedUserId != null) {
6513                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6514                if (suid == null) {
6515                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6516                            "Creating application package " + pkg.packageName
6517                            + " for shared user failed");
6518                }
6519                if (DEBUG_PACKAGE_SCANNING) {
6520                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6521                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6522                                + "): packages=" + suid.packages);
6523                }
6524            }
6525
6526            // Check if we are renaming from an original package name.
6527            PackageSetting origPackage = null;
6528            String realName = null;
6529            if (pkg.mOriginalPackages != null) {
6530                // This package may need to be renamed to a previously
6531                // installed name.  Let's check on that...
6532                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6533                if (pkg.mOriginalPackages.contains(renamed)) {
6534                    // This package had originally been installed as the
6535                    // original name, and we have already taken care of
6536                    // transitioning to the new one.  Just update the new
6537                    // one to continue using the old name.
6538                    realName = pkg.mRealPackage;
6539                    if (!pkg.packageName.equals(renamed)) {
6540                        // Callers into this function may have already taken
6541                        // care of renaming the package; only do it here if
6542                        // it is not already done.
6543                        pkg.setPackageName(renamed);
6544                    }
6545
6546                } else {
6547                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6548                        if ((origPackage = mSettings.peekPackageLPr(
6549                                pkg.mOriginalPackages.get(i))) != null) {
6550                            // We do have the package already installed under its
6551                            // original name...  should we use it?
6552                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6553                                // New package is not compatible with original.
6554                                origPackage = null;
6555                                continue;
6556                            } else if (origPackage.sharedUser != null) {
6557                                // Make sure uid is compatible between packages.
6558                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6559                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6560                                            + " to " + pkg.packageName + ": old uid "
6561                                            + origPackage.sharedUser.name
6562                                            + " differs from " + pkg.mSharedUserId);
6563                                    origPackage = null;
6564                                    continue;
6565                                }
6566                            } else {
6567                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6568                                        + pkg.packageName + " to old name " + origPackage.name);
6569                            }
6570                            break;
6571                        }
6572                    }
6573                }
6574            }
6575
6576            if (mTransferedPackages.contains(pkg.packageName)) {
6577                Slog.w(TAG, "Package " + pkg.packageName
6578                        + " was transferred to another, but its .apk remains");
6579            }
6580
6581            // Just create the setting, don't add it yet. For already existing packages
6582            // the PkgSetting exists already and doesn't have to be created.
6583            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6584                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6585                    pkg.applicationInfo.primaryCpuAbi,
6586                    pkg.applicationInfo.secondaryCpuAbi,
6587                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6588                    user, false);
6589            if (pkgSetting == null) {
6590                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6591                        "Creating application package " + pkg.packageName + " failed");
6592            }
6593
6594            if (pkgSetting.origPackage != null) {
6595                // If we are first transitioning from an original package,
6596                // fix up the new package's name now.  We need to do this after
6597                // looking up the package under its new name, so getPackageLP
6598                // can take care of fiddling things correctly.
6599                pkg.setPackageName(origPackage.name);
6600
6601                // File a report about this.
6602                String msg = "New package " + pkgSetting.realName
6603                        + " renamed to replace old package " + pkgSetting.name;
6604                reportSettingsProblem(Log.WARN, msg);
6605
6606                // Make a note of it.
6607                mTransferedPackages.add(origPackage.name);
6608
6609                // No longer need to retain this.
6610                pkgSetting.origPackage = null;
6611            }
6612
6613            if (realName != null) {
6614                // Make a note of it.
6615                mTransferedPackages.add(pkg.packageName);
6616            }
6617
6618            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6619                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6620            }
6621
6622            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6623                // Check all shared libraries and map to their actual file path.
6624                // We only do this here for apps not on a system dir, because those
6625                // are the only ones that can fail an install due to this.  We
6626                // will take care of the system apps by updating all of their
6627                // library paths after the scan is done.
6628                updateSharedLibrariesLPw(pkg, null);
6629            }
6630
6631            if (mFoundPolicyFile) {
6632                SELinuxMMAC.assignSeinfoValue(pkg);
6633            }
6634
6635            pkg.applicationInfo.uid = pkgSetting.appId;
6636            pkg.mExtras = pkgSetting;
6637            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6638                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6639                    // We just determined the app is signed correctly, so bring
6640                    // over the latest parsed certs.
6641                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6642                } else {
6643                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6644                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6645                                "Package " + pkg.packageName + " upgrade keys do not match the "
6646                                + "previously installed version");
6647                    } else {
6648                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6649                        String msg = "System package " + pkg.packageName
6650                            + " signature changed; retaining data.";
6651                        reportSettingsProblem(Log.WARN, msg);
6652                    }
6653                }
6654            } else {
6655                try {
6656                    verifySignaturesLP(pkgSetting, pkg);
6657                    // We just determined the app is signed correctly, so bring
6658                    // over the latest parsed certs.
6659                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6660                } catch (PackageManagerException e) {
6661                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6662                        throw e;
6663                    }
6664                    // The signature has changed, but this package is in the system
6665                    // image...  let's recover!
6666                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6667                    // However...  if this package is part of a shared user, but it
6668                    // doesn't match the signature of the shared user, let's fail.
6669                    // What this means is that you can't change the signatures
6670                    // associated with an overall shared user, which doesn't seem all
6671                    // that unreasonable.
6672                    if (pkgSetting.sharedUser != null) {
6673                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6674                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6675                            throw new PackageManagerException(
6676                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6677                                            "Signature mismatch for shared user : "
6678                                            + pkgSetting.sharedUser);
6679                        }
6680                    }
6681                    // File a report about this.
6682                    String msg = "System package " + pkg.packageName
6683                        + " signature changed; retaining data.";
6684                    reportSettingsProblem(Log.WARN, msg);
6685                }
6686            }
6687            // Verify that this new package doesn't have any content providers
6688            // that conflict with existing packages.  Only do this if the
6689            // package isn't already installed, since we don't want to break
6690            // things that are installed.
6691            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6692                final int N = pkg.providers.size();
6693                int i;
6694                for (i=0; i<N; i++) {
6695                    PackageParser.Provider p = pkg.providers.get(i);
6696                    if (p.info.authority != null) {
6697                        String names[] = p.info.authority.split(";");
6698                        for (int j = 0; j < names.length; j++) {
6699                            if (mProvidersByAuthority.containsKey(names[j])) {
6700                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6701                                final String otherPackageName =
6702                                        ((other != null && other.getComponentName() != null) ?
6703                                                other.getComponentName().getPackageName() : "?");
6704                                throw new PackageManagerException(
6705                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6706                                                "Can't install because provider name " + names[j]
6707                                                + " (in package " + pkg.applicationInfo.packageName
6708                                                + ") is already used by " + otherPackageName);
6709                            }
6710                        }
6711                    }
6712                }
6713            }
6714
6715            if (pkg.mAdoptPermissions != null) {
6716                // This package wants to adopt ownership of permissions from
6717                // another package.
6718                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6719                    final String origName = pkg.mAdoptPermissions.get(i);
6720                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6721                    if (orig != null) {
6722                        if (verifyPackageUpdateLPr(orig, pkg)) {
6723                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6724                                    + pkg.packageName);
6725                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6726                        }
6727                    }
6728                }
6729            }
6730        }
6731
6732        final String pkgName = pkg.packageName;
6733
6734        final long scanFileTime = scanFile.lastModified();
6735        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6736        pkg.applicationInfo.processName = fixProcessName(
6737                pkg.applicationInfo.packageName,
6738                pkg.applicationInfo.processName,
6739                pkg.applicationInfo.uid);
6740
6741        File dataPath;
6742        if (mPlatformPackage == pkg) {
6743            // The system package is special.
6744            dataPath = new File(Environment.getDataDirectory(), "system");
6745
6746            pkg.applicationInfo.dataDir = dataPath.getPath();
6747
6748        } else {
6749            // This is a normal package, need to make its data directory.
6750            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6751                    UserHandle.USER_OWNER, pkg.packageName);
6752
6753            boolean uidError = false;
6754            if (dataPath.exists()) {
6755                int currentUid = 0;
6756                try {
6757                    StructStat stat = Os.stat(dataPath.getPath());
6758                    currentUid = stat.st_uid;
6759                } catch (ErrnoException e) {
6760                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6761                }
6762
6763                // If we have mismatched owners for the data path, we have a problem.
6764                if (currentUid != pkg.applicationInfo.uid) {
6765                    boolean recovered = false;
6766                    if (currentUid == 0) {
6767                        // The directory somehow became owned by root.  Wow.
6768                        // This is probably because the system was stopped while
6769                        // installd was in the middle of messing with its libs
6770                        // directory.  Ask installd to fix that.
6771                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6772                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6773                        if (ret >= 0) {
6774                            recovered = true;
6775                            String msg = "Package " + pkg.packageName
6776                                    + " unexpectedly changed to uid 0; recovered to " +
6777                                    + pkg.applicationInfo.uid;
6778                            reportSettingsProblem(Log.WARN, msg);
6779                        }
6780                    }
6781                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6782                            || (scanFlags&SCAN_BOOTING) != 0)) {
6783                        // If this is a system app, we can at least delete its
6784                        // current data so the application will still work.
6785                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6786                        if (ret >= 0) {
6787                            // TODO: Kill the processes first
6788                            // Old data gone!
6789                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6790                                    ? "System package " : "Third party package ";
6791                            String msg = prefix + pkg.packageName
6792                                    + " has changed from uid: "
6793                                    + currentUid + " to "
6794                                    + pkg.applicationInfo.uid + "; old data erased";
6795                            reportSettingsProblem(Log.WARN, msg);
6796                            recovered = true;
6797
6798                            // And now re-install the app.
6799                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6800                                    pkg.applicationInfo.seinfo);
6801                            if (ret == -1) {
6802                                // Ack should not happen!
6803                                msg = prefix + pkg.packageName
6804                                        + " could not have data directory re-created after delete.";
6805                                reportSettingsProblem(Log.WARN, msg);
6806                                throw new PackageManagerException(
6807                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6808                            }
6809                        }
6810                        if (!recovered) {
6811                            mHasSystemUidErrors = true;
6812                        }
6813                    } else if (!recovered) {
6814                        // If we allow this install to proceed, we will be broken.
6815                        // Abort, abort!
6816                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6817                                "scanPackageLI");
6818                    }
6819                    if (!recovered) {
6820                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6821                            + pkg.applicationInfo.uid + "/fs_"
6822                            + currentUid;
6823                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6824                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6825                        String msg = "Package " + pkg.packageName
6826                                + " has mismatched uid: "
6827                                + currentUid + " on disk, "
6828                                + pkg.applicationInfo.uid + " in settings";
6829                        // writer
6830                        synchronized (mPackages) {
6831                            mSettings.mReadMessages.append(msg);
6832                            mSettings.mReadMessages.append('\n');
6833                            uidError = true;
6834                            if (!pkgSetting.uidError) {
6835                                reportSettingsProblem(Log.ERROR, msg);
6836                            }
6837                        }
6838                    }
6839                }
6840                pkg.applicationInfo.dataDir = dataPath.getPath();
6841                if (mShouldRestoreconData) {
6842                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6843                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6844                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6845                }
6846            } else {
6847                if (DEBUG_PACKAGE_SCANNING) {
6848                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6849                        Log.v(TAG, "Want this data dir: " + dataPath);
6850                }
6851                //invoke installer to do the actual installation
6852                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6853                        pkg.applicationInfo.seinfo);
6854                if (ret < 0) {
6855                    // Error from installer
6856                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6857                            "Unable to create data dirs [errorCode=" + ret + "]");
6858                }
6859
6860                if (dataPath.exists()) {
6861                    pkg.applicationInfo.dataDir = dataPath.getPath();
6862                } else {
6863                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6864                    pkg.applicationInfo.dataDir = null;
6865                }
6866            }
6867
6868            pkgSetting.uidError = uidError;
6869        }
6870
6871        final String path = scanFile.getPath();
6872        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6873
6874        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6875            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6876
6877            // Some system apps still use directory structure for native libraries
6878            // in which case we might end up not detecting abi solely based on apk
6879            // structure. Try to detect abi based on directory structure.
6880            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6881                    pkg.applicationInfo.primaryCpuAbi == null) {
6882                setBundledAppAbisAndRoots(pkg, pkgSetting);
6883                setNativeLibraryPaths(pkg);
6884            }
6885
6886        } else {
6887            if ((scanFlags & SCAN_MOVE) != 0) {
6888                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6889                // but we already have this packages package info in the PackageSetting. We just
6890                // use that and derive the native library path based on the new codepath.
6891                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6892                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6893            }
6894
6895            // Set native library paths again. For moves, the path will be updated based on the
6896            // ABIs we've determined above. For non-moves, the path will be updated based on the
6897            // ABIs we determined during compilation, but the path will depend on the final
6898            // package path (after the rename away from the stage path).
6899            setNativeLibraryPaths(pkg);
6900        }
6901
6902        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6903        final int[] userIds = sUserManager.getUserIds();
6904        synchronized (mInstallLock) {
6905            // Make sure all user data directories are ready to roll; we're okay
6906            // if they already exist
6907            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6908                for (int userId : userIds) {
6909                    if (userId != 0) {
6910                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6911                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6912                                pkg.applicationInfo.seinfo);
6913                    }
6914                }
6915            }
6916
6917            // Create a native library symlink only if we have native libraries
6918            // and if the native libraries are 32 bit libraries. We do not provide
6919            // this symlink for 64 bit libraries.
6920            if (pkg.applicationInfo.primaryCpuAbi != null &&
6921                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6922                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6923                for (int userId : userIds) {
6924                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6925                            nativeLibPath, userId) < 0) {
6926                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6927                                "Failed linking native library dir (user=" + userId + ")");
6928                    }
6929                }
6930            }
6931        }
6932
6933        // This is a special case for the "system" package, where the ABI is
6934        // dictated by the zygote configuration (and init.rc). We should keep track
6935        // of this ABI so that we can deal with "normal" applications that run under
6936        // the same UID correctly.
6937        if (mPlatformPackage == pkg) {
6938            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6939                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6940        }
6941
6942        // If there's a mismatch between the abi-override in the package setting
6943        // and the abiOverride specified for the install. Warn about this because we
6944        // would've already compiled the app without taking the package setting into
6945        // account.
6946        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6947            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6948                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6949                        " for package: " + pkg.packageName);
6950            }
6951        }
6952
6953        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6954        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6955        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6956
6957        // Copy the derived override back to the parsed package, so that we can
6958        // update the package settings accordingly.
6959        pkg.cpuAbiOverride = cpuAbiOverride;
6960
6961        if (DEBUG_ABI_SELECTION) {
6962            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6963                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6964                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6965        }
6966
6967        // Push the derived path down into PackageSettings so we know what to
6968        // clean up at uninstall time.
6969        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6970
6971        if (DEBUG_ABI_SELECTION) {
6972            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6973                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6974                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6975        }
6976
6977        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6978            // We don't do this here during boot because we can do it all
6979            // at once after scanning all existing packages.
6980            //
6981            // We also do this *before* we perform dexopt on this package, so that
6982            // we can avoid redundant dexopts, and also to make sure we've got the
6983            // code and package path correct.
6984            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6985                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6986        }
6987
6988        if ((scanFlags & SCAN_NO_DEX) == 0) {
6989            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6990                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6991            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6992                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6993            }
6994        }
6995        if (mFactoryTest && pkg.requestedPermissions.contains(
6996                android.Manifest.permission.FACTORY_TEST)) {
6997            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6998        }
6999
7000        ArrayList<PackageParser.Package> clientLibPkgs = null;
7001
7002        // writer
7003        synchronized (mPackages) {
7004            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7005                // Only system apps can add new shared libraries.
7006                if (pkg.libraryNames != null) {
7007                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7008                        String name = pkg.libraryNames.get(i);
7009                        boolean allowed = false;
7010                        if (pkg.isUpdatedSystemApp()) {
7011                            // New library entries can only be added through the
7012                            // system image.  This is important to get rid of a lot
7013                            // of nasty edge cases: for example if we allowed a non-
7014                            // system update of the app to add a library, then uninstalling
7015                            // the update would make the library go away, and assumptions
7016                            // we made such as through app install filtering would now
7017                            // have allowed apps on the device which aren't compatible
7018                            // with it.  Better to just have the restriction here, be
7019                            // conservative, and create many fewer cases that can negatively
7020                            // impact the user experience.
7021                            final PackageSetting sysPs = mSettings
7022                                    .getDisabledSystemPkgLPr(pkg.packageName);
7023                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7024                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7025                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7026                                        allowed = true;
7027                                        allowed = true;
7028                                        break;
7029                                    }
7030                                }
7031                            }
7032                        } else {
7033                            allowed = true;
7034                        }
7035                        if (allowed) {
7036                            if (!mSharedLibraries.containsKey(name)) {
7037                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7038                            } else if (!name.equals(pkg.packageName)) {
7039                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7040                                        + name + " already exists; skipping");
7041                            }
7042                        } else {
7043                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7044                                    + name + " that is not declared on system image; skipping");
7045                        }
7046                    }
7047                    if ((scanFlags&SCAN_BOOTING) == 0) {
7048                        // If we are not booting, we need to update any applications
7049                        // that are clients of our shared library.  If we are booting,
7050                        // this will all be done once the scan is complete.
7051                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7052                    }
7053                }
7054            }
7055        }
7056
7057        // We also need to dexopt any apps that are dependent on this library.  Note that
7058        // if these fail, we should abort the install since installing the library will
7059        // result in some apps being broken.
7060        if (clientLibPkgs != null) {
7061            if ((scanFlags & SCAN_NO_DEX) == 0) {
7062                for (int i = 0; i < clientLibPkgs.size(); i++) {
7063                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7064                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7065                            null /* instruction sets */, forceDex,
7066                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7067                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7068                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7069                                "scanPackageLI failed to dexopt clientLibPkgs");
7070                    }
7071                }
7072            }
7073        }
7074
7075        // Also need to kill any apps that are dependent on the library.
7076        if (clientLibPkgs != null) {
7077            for (int i=0; i<clientLibPkgs.size(); i++) {
7078                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7079                killApplication(clientPkg.applicationInfo.packageName,
7080                        clientPkg.applicationInfo.uid, "update lib");
7081            }
7082        }
7083
7084        // Make sure we're not adding any bogus keyset info
7085        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7086        ksms.assertScannedPackageValid(pkg);
7087
7088        // writer
7089        synchronized (mPackages) {
7090            // We don't expect installation to fail beyond this point
7091
7092            // Add the new setting to mSettings
7093            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7094            // Add the new setting to mPackages
7095            mPackages.put(pkg.applicationInfo.packageName, pkg);
7096            // Make sure we don't accidentally delete its data.
7097            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7098            while (iter.hasNext()) {
7099                PackageCleanItem item = iter.next();
7100                if (pkgName.equals(item.packageName)) {
7101                    iter.remove();
7102                }
7103            }
7104
7105            // Take care of first install / last update times.
7106            if (currentTime != 0) {
7107                if (pkgSetting.firstInstallTime == 0) {
7108                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7109                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7110                    pkgSetting.lastUpdateTime = currentTime;
7111                }
7112            } else if (pkgSetting.firstInstallTime == 0) {
7113                // We need *something*.  Take time time stamp of the file.
7114                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7115            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7116                if (scanFileTime != pkgSetting.timeStamp) {
7117                    // A package on the system image has changed; consider this
7118                    // to be an update.
7119                    pkgSetting.lastUpdateTime = scanFileTime;
7120                }
7121            }
7122
7123            // Add the package's KeySets to the global KeySetManagerService
7124            ksms.addScannedPackageLPw(pkg);
7125
7126            int N = pkg.providers.size();
7127            StringBuilder r = null;
7128            int i;
7129            for (i=0; i<N; i++) {
7130                PackageParser.Provider p = pkg.providers.get(i);
7131                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7132                        p.info.processName, pkg.applicationInfo.uid);
7133                mProviders.addProvider(p);
7134                p.syncable = p.info.isSyncable;
7135                if (p.info.authority != null) {
7136                    String names[] = p.info.authority.split(";");
7137                    p.info.authority = null;
7138                    for (int j = 0; j < names.length; j++) {
7139                        if (j == 1 && p.syncable) {
7140                            // We only want the first authority for a provider to possibly be
7141                            // syncable, so if we already added this provider using a different
7142                            // authority clear the syncable flag. We copy the provider before
7143                            // changing it because the mProviders object contains a reference
7144                            // to a provider that we don't want to change.
7145                            // Only do this for the second authority since the resulting provider
7146                            // object can be the same for all future authorities for this provider.
7147                            p = new PackageParser.Provider(p);
7148                            p.syncable = false;
7149                        }
7150                        if (!mProvidersByAuthority.containsKey(names[j])) {
7151                            mProvidersByAuthority.put(names[j], p);
7152                            if (p.info.authority == null) {
7153                                p.info.authority = names[j];
7154                            } else {
7155                                p.info.authority = p.info.authority + ";" + names[j];
7156                            }
7157                            if (DEBUG_PACKAGE_SCANNING) {
7158                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7159                                    Log.d(TAG, "Registered content provider: " + names[j]
7160                                            + ", className = " + p.info.name + ", isSyncable = "
7161                                            + p.info.isSyncable);
7162                            }
7163                        } else {
7164                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7165                            Slog.w(TAG, "Skipping provider name " + names[j] +
7166                                    " (in package " + pkg.applicationInfo.packageName +
7167                                    "): name already used by "
7168                                    + ((other != null && other.getComponentName() != null)
7169                                            ? other.getComponentName().getPackageName() : "?"));
7170                        }
7171                    }
7172                }
7173                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7174                    if (r == null) {
7175                        r = new StringBuilder(256);
7176                    } else {
7177                        r.append(' ');
7178                    }
7179                    r.append(p.info.name);
7180                }
7181            }
7182            if (r != null) {
7183                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7184            }
7185
7186            N = pkg.services.size();
7187            r = null;
7188            for (i=0; i<N; i++) {
7189                PackageParser.Service s = pkg.services.get(i);
7190                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7191                        s.info.processName, pkg.applicationInfo.uid);
7192                mServices.addService(s);
7193                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7194                    if (r == null) {
7195                        r = new StringBuilder(256);
7196                    } else {
7197                        r.append(' ');
7198                    }
7199                    r.append(s.info.name);
7200                }
7201            }
7202            if (r != null) {
7203                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7204            }
7205
7206            N = pkg.receivers.size();
7207            r = null;
7208            for (i=0; i<N; i++) {
7209                PackageParser.Activity a = pkg.receivers.get(i);
7210                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7211                        a.info.processName, pkg.applicationInfo.uid);
7212                mReceivers.addActivity(a, "receiver");
7213                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7214                    if (r == null) {
7215                        r = new StringBuilder(256);
7216                    } else {
7217                        r.append(' ');
7218                    }
7219                    r.append(a.info.name);
7220                }
7221            }
7222            if (r != null) {
7223                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7224            }
7225
7226            N = pkg.activities.size();
7227            r = null;
7228            for (i=0; i<N; i++) {
7229                PackageParser.Activity a = pkg.activities.get(i);
7230                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7231                        a.info.processName, pkg.applicationInfo.uid);
7232                mActivities.addActivity(a, "activity");
7233                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7234                    if (r == null) {
7235                        r = new StringBuilder(256);
7236                    } else {
7237                        r.append(' ');
7238                    }
7239                    r.append(a.info.name);
7240                }
7241            }
7242            if (r != null) {
7243                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7244            }
7245
7246            N = pkg.permissionGroups.size();
7247            r = null;
7248            for (i=0; i<N; i++) {
7249                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7250                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7251                if (cur == null) {
7252                    mPermissionGroups.put(pg.info.name, pg);
7253                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7254                        if (r == null) {
7255                            r = new StringBuilder(256);
7256                        } else {
7257                            r.append(' ');
7258                        }
7259                        r.append(pg.info.name);
7260                    }
7261                } else {
7262                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7263                            + pg.info.packageName + " ignored: original from "
7264                            + cur.info.packageName);
7265                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7266                        if (r == null) {
7267                            r = new StringBuilder(256);
7268                        } else {
7269                            r.append(' ');
7270                        }
7271                        r.append("DUP:");
7272                        r.append(pg.info.name);
7273                    }
7274                }
7275            }
7276            if (r != null) {
7277                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7278            }
7279
7280            N = pkg.permissions.size();
7281            r = null;
7282            for (i=0; i<N; i++) {
7283                PackageParser.Permission p = pkg.permissions.get(i);
7284
7285                // Now that permission groups have a special meaning, we ignore permission
7286                // groups for legacy apps to prevent unexpected behavior. In particular,
7287                // permissions for one app being granted to someone just becuase they happen
7288                // to be in a group defined by another app (before this had no implications).
7289                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7290                    p.group = mPermissionGroups.get(p.info.group);
7291                    // Warn for a permission in an unknown group.
7292                    if (p.info.group != null && p.group == null) {
7293                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7294                                + p.info.packageName + " in an unknown group " + p.info.group);
7295                    }
7296                }
7297
7298                ArrayMap<String, BasePermission> permissionMap =
7299                        p.tree ? mSettings.mPermissionTrees
7300                                : mSettings.mPermissions;
7301                BasePermission bp = permissionMap.get(p.info.name);
7302
7303                // Allow system apps to redefine non-system permissions
7304                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7305                    final boolean currentOwnerIsSystem = (bp.perm != null
7306                            && isSystemApp(bp.perm.owner));
7307                    if (isSystemApp(p.owner)) {
7308                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7309                            // It's a built-in permission and no owner, take ownership now
7310                            bp.packageSetting = pkgSetting;
7311                            bp.perm = p;
7312                            bp.uid = pkg.applicationInfo.uid;
7313                            bp.sourcePackage = p.info.packageName;
7314                        } else if (!currentOwnerIsSystem) {
7315                            String msg = "New decl " + p.owner + " of permission  "
7316                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7317                            reportSettingsProblem(Log.WARN, msg);
7318                            bp = null;
7319                        }
7320                    }
7321                }
7322
7323                if (bp == null) {
7324                    bp = new BasePermission(p.info.name, p.info.packageName,
7325                            BasePermission.TYPE_NORMAL);
7326                    permissionMap.put(p.info.name, bp);
7327                }
7328
7329                if (bp.perm == null) {
7330                    if (bp.sourcePackage == null
7331                            || bp.sourcePackage.equals(p.info.packageName)) {
7332                        BasePermission tree = findPermissionTreeLP(p.info.name);
7333                        if (tree == null
7334                                || tree.sourcePackage.equals(p.info.packageName)) {
7335                            bp.packageSetting = pkgSetting;
7336                            bp.perm = p;
7337                            bp.uid = pkg.applicationInfo.uid;
7338                            bp.sourcePackage = p.info.packageName;
7339                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7340                                if (r == null) {
7341                                    r = new StringBuilder(256);
7342                                } else {
7343                                    r.append(' ');
7344                                }
7345                                r.append(p.info.name);
7346                            }
7347                        } else {
7348                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7349                                    + p.info.packageName + " ignored: base tree "
7350                                    + tree.name + " is from package "
7351                                    + tree.sourcePackage);
7352                        }
7353                    } else {
7354                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7355                                + p.info.packageName + " ignored: original from "
7356                                + bp.sourcePackage);
7357                    }
7358                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7359                    if (r == null) {
7360                        r = new StringBuilder(256);
7361                    } else {
7362                        r.append(' ');
7363                    }
7364                    r.append("DUP:");
7365                    r.append(p.info.name);
7366                }
7367                if (bp.perm == p) {
7368                    bp.protectionLevel = p.info.protectionLevel;
7369                }
7370            }
7371
7372            if (r != null) {
7373                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7374            }
7375
7376            N = pkg.instrumentation.size();
7377            r = null;
7378            for (i=0; i<N; i++) {
7379                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7380                a.info.packageName = pkg.applicationInfo.packageName;
7381                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7382                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7383                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7384                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7385                a.info.dataDir = pkg.applicationInfo.dataDir;
7386
7387                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7388                // need other information about the application, like the ABI and what not ?
7389                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7390                mInstrumentation.put(a.getComponentName(), a);
7391                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7392                    if (r == null) {
7393                        r = new StringBuilder(256);
7394                    } else {
7395                        r.append(' ');
7396                    }
7397                    r.append(a.info.name);
7398                }
7399            }
7400            if (r != null) {
7401                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7402            }
7403
7404            if (pkg.protectedBroadcasts != null) {
7405                N = pkg.protectedBroadcasts.size();
7406                for (i=0; i<N; i++) {
7407                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7408                }
7409            }
7410
7411            pkgSetting.setTimeStamp(scanFileTime);
7412
7413            // Create idmap files for pairs of (packages, overlay packages).
7414            // Note: "android", ie framework-res.apk, is handled by native layers.
7415            if (pkg.mOverlayTarget != null) {
7416                // This is an overlay package.
7417                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7418                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7419                        mOverlays.put(pkg.mOverlayTarget,
7420                                new ArrayMap<String, PackageParser.Package>());
7421                    }
7422                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7423                    map.put(pkg.packageName, pkg);
7424                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7425                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7426                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7427                                "scanPackageLI failed to createIdmap");
7428                    }
7429                }
7430            } else if (mOverlays.containsKey(pkg.packageName) &&
7431                    !pkg.packageName.equals("android")) {
7432                // This is a regular package, with one or more known overlay packages.
7433                createIdmapsForPackageLI(pkg);
7434            }
7435        }
7436
7437        return pkg;
7438    }
7439
7440    /**
7441     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7442     * is derived purely on the basis of the contents of {@code scanFile} and
7443     * {@code cpuAbiOverride}.
7444     *
7445     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7446     */
7447    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7448                                 String cpuAbiOverride, boolean extractLibs)
7449            throws PackageManagerException {
7450        // TODO: We can probably be smarter about this stuff. For installed apps,
7451        // we can calculate this information at install time once and for all. For
7452        // system apps, we can probably assume that this information doesn't change
7453        // after the first boot scan. As things stand, we do lots of unnecessary work.
7454
7455        // Give ourselves some initial paths; we'll come back for another
7456        // pass once we've determined ABI below.
7457        setNativeLibraryPaths(pkg);
7458
7459        // We would never need to extract libs for forward-locked and external packages,
7460        // since the container service will do it for us. We shouldn't attempt to
7461        // extract libs from system app when it was not updated.
7462        if (pkg.isForwardLocked() || isExternal(pkg) ||
7463            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7464            extractLibs = false;
7465        }
7466
7467        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7468        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7469
7470        NativeLibraryHelper.Handle handle = null;
7471        try {
7472            handle = NativeLibraryHelper.Handle.create(scanFile);
7473            // TODO(multiArch): This can be null for apps that didn't go through the
7474            // usual installation process. We can calculate it again, like we
7475            // do during install time.
7476            //
7477            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7478            // unnecessary.
7479            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7480
7481            // Null out the abis so that they can be recalculated.
7482            pkg.applicationInfo.primaryCpuAbi = null;
7483            pkg.applicationInfo.secondaryCpuAbi = null;
7484            if (isMultiArch(pkg.applicationInfo)) {
7485                // Warn if we've set an abiOverride for multi-lib packages..
7486                // By definition, we need to copy both 32 and 64 bit libraries for
7487                // such packages.
7488                if (pkg.cpuAbiOverride != null
7489                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7490                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7491                }
7492
7493                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7494                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7495                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7496                    if (extractLibs) {
7497                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7498                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7499                                useIsaSpecificSubdirs);
7500                    } else {
7501                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7502                    }
7503                }
7504
7505                maybeThrowExceptionForMultiArchCopy(
7506                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7507
7508                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7509                    if (extractLibs) {
7510                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7511                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7512                                useIsaSpecificSubdirs);
7513                    } else {
7514                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7515                    }
7516                }
7517
7518                maybeThrowExceptionForMultiArchCopy(
7519                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7520
7521                if (abi64 >= 0) {
7522                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7523                }
7524
7525                if (abi32 >= 0) {
7526                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7527                    if (abi64 >= 0) {
7528                        pkg.applicationInfo.secondaryCpuAbi = abi;
7529                    } else {
7530                        pkg.applicationInfo.primaryCpuAbi = abi;
7531                    }
7532                }
7533            } else {
7534                String[] abiList = (cpuAbiOverride != null) ?
7535                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7536
7537                // Enable gross and lame hacks for apps that are built with old
7538                // SDK tools. We must scan their APKs for renderscript bitcode and
7539                // not launch them if it's present. Don't bother checking on devices
7540                // that don't have 64 bit support.
7541                boolean needsRenderScriptOverride = false;
7542                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7543                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7544                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7545                    needsRenderScriptOverride = true;
7546                }
7547
7548                final int copyRet;
7549                if (extractLibs) {
7550                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7551                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7552                } else {
7553                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7554                }
7555
7556                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7557                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7558                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7559                }
7560
7561                if (copyRet >= 0) {
7562                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7563                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7564                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7565                } else if (needsRenderScriptOverride) {
7566                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7567                }
7568            }
7569        } catch (IOException ioe) {
7570            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7571        } finally {
7572            IoUtils.closeQuietly(handle);
7573        }
7574
7575        // Now that we've calculated the ABIs and determined if it's an internal app,
7576        // we will go ahead and populate the nativeLibraryPath.
7577        setNativeLibraryPaths(pkg);
7578    }
7579
7580    /**
7581     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7582     * i.e, so that all packages can be run inside a single process if required.
7583     *
7584     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7585     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7586     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7587     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7588     * updating a package that belongs to a shared user.
7589     *
7590     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7591     * adds unnecessary complexity.
7592     */
7593    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7594            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7595        String requiredInstructionSet = null;
7596        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7597            requiredInstructionSet = VMRuntime.getInstructionSet(
7598                     scannedPackage.applicationInfo.primaryCpuAbi);
7599        }
7600
7601        PackageSetting requirer = null;
7602        for (PackageSetting ps : packagesForUser) {
7603            // If packagesForUser contains scannedPackage, we skip it. This will happen
7604            // when scannedPackage is an update of an existing package. Without this check,
7605            // we will never be able to change the ABI of any package belonging to a shared
7606            // user, even if it's compatible with other packages.
7607            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7608                if (ps.primaryCpuAbiString == null) {
7609                    continue;
7610                }
7611
7612                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7613                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7614                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7615                    // this but there's not much we can do.
7616                    String errorMessage = "Instruction set mismatch, "
7617                            + ((requirer == null) ? "[caller]" : requirer)
7618                            + " requires " + requiredInstructionSet + " whereas " + ps
7619                            + " requires " + instructionSet;
7620                    Slog.w(TAG, errorMessage);
7621                }
7622
7623                if (requiredInstructionSet == null) {
7624                    requiredInstructionSet = instructionSet;
7625                    requirer = ps;
7626                }
7627            }
7628        }
7629
7630        if (requiredInstructionSet != null) {
7631            String adjustedAbi;
7632            if (requirer != null) {
7633                // requirer != null implies that either scannedPackage was null or that scannedPackage
7634                // did not require an ABI, in which case we have to adjust scannedPackage to match
7635                // the ABI of the set (which is the same as requirer's ABI)
7636                adjustedAbi = requirer.primaryCpuAbiString;
7637                if (scannedPackage != null) {
7638                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7639                }
7640            } else {
7641                // requirer == null implies that we're updating all ABIs in the set to
7642                // match scannedPackage.
7643                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7644            }
7645
7646            for (PackageSetting ps : packagesForUser) {
7647                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7648                    if (ps.primaryCpuAbiString != null) {
7649                        continue;
7650                    }
7651
7652                    ps.primaryCpuAbiString = adjustedAbi;
7653                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7654                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7655                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7656
7657                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7658                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7659                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7660                            ps.primaryCpuAbiString = null;
7661                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7662                            return;
7663                        } else {
7664                            mInstaller.rmdex(ps.codePathString,
7665                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7666                        }
7667                    }
7668                }
7669            }
7670        }
7671    }
7672
7673    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7674        synchronized (mPackages) {
7675            mResolverReplaced = true;
7676            // Set up information for custom user intent resolution activity.
7677            mResolveActivity.applicationInfo = pkg.applicationInfo;
7678            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7679            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7680            mResolveActivity.processName = pkg.applicationInfo.packageName;
7681            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7682            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7683                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7684            mResolveActivity.theme = 0;
7685            mResolveActivity.exported = true;
7686            mResolveActivity.enabled = true;
7687            mResolveInfo.activityInfo = mResolveActivity;
7688            mResolveInfo.priority = 0;
7689            mResolveInfo.preferredOrder = 0;
7690            mResolveInfo.match = 0;
7691            mResolveComponentName = mCustomResolverComponentName;
7692            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7693                    mResolveComponentName);
7694        }
7695    }
7696
7697    private static String calculateBundledApkRoot(final String codePathString) {
7698        final File codePath = new File(codePathString);
7699        final File codeRoot;
7700        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7701            codeRoot = Environment.getRootDirectory();
7702        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7703            codeRoot = Environment.getOemDirectory();
7704        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7705            codeRoot = Environment.getVendorDirectory();
7706        } else {
7707            // Unrecognized code path; take its top real segment as the apk root:
7708            // e.g. /something/app/blah.apk => /something
7709            try {
7710                File f = codePath.getCanonicalFile();
7711                File parent = f.getParentFile();    // non-null because codePath is a file
7712                File tmp;
7713                while ((tmp = parent.getParentFile()) != null) {
7714                    f = parent;
7715                    parent = tmp;
7716                }
7717                codeRoot = f;
7718                Slog.w(TAG, "Unrecognized code path "
7719                        + codePath + " - using " + codeRoot);
7720            } catch (IOException e) {
7721                // Can't canonicalize the code path -- shenanigans?
7722                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7723                return Environment.getRootDirectory().getPath();
7724            }
7725        }
7726        return codeRoot.getPath();
7727    }
7728
7729    /**
7730     * Derive and set the location of native libraries for the given package,
7731     * which varies depending on where and how the package was installed.
7732     */
7733    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7734        final ApplicationInfo info = pkg.applicationInfo;
7735        final String codePath = pkg.codePath;
7736        final File codeFile = new File(codePath);
7737        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7738        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7739
7740        info.nativeLibraryRootDir = null;
7741        info.nativeLibraryRootRequiresIsa = false;
7742        info.nativeLibraryDir = null;
7743        info.secondaryNativeLibraryDir = null;
7744
7745        if (isApkFile(codeFile)) {
7746            // Monolithic install
7747            if (bundledApp) {
7748                // If "/system/lib64/apkname" exists, assume that is the per-package
7749                // native library directory to use; otherwise use "/system/lib/apkname".
7750                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7751                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7752                        getPrimaryInstructionSet(info));
7753
7754                // This is a bundled system app so choose the path based on the ABI.
7755                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7756                // is just the default path.
7757                final String apkName = deriveCodePathName(codePath);
7758                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7759                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7760                        apkName).getAbsolutePath();
7761
7762                if (info.secondaryCpuAbi != null) {
7763                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7764                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7765                            secondaryLibDir, apkName).getAbsolutePath();
7766                }
7767            } else if (asecApp) {
7768                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7769                        .getAbsolutePath();
7770            } else {
7771                final String apkName = deriveCodePathName(codePath);
7772                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7773                        .getAbsolutePath();
7774            }
7775
7776            info.nativeLibraryRootRequiresIsa = false;
7777            info.nativeLibraryDir = info.nativeLibraryRootDir;
7778        } else {
7779            // Cluster install
7780            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7781            info.nativeLibraryRootRequiresIsa = true;
7782
7783            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7784                    getPrimaryInstructionSet(info)).getAbsolutePath();
7785
7786            if (info.secondaryCpuAbi != null) {
7787                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7788                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7789            }
7790        }
7791    }
7792
7793    /**
7794     * Calculate the abis and roots for a bundled app. These can uniquely
7795     * be determined from the contents of the system partition, i.e whether
7796     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7797     * of this information, and instead assume that the system was built
7798     * sensibly.
7799     */
7800    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7801                                           PackageSetting pkgSetting) {
7802        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7803
7804        // If "/system/lib64/apkname" exists, assume that is the per-package
7805        // native library directory to use; otherwise use "/system/lib/apkname".
7806        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7807        setBundledAppAbi(pkg, apkRoot, apkName);
7808        // pkgSetting might be null during rescan following uninstall of updates
7809        // to a bundled app, so accommodate that possibility.  The settings in
7810        // that case will be established later from the parsed package.
7811        //
7812        // If the settings aren't null, sync them up with what we've just derived.
7813        // note that apkRoot isn't stored in the package settings.
7814        if (pkgSetting != null) {
7815            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7816            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7817        }
7818    }
7819
7820    /**
7821     * Deduces the ABI of a bundled app and sets the relevant fields on the
7822     * parsed pkg object.
7823     *
7824     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7825     *        under which system libraries are installed.
7826     * @param apkName the name of the installed package.
7827     */
7828    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7829        final File codeFile = new File(pkg.codePath);
7830
7831        final boolean has64BitLibs;
7832        final boolean has32BitLibs;
7833        if (isApkFile(codeFile)) {
7834            // Monolithic install
7835            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7836            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7837        } else {
7838            // Cluster install
7839            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7840            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7841                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7842                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7843                has64BitLibs = (new File(rootDir, isa)).exists();
7844            } else {
7845                has64BitLibs = false;
7846            }
7847            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7848                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7849                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7850                has32BitLibs = (new File(rootDir, isa)).exists();
7851            } else {
7852                has32BitLibs = false;
7853            }
7854        }
7855
7856        if (has64BitLibs && !has32BitLibs) {
7857            // The package has 64 bit libs, but not 32 bit libs. Its primary
7858            // ABI should be 64 bit. We can safely assume here that the bundled
7859            // native libraries correspond to the most preferred ABI in the list.
7860
7861            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7862            pkg.applicationInfo.secondaryCpuAbi = null;
7863        } else if (has32BitLibs && !has64BitLibs) {
7864            // The package has 32 bit libs but not 64 bit libs. Its primary
7865            // ABI should be 32 bit.
7866
7867            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7868            pkg.applicationInfo.secondaryCpuAbi = null;
7869        } else if (has32BitLibs && has64BitLibs) {
7870            // The application has both 64 and 32 bit bundled libraries. We check
7871            // here that the app declares multiArch support, and warn if it doesn't.
7872            //
7873            // We will be lenient here and record both ABIs. The primary will be the
7874            // ABI that's higher on the list, i.e, a device that's configured to prefer
7875            // 64 bit apps will see a 64 bit primary ABI,
7876
7877            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7878                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7879            }
7880
7881            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7882                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7883                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7884            } else {
7885                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7886                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7887            }
7888        } else {
7889            pkg.applicationInfo.primaryCpuAbi = null;
7890            pkg.applicationInfo.secondaryCpuAbi = null;
7891        }
7892    }
7893
7894    private void killApplication(String pkgName, int appId, String reason) {
7895        // Request the ActivityManager to kill the process(only for existing packages)
7896        // so that we do not end up in a confused state while the user is still using the older
7897        // version of the application while the new one gets installed.
7898        IActivityManager am = ActivityManagerNative.getDefault();
7899        if (am != null) {
7900            try {
7901                am.killApplicationWithAppId(pkgName, appId, reason);
7902            } catch (RemoteException e) {
7903            }
7904        }
7905    }
7906
7907    void removePackageLI(PackageSetting ps, boolean chatty) {
7908        if (DEBUG_INSTALL) {
7909            if (chatty)
7910                Log.d(TAG, "Removing package " + ps.name);
7911        }
7912
7913        // writer
7914        synchronized (mPackages) {
7915            mPackages.remove(ps.name);
7916            final PackageParser.Package pkg = ps.pkg;
7917            if (pkg != null) {
7918                cleanPackageDataStructuresLILPw(pkg, chatty);
7919            }
7920        }
7921    }
7922
7923    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7924        if (DEBUG_INSTALL) {
7925            if (chatty)
7926                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7927        }
7928
7929        // writer
7930        synchronized (mPackages) {
7931            mPackages.remove(pkg.applicationInfo.packageName);
7932            cleanPackageDataStructuresLILPw(pkg, chatty);
7933        }
7934    }
7935
7936    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7937        int N = pkg.providers.size();
7938        StringBuilder r = null;
7939        int i;
7940        for (i=0; i<N; i++) {
7941            PackageParser.Provider p = pkg.providers.get(i);
7942            mProviders.removeProvider(p);
7943            if (p.info.authority == null) {
7944
7945                /* There was another ContentProvider with this authority when
7946                 * this app was installed so this authority is null,
7947                 * Ignore it as we don't have to unregister the provider.
7948                 */
7949                continue;
7950            }
7951            String names[] = p.info.authority.split(";");
7952            for (int j = 0; j < names.length; j++) {
7953                if (mProvidersByAuthority.get(names[j]) == p) {
7954                    mProvidersByAuthority.remove(names[j]);
7955                    if (DEBUG_REMOVE) {
7956                        if (chatty)
7957                            Log.d(TAG, "Unregistered content provider: " + names[j]
7958                                    + ", className = " + p.info.name + ", isSyncable = "
7959                                    + p.info.isSyncable);
7960                    }
7961                }
7962            }
7963            if (DEBUG_REMOVE && chatty) {
7964                if (r == null) {
7965                    r = new StringBuilder(256);
7966                } else {
7967                    r.append(' ');
7968                }
7969                r.append(p.info.name);
7970            }
7971        }
7972        if (r != null) {
7973            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7974        }
7975
7976        N = pkg.services.size();
7977        r = null;
7978        for (i=0; i<N; i++) {
7979            PackageParser.Service s = pkg.services.get(i);
7980            mServices.removeService(s);
7981            if (chatty) {
7982                if (r == null) {
7983                    r = new StringBuilder(256);
7984                } else {
7985                    r.append(' ');
7986                }
7987                r.append(s.info.name);
7988            }
7989        }
7990        if (r != null) {
7991            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7992        }
7993
7994        N = pkg.receivers.size();
7995        r = null;
7996        for (i=0; i<N; i++) {
7997            PackageParser.Activity a = pkg.receivers.get(i);
7998            mReceivers.removeActivity(a, "receiver");
7999            if (DEBUG_REMOVE && chatty) {
8000                if (r == null) {
8001                    r = new StringBuilder(256);
8002                } else {
8003                    r.append(' ');
8004                }
8005                r.append(a.info.name);
8006            }
8007        }
8008        if (r != null) {
8009            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8010        }
8011
8012        N = pkg.activities.size();
8013        r = null;
8014        for (i=0; i<N; i++) {
8015            PackageParser.Activity a = pkg.activities.get(i);
8016            mActivities.removeActivity(a, "activity");
8017            if (DEBUG_REMOVE && chatty) {
8018                if (r == null) {
8019                    r = new StringBuilder(256);
8020                } else {
8021                    r.append(' ');
8022                }
8023                r.append(a.info.name);
8024            }
8025        }
8026        if (r != null) {
8027            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8028        }
8029
8030        N = pkg.permissions.size();
8031        r = null;
8032        for (i=0; i<N; i++) {
8033            PackageParser.Permission p = pkg.permissions.get(i);
8034            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8035            if (bp == null) {
8036                bp = mSettings.mPermissionTrees.get(p.info.name);
8037            }
8038            if (bp != null && bp.perm == p) {
8039                bp.perm = null;
8040                if (DEBUG_REMOVE && chatty) {
8041                    if (r == null) {
8042                        r = new StringBuilder(256);
8043                    } else {
8044                        r.append(' ');
8045                    }
8046                    r.append(p.info.name);
8047                }
8048            }
8049            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8050                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8051                if (appOpPerms != null) {
8052                    appOpPerms.remove(pkg.packageName);
8053                }
8054            }
8055        }
8056        if (r != null) {
8057            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8058        }
8059
8060        N = pkg.requestedPermissions.size();
8061        r = null;
8062        for (i=0; i<N; i++) {
8063            String perm = pkg.requestedPermissions.get(i);
8064            BasePermission bp = mSettings.mPermissions.get(perm);
8065            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8066                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8067                if (appOpPerms != null) {
8068                    appOpPerms.remove(pkg.packageName);
8069                    if (appOpPerms.isEmpty()) {
8070                        mAppOpPermissionPackages.remove(perm);
8071                    }
8072                }
8073            }
8074        }
8075        if (r != null) {
8076            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8077        }
8078
8079        N = pkg.instrumentation.size();
8080        r = null;
8081        for (i=0; i<N; i++) {
8082            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8083            mInstrumentation.remove(a.getComponentName());
8084            if (DEBUG_REMOVE && chatty) {
8085                if (r == null) {
8086                    r = new StringBuilder(256);
8087                } else {
8088                    r.append(' ');
8089                }
8090                r.append(a.info.name);
8091            }
8092        }
8093        if (r != null) {
8094            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8095        }
8096
8097        r = null;
8098        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8099            // Only system apps can hold shared libraries.
8100            if (pkg.libraryNames != null) {
8101                for (i=0; i<pkg.libraryNames.size(); i++) {
8102                    String name = pkg.libraryNames.get(i);
8103                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8104                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8105                        mSharedLibraries.remove(name);
8106                        if (DEBUG_REMOVE && chatty) {
8107                            if (r == null) {
8108                                r = new StringBuilder(256);
8109                            } else {
8110                                r.append(' ');
8111                            }
8112                            r.append(name);
8113                        }
8114                    }
8115                }
8116            }
8117        }
8118        if (r != null) {
8119            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8120        }
8121    }
8122
8123    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8124        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8125            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8126                return true;
8127            }
8128        }
8129        return false;
8130    }
8131
8132    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8133    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8134    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8135
8136    private void updatePermissionsLPw(String changingPkg,
8137            PackageParser.Package pkgInfo, int flags) {
8138        // Make sure there are no dangling permission trees.
8139        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8140        while (it.hasNext()) {
8141            final BasePermission bp = it.next();
8142            if (bp.packageSetting == null) {
8143                // We may not yet have parsed the package, so just see if
8144                // we still know about its settings.
8145                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8146            }
8147            if (bp.packageSetting == null) {
8148                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8149                        + " from package " + bp.sourcePackage);
8150                it.remove();
8151            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8152                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8153                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8154                            + " from package " + bp.sourcePackage);
8155                    flags |= UPDATE_PERMISSIONS_ALL;
8156                    it.remove();
8157                }
8158            }
8159        }
8160
8161        // Make sure all dynamic permissions have been assigned to a package,
8162        // and make sure there are no dangling permissions.
8163        it = mSettings.mPermissions.values().iterator();
8164        while (it.hasNext()) {
8165            final BasePermission bp = it.next();
8166            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8167                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8168                        + bp.name + " pkg=" + bp.sourcePackage
8169                        + " info=" + bp.pendingInfo);
8170                if (bp.packageSetting == null && bp.pendingInfo != null) {
8171                    final BasePermission tree = findPermissionTreeLP(bp.name);
8172                    if (tree != null && tree.perm != null) {
8173                        bp.packageSetting = tree.packageSetting;
8174                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8175                                new PermissionInfo(bp.pendingInfo));
8176                        bp.perm.info.packageName = tree.perm.info.packageName;
8177                        bp.perm.info.name = bp.name;
8178                        bp.uid = tree.uid;
8179                    }
8180                }
8181            }
8182            if (bp.packageSetting == null) {
8183                // We may not yet have parsed the package, so just see if
8184                // we still know about its settings.
8185                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8186            }
8187            if (bp.packageSetting == null) {
8188                Slog.w(TAG, "Removing dangling permission: " + bp.name
8189                        + " from package " + bp.sourcePackage);
8190                it.remove();
8191            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8192                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8193                    Slog.i(TAG, "Removing old permission: " + bp.name
8194                            + " from package " + bp.sourcePackage);
8195                    flags |= UPDATE_PERMISSIONS_ALL;
8196                    it.remove();
8197                }
8198            }
8199        }
8200
8201        // Now update the permissions for all packages, in particular
8202        // replace the granted permissions of the system packages.
8203        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8204            for (PackageParser.Package pkg : mPackages.values()) {
8205                if (pkg != pkgInfo) {
8206                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8207                            changingPkg);
8208                }
8209            }
8210        }
8211
8212        if (pkgInfo != null) {
8213            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8214        }
8215    }
8216
8217    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8218            String packageOfInterest) {
8219        // IMPORTANT: There are two types of permissions: install and runtime.
8220        // Install time permissions are granted when the app is installed to
8221        // all device users and users added in the future. Runtime permissions
8222        // are granted at runtime explicitly to specific users. Normal and signature
8223        // protected permissions are install time permissions. Dangerous permissions
8224        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8225        // otherwise they are runtime permissions. This function does not manage
8226        // runtime permissions except for the case an app targeting Lollipop MR1
8227        // being upgraded to target a newer SDK, in which case dangerous permissions
8228        // are transformed from install time to runtime ones.
8229
8230        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8231        if (ps == null) {
8232            return;
8233        }
8234
8235        PermissionsState permissionsState = ps.getPermissionsState();
8236        PermissionsState origPermissions = permissionsState;
8237
8238        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8239
8240        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8241
8242        boolean changedInstallPermission = false;
8243
8244        if (replace) {
8245            ps.installPermissionsFixed = false;
8246            if (!ps.isSharedUser()) {
8247                origPermissions = new PermissionsState(permissionsState);
8248                permissionsState.reset();
8249            }
8250        }
8251
8252        permissionsState.setGlobalGids(mGlobalGids);
8253
8254        final int N = pkg.requestedPermissions.size();
8255        for (int i=0; i<N; i++) {
8256            final String name = pkg.requestedPermissions.get(i);
8257            final BasePermission bp = mSettings.mPermissions.get(name);
8258
8259            if (DEBUG_INSTALL) {
8260                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8261            }
8262
8263            if (bp == null || bp.packageSetting == null) {
8264                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8265                    Slog.w(TAG, "Unknown permission " + name
8266                            + " in package " + pkg.packageName);
8267                }
8268                continue;
8269            }
8270
8271            final String perm = bp.name;
8272            boolean allowedSig = false;
8273            int grant = GRANT_DENIED;
8274
8275            // Keep track of app op permissions.
8276            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8277                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8278                if (pkgs == null) {
8279                    pkgs = new ArraySet<>();
8280                    mAppOpPermissionPackages.put(bp.name, pkgs);
8281                }
8282                pkgs.add(pkg.packageName);
8283            }
8284
8285            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8286            switch (level) {
8287                case PermissionInfo.PROTECTION_NORMAL: {
8288                    // For all apps normal permissions are install time ones.
8289                    grant = GRANT_INSTALL;
8290                } break;
8291
8292                case PermissionInfo.PROTECTION_DANGEROUS: {
8293                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8294                        // For legacy apps dangerous permissions are install time ones.
8295                        grant = GRANT_INSTALL_LEGACY;
8296                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8297                        // For legacy apps that became modern, install becomes runtime.
8298                        grant = GRANT_UPGRADE;
8299                    } else {
8300                        // For modern apps keep runtime permissions unchanged.
8301                        grant = GRANT_RUNTIME;
8302                    }
8303                } break;
8304
8305                case PermissionInfo.PROTECTION_SIGNATURE: {
8306                    // For all apps signature permissions are install time ones.
8307                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8308                    if (allowedSig) {
8309                        grant = GRANT_INSTALL;
8310                    }
8311                } break;
8312            }
8313
8314            if (DEBUG_INSTALL) {
8315                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8316            }
8317
8318            if (grant != GRANT_DENIED) {
8319                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8320                    // If this is an existing, non-system package, then
8321                    // we can't add any new permissions to it.
8322                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8323                        // Except...  if this is a permission that was added
8324                        // to the platform (note: need to only do this when
8325                        // updating the platform).
8326                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8327                            grant = GRANT_DENIED;
8328                        }
8329                    }
8330                }
8331
8332                switch (grant) {
8333                    case GRANT_INSTALL: {
8334                        // Revoke this as runtime permission to handle the case of
8335                        // a runtime permission being downgraded to an install one.
8336                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8337                            if (origPermissions.getRuntimePermissionState(
8338                                    bp.name, userId) != null) {
8339                                // Revoke the runtime permission and clear the flags.
8340                                origPermissions.revokeRuntimePermission(bp, userId);
8341                                origPermissions.updatePermissionFlags(bp, userId,
8342                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8343                                // If we revoked a permission permission, we have to write.
8344                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8345                                        changedRuntimePermissionUserIds, userId);
8346                            }
8347                        }
8348                        // Grant an install permission.
8349                        if (permissionsState.grantInstallPermission(bp) !=
8350                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8351                            changedInstallPermission = true;
8352                        }
8353                    } break;
8354
8355                    case GRANT_INSTALL_LEGACY: {
8356                        // Grant an install permission.
8357                        if (permissionsState.grantInstallPermission(bp) !=
8358                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8359                            changedInstallPermission = true;
8360                        }
8361                    } break;
8362
8363                    case GRANT_RUNTIME: {
8364                        // Grant previously granted runtime permissions.
8365                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8366                            PermissionState permissionState = origPermissions
8367                                    .getRuntimePermissionState(bp.name, userId);
8368                            final int flags = permissionState != null
8369                                    ? permissionState.getFlags() : 0;
8370                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8371                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8372                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8373                                    // If we cannot put the permission as it was, we have to write.
8374                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8375                                            changedRuntimePermissionUserIds, userId);
8376                                }
8377                            }
8378                            // Propagate the permission flags.
8379                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8380                        }
8381                    } break;
8382
8383                    case GRANT_UPGRADE: {
8384                        // Grant runtime permissions for a previously held install permission.
8385                        PermissionState permissionState = origPermissions
8386                                .getInstallPermissionState(bp.name);
8387                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8388
8389                        if (origPermissions.revokeInstallPermission(bp)
8390                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8391                            // We will be transferring the permission flags, so clear them.
8392                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8393                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8394                            changedInstallPermission = true;
8395                        }
8396
8397                        // If the permission is not to be promoted to runtime we ignore it and
8398                        // also its other flags as they are not applicable to install permissions.
8399                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8400                            for (int userId : currentUserIds) {
8401                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8402                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8403                                    // Transfer the permission flags.
8404                                    permissionsState.updatePermissionFlags(bp, userId,
8405                                            flags, flags);
8406                                    // If we granted the permission, we have to write.
8407                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8408                                            changedRuntimePermissionUserIds, userId);
8409                                }
8410                            }
8411                        }
8412                    } break;
8413
8414                    default: {
8415                        if (packageOfInterest == null
8416                                || packageOfInterest.equals(pkg.packageName)) {
8417                            Slog.w(TAG, "Not granting permission " + perm
8418                                    + " to package " + pkg.packageName
8419                                    + " because it was previously installed without");
8420                        }
8421                    } break;
8422                }
8423            } else {
8424                if (permissionsState.revokeInstallPermission(bp) !=
8425                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8426                    // Also drop the permission flags.
8427                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8428                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8429                    changedInstallPermission = true;
8430                    Slog.i(TAG, "Un-granting permission " + perm
8431                            + " from package " + pkg.packageName
8432                            + " (protectionLevel=" + bp.protectionLevel
8433                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8434                            + ")");
8435                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8436                    // Don't print warning for app op permissions, since it is fine for them
8437                    // not to be granted, there is a UI for the user to decide.
8438                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8439                        Slog.w(TAG, "Not granting permission " + perm
8440                                + " to package " + pkg.packageName
8441                                + " (protectionLevel=" + bp.protectionLevel
8442                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8443                                + ")");
8444                    }
8445                }
8446            }
8447        }
8448
8449        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8450                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8451            // This is the first that we have heard about this package, so the
8452            // permissions we have now selected are fixed until explicitly
8453            // changed.
8454            ps.installPermissionsFixed = true;
8455        }
8456
8457        // Persist the runtime permissions state for users with changes.
8458        for (int userId : changedRuntimePermissionUserIds) {
8459            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8460        }
8461    }
8462
8463    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8464        boolean allowed = false;
8465        final int NP = PackageParser.NEW_PERMISSIONS.length;
8466        for (int ip=0; ip<NP; ip++) {
8467            final PackageParser.NewPermissionInfo npi
8468                    = PackageParser.NEW_PERMISSIONS[ip];
8469            if (npi.name.equals(perm)
8470                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8471                allowed = true;
8472                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8473                        + pkg.packageName);
8474                break;
8475            }
8476        }
8477        return allowed;
8478    }
8479
8480    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8481            BasePermission bp, PermissionsState origPermissions) {
8482        boolean allowed;
8483        allowed = (compareSignatures(
8484                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8485                        == PackageManager.SIGNATURE_MATCH)
8486                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8487                        == PackageManager.SIGNATURE_MATCH);
8488        if (!allowed && (bp.protectionLevel
8489                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8490            if (isSystemApp(pkg)) {
8491                // For updated system applications, a system permission
8492                // is granted only if it had been defined by the original application.
8493                if (pkg.isUpdatedSystemApp()) {
8494                    final PackageSetting sysPs = mSettings
8495                            .getDisabledSystemPkgLPr(pkg.packageName);
8496                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8497                        // If the original was granted this permission, we take
8498                        // that grant decision as read and propagate it to the
8499                        // update.
8500                        if (sysPs.isPrivileged()) {
8501                            allowed = true;
8502                        }
8503                    } else {
8504                        // The system apk may have been updated with an older
8505                        // version of the one on the data partition, but which
8506                        // granted a new system permission that it didn't have
8507                        // before.  In this case we do want to allow the app to
8508                        // now get the new permission if the ancestral apk is
8509                        // privileged to get it.
8510                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8511                            for (int j=0;
8512                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8513                                if (perm.equals(
8514                                        sysPs.pkg.requestedPermissions.get(j))) {
8515                                    allowed = true;
8516                                    break;
8517                                }
8518                            }
8519                        }
8520                    }
8521                } else {
8522                    allowed = isPrivilegedApp(pkg);
8523                }
8524            }
8525        }
8526        if (!allowed) {
8527            if (!allowed && (bp.protectionLevel
8528                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8529                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8530                // If this was a previously normal/dangerous permission that got moved
8531                // to a system permission as part of the runtime permission redesign, then
8532                // we still want to blindly grant it to old apps.
8533                allowed = true;
8534            }
8535            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8536                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8537                // If this permission is to be granted to the system installer and
8538                // this app is an installer, then it gets the permission.
8539                allowed = true;
8540            }
8541            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8542                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8543                // If this permission is to be granted to the system verifier and
8544                // this app is a verifier, then it gets the permission.
8545                allowed = true;
8546            }
8547            if (!allowed && (bp.protectionLevel
8548                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8549                    && isSystemApp(pkg)) {
8550                // Any pre-installed system app is allowed to get this permission.
8551                allowed = true;
8552            }
8553            if (!allowed && (bp.protectionLevel
8554                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8555                // For development permissions, a development permission
8556                // is granted only if it was already granted.
8557                allowed = origPermissions.hasInstallPermission(perm);
8558            }
8559        }
8560        return allowed;
8561    }
8562
8563    final class ActivityIntentResolver
8564            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8565        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8566                boolean defaultOnly, int userId) {
8567            if (!sUserManager.exists(userId)) return null;
8568            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8569            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8570        }
8571
8572        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8573                int userId) {
8574            if (!sUserManager.exists(userId)) return null;
8575            mFlags = flags;
8576            return super.queryIntent(intent, resolvedType,
8577                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8578        }
8579
8580        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8581                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8582            if (!sUserManager.exists(userId)) return null;
8583            if (packageActivities == null) {
8584                return null;
8585            }
8586            mFlags = flags;
8587            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8588            final int N = packageActivities.size();
8589            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8590                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8591
8592            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8593            for (int i = 0; i < N; ++i) {
8594                intentFilters = packageActivities.get(i).intents;
8595                if (intentFilters != null && intentFilters.size() > 0) {
8596                    PackageParser.ActivityIntentInfo[] array =
8597                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8598                    intentFilters.toArray(array);
8599                    listCut.add(array);
8600                }
8601            }
8602            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8603        }
8604
8605        public final void addActivity(PackageParser.Activity a, String type) {
8606            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8607            mActivities.put(a.getComponentName(), a);
8608            if (DEBUG_SHOW_INFO)
8609                Log.v(
8610                TAG, "  " + type + " " +
8611                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8612            if (DEBUG_SHOW_INFO)
8613                Log.v(TAG, "    Class=" + a.info.name);
8614            final int NI = a.intents.size();
8615            for (int j=0; j<NI; j++) {
8616                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8617                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8618                    intent.setPriority(0);
8619                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8620                            + a.className + " with priority > 0, forcing to 0");
8621                }
8622                if (DEBUG_SHOW_INFO) {
8623                    Log.v(TAG, "    IntentFilter:");
8624                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8625                }
8626                if (!intent.debugCheck()) {
8627                    Log.w(TAG, "==> For Activity " + a.info.name);
8628                }
8629                addFilter(intent);
8630            }
8631        }
8632
8633        public final void removeActivity(PackageParser.Activity a, String type) {
8634            mActivities.remove(a.getComponentName());
8635            if (DEBUG_SHOW_INFO) {
8636                Log.v(TAG, "  " + type + " "
8637                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8638                                : a.info.name) + ":");
8639                Log.v(TAG, "    Class=" + a.info.name);
8640            }
8641            final int NI = a.intents.size();
8642            for (int j=0; j<NI; j++) {
8643                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8644                if (DEBUG_SHOW_INFO) {
8645                    Log.v(TAG, "    IntentFilter:");
8646                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8647                }
8648                removeFilter(intent);
8649            }
8650        }
8651
8652        @Override
8653        protected boolean allowFilterResult(
8654                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8655            ActivityInfo filterAi = filter.activity.info;
8656            for (int i=dest.size()-1; i>=0; i--) {
8657                ActivityInfo destAi = dest.get(i).activityInfo;
8658                if (destAi.name == filterAi.name
8659                        && destAi.packageName == filterAi.packageName) {
8660                    return false;
8661                }
8662            }
8663            return true;
8664        }
8665
8666        @Override
8667        protected ActivityIntentInfo[] newArray(int size) {
8668            return new ActivityIntentInfo[size];
8669        }
8670
8671        @Override
8672        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8673            if (!sUserManager.exists(userId)) return true;
8674            PackageParser.Package p = filter.activity.owner;
8675            if (p != null) {
8676                PackageSetting ps = (PackageSetting)p.mExtras;
8677                if (ps != null) {
8678                    // System apps are never considered stopped for purposes of
8679                    // filtering, because there may be no way for the user to
8680                    // actually re-launch them.
8681                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8682                            && ps.getStopped(userId);
8683                }
8684            }
8685            return false;
8686        }
8687
8688        @Override
8689        protected boolean isPackageForFilter(String packageName,
8690                PackageParser.ActivityIntentInfo info) {
8691            return packageName.equals(info.activity.owner.packageName);
8692        }
8693
8694        @Override
8695        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8696                int match, int userId) {
8697            if (!sUserManager.exists(userId)) return null;
8698            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8699                return null;
8700            }
8701            final PackageParser.Activity activity = info.activity;
8702            if (mSafeMode && (activity.info.applicationInfo.flags
8703                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8704                return null;
8705            }
8706            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8707            if (ps == null) {
8708                return null;
8709            }
8710            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8711                    ps.readUserState(userId), userId);
8712            if (ai == null) {
8713                return null;
8714            }
8715            final ResolveInfo res = new ResolveInfo();
8716            res.activityInfo = ai;
8717            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8718                res.filter = info;
8719            }
8720            if (info != null) {
8721                res.handleAllWebDataURI = info.handleAllWebDataURI();
8722            }
8723            res.priority = info.getPriority();
8724            res.preferredOrder = activity.owner.mPreferredOrder;
8725            //System.out.println("Result: " + res.activityInfo.className +
8726            //                   " = " + res.priority);
8727            res.match = match;
8728            res.isDefault = info.hasDefault;
8729            res.labelRes = info.labelRes;
8730            res.nonLocalizedLabel = info.nonLocalizedLabel;
8731            if (userNeedsBadging(userId)) {
8732                res.noResourceId = true;
8733            } else {
8734                res.icon = info.icon;
8735            }
8736            res.iconResourceId = info.icon;
8737            res.system = res.activityInfo.applicationInfo.isSystemApp();
8738            return res;
8739        }
8740
8741        @Override
8742        protected void sortResults(List<ResolveInfo> results) {
8743            Collections.sort(results, mResolvePrioritySorter);
8744        }
8745
8746        @Override
8747        protected void dumpFilter(PrintWriter out, String prefix,
8748                PackageParser.ActivityIntentInfo filter) {
8749            out.print(prefix); out.print(
8750                    Integer.toHexString(System.identityHashCode(filter.activity)));
8751                    out.print(' ');
8752                    filter.activity.printComponentShortName(out);
8753                    out.print(" filter ");
8754                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8755        }
8756
8757        @Override
8758        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8759            return filter.activity;
8760        }
8761
8762        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8763            PackageParser.Activity activity = (PackageParser.Activity)label;
8764            out.print(prefix); out.print(
8765                    Integer.toHexString(System.identityHashCode(activity)));
8766                    out.print(' ');
8767                    activity.printComponentShortName(out);
8768            if (count > 1) {
8769                out.print(" ("); out.print(count); out.print(" filters)");
8770            }
8771            out.println();
8772        }
8773
8774//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8775//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8776//            final List<ResolveInfo> retList = Lists.newArrayList();
8777//            while (i.hasNext()) {
8778//                final ResolveInfo resolveInfo = i.next();
8779//                if (isEnabledLP(resolveInfo.activityInfo)) {
8780//                    retList.add(resolveInfo);
8781//                }
8782//            }
8783//            return retList;
8784//        }
8785
8786        // Keys are String (activity class name), values are Activity.
8787        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8788                = new ArrayMap<ComponentName, PackageParser.Activity>();
8789        private int mFlags;
8790    }
8791
8792    private final class ServiceIntentResolver
8793            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8794        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8795                boolean defaultOnly, int userId) {
8796            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8797            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8798        }
8799
8800        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8801                int userId) {
8802            if (!sUserManager.exists(userId)) return null;
8803            mFlags = flags;
8804            return super.queryIntent(intent, resolvedType,
8805                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8806        }
8807
8808        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8809                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8810            if (!sUserManager.exists(userId)) return null;
8811            if (packageServices == null) {
8812                return null;
8813            }
8814            mFlags = flags;
8815            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8816            final int N = packageServices.size();
8817            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8818                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8819
8820            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8821            for (int i = 0; i < N; ++i) {
8822                intentFilters = packageServices.get(i).intents;
8823                if (intentFilters != null && intentFilters.size() > 0) {
8824                    PackageParser.ServiceIntentInfo[] array =
8825                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8826                    intentFilters.toArray(array);
8827                    listCut.add(array);
8828                }
8829            }
8830            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8831        }
8832
8833        public final void addService(PackageParser.Service s) {
8834            mServices.put(s.getComponentName(), s);
8835            if (DEBUG_SHOW_INFO) {
8836                Log.v(TAG, "  "
8837                        + (s.info.nonLocalizedLabel != null
8838                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8839                Log.v(TAG, "    Class=" + s.info.name);
8840            }
8841            final int NI = s.intents.size();
8842            int j;
8843            for (j=0; j<NI; j++) {
8844                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8845                if (DEBUG_SHOW_INFO) {
8846                    Log.v(TAG, "    IntentFilter:");
8847                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8848                }
8849                if (!intent.debugCheck()) {
8850                    Log.w(TAG, "==> For Service " + s.info.name);
8851                }
8852                addFilter(intent);
8853            }
8854        }
8855
8856        public final void removeService(PackageParser.Service s) {
8857            mServices.remove(s.getComponentName());
8858            if (DEBUG_SHOW_INFO) {
8859                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8860                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8861                Log.v(TAG, "    Class=" + s.info.name);
8862            }
8863            final int NI = s.intents.size();
8864            int j;
8865            for (j=0; j<NI; j++) {
8866                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8867                if (DEBUG_SHOW_INFO) {
8868                    Log.v(TAG, "    IntentFilter:");
8869                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8870                }
8871                removeFilter(intent);
8872            }
8873        }
8874
8875        @Override
8876        protected boolean allowFilterResult(
8877                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8878            ServiceInfo filterSi = filter.service.info;
8879            for (int i=dest.size()-1; i>=0; i--) {
8880                ServiceInfo destAi = dest.get(i).serviceInfo;
8881                if (destAi.name == filterSi.name
8882                        && destAi.packageName == filterSi.packageName) {
8883                    return false;
8884                }
8885            }
8886            return true;
8887        }
8888
8889        @Override
8890        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8891            return new PackageParser.ServiceIntentInfo[size];
8892        }
8893
8894        @Override
8895        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8896            if (!sUserManager.exists(userId)) return true;
8897            PackageParser.Package p = filter.service.owner;
8898            if (p != null) {
8899                PackageSetting ps = (PackageSetting)p.mExtras;
8900                if (ps != null) {
8901                    // System apps are never considered stopped for purposes of
8902                    // filtering, because there may be no way for the user to
8903                    // actually re-launch them.
8904                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8905                            && ps.getStopped(userId);
8906                }
8907            }
8908            return false;
8909        }
8910
8911        @Override
8912        protected boolean isPackageForFilter(String packageName,
8913                PackageParser.ServiceIntentInfo info) {
8914            return packageName.equals(info.service.owner.packageName);
8915        }
8916
8917        @Override
8918        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8919                int match, int userId) {
8920            if (!sUserManager.exists(userId)) return null;
8921            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8922            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8923                return null;
8924            }
8925            final PackageParser.Service service = info.service;
8926            if (mSafeMode && (service.info.applicationInfo.flags
8927                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8928                return null;
8929            }
8930            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8931            if (ps == null) {
8932                return null;
8933            }
8934            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8935                    ps.readUserState(userId), userId);
8936            if (si == null) {
8937                return null;
8938            }
8939            final ResolveInfo res = new ResolveInfo();
8940            res.serviceInfo = si;
8941            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8942                res.filter = filter;
8943            }
8944            res.priority = info.getPriority();
8945            res.preferredOrder = service.owner.mPreferredOrder;
8946            res.match = match;
8947            res.isDefault = info.hasDefault;
8948            res.labelRes = info.labelRes;
8949            res.nonLocalizedLabel = info.nonLocalizedLabel;
8950            res.icon = info.icon;
8951            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8952            return res;
8953        }
8954
8955        @Override
8956        protected void sortResults(List<ResolveInfo> results) {
8957            Collections.sort(results, mResolvePrioritySorter);
8958        }
8959
8960        @Override
8961        protected void dumpFilter(PrintWriter out, String prefix,
8962                PackageParser.ServiceIntentInfo filter) {
8963            out.print(prefix); out.print(
8964                    Integer.toHexString(System.identityHashCode(filter.service)));
8965                    out.print(' ');
8966                    filter.service.printComponentShortName(out);
8967                    out.print(" filter ");
8968                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8969        }
8970
8971        @Override
8972        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8973            return filter.service;
8974        }
8975
8976        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8977            PackageParser.Service service = (PackageParser.Service)label;
8978            out.print(prefix); out.print(
8979                    Integer.toHexString(System.identityHashCode(service)));
8980                    out.print(' ');
8981                    service.printComponentShortName(out);
8982            if (count > 1) {
8983                out.print(" ("); out.print(count); out.print(" filters)");
8984            }
8985            out.println();
8986        }
8987
8988//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8989//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8990//            final List<ResolveInfo> retList = Lists.newArrayList();
8991//            while (i.hasNext()) {
8992//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8993//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8994//                    retList.add(resolveInfo);
8995//                }
8996//            }
8997//            return retList;
8998//        }
8999
9000        // Keys are String (activity class name), values are Activity.
9001        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9002                = new ArrayMap<ComponentName, PackageParser.Service>();
9003        private int mFlags;
9004    };
9005
9006    private final class ProviderIntentResolver
9007            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9008        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9009                boolean defaultOnly, int userId) {
9010            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9011            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9012        }
9013
9014        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9015                int userId) {
9016            if (!sUserManager.exists(userId))
9017                return null;
9018            mFlags = flags;
9019            return super.queryIntent(intent, resolvedType,
9020                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9021        }
9022
9023        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9024                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9025            if (!sUserManager.exists(userId))
9026                return null;
9027            if (packageProviders == null) {
9028                return null;
9029            }
9030            mFlags = flags;
9031            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9032            final int N = packageProviders.size();
9033            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9034                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9035
9036            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9037            for (int i = 0; i < N; ++i) {
9038                intentFilters = packageProviders.get(i).intents;
9039                if (intentFilters != null && intentFilters.size() > 0) {
9040                    PackageParser.ProviderIntentInfo[] array =
9041                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9042                    intentFilters.toArray(array);
9043                    listCut.add(array);
9044                }
9045            }
9046            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9047        }
9048
9049        public final void addProvider(PackageParser.Provider p) {
9050            if (mProviders.containsKey(p.getComponentName())) {
9051                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9052                return;
9053            }
9054
9055            mProviders.put(p.getComponentName(), p);
9056            if (DEBUG_SHOW_INFO) {
9057                Log.v(TAG, "  "
9058                        + (p.info.nonLocalizedLabel != null
9059                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9060                Log.v(TAG, "    Class=" + p.info.name);
9061            }
9062            final int NI = p.intents.size();
9063            int j;
9064            for (j = 0; j < NI; j++) {
9065                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9066                if (DEBUG_SHOW_INFO) {
9067                    Log.v(TAG, "    IntentFilter:");
9068                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9069                }
9070                if (!intent.debugCheck()) {
9071                    Log.w(TAG, "==> For Provider " + p.info.name);
9072                }
9073                addFilter(intent);
9074            }
9075        }
9076
9077        public final void removeProvider(PackageParser.Provider p) {
9078            mProviders.remove(p.getComponentName());
9079            if (DEBUG_SHOW_INFO) {
9080                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9081                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9082                Log.v(TAG, "    Class=" + p.info.name);
9083            }
9084            final int NI = p.intents.size();
9085            int j;
9086            for (j = 0; j < NI; j++) {
9087                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9088                if (DEBUG_SHOW_INFO) {
9089                    Log.v(TAG, "    IntentFilter:");
9090                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9091                }
9092                removeFilter(intent);
9093            }
9094        }
9095
9096        @Override
9097        protected boolean allowFilterResult(
9098                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9099            ProviderInfo filterPi = filter.provider.info;
9100            for (int i = dest.size() - 1; i >= 0; i--) {
9101                ProviderInfo destPi = dest.get(i).providerInfo;
9102                if (destPi.name == filterPi.name
9103                        && destPi.packageName == filterPi.packageName) {
9104                    return false;
9105                }
9106            }
9107            return true;
9108        }
9109
9110        @Override
9111        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9112            return new PackageParser.ProviderIntentInfo[size];
9113        }
9114
9115        @Override
9116        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9117            if (!sUserManager.exists(userId))
9118                return true;
9119            PackageParser.Package p = filter.provider.owner;
9120            if (p != null) {
9121                PackageSetting ps = (PackageSetting) p.mExtras;
9122                if (ps != null) {
9123                    // System apps are never considered stopped for purposes of
9124                    // filtering, because there may be no way for the user to
9125                    // actually re-launch them.
9126                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9127                            && ps.getStopped(userId);
9128                }
9129            }
9130            return false;
9131        }
9132
9133        @Override
9134        protected boolean isPackageForFilter(String packageName,
9135                PackageParser.ProviderIntentInfo info) {
9136            return packageName.equals(info.provider.owner.packageName);
9137        }
9138
9139        @Override
9140        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9141                int match, int userId) {
9142            if (!sUserManager.exists(userId))
9143                return null;
9144            final PackageParser.ProviderIntentInfo info = filter;
9145            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9146                return null;
9147            }
9148            final PackageParser.Provider provider = info.provider;
9149            if (mSafeMode && (provider.info.applicationInfo.flags
9150                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9151                return null;
9152            }
9153            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9154            if (ps == null) {
9155                return null;
9156            }
9157            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9158                    ps.readUserState(userId), userId);
9159            if (pi == null) {
9160                return null;
9161            }
9162            final ResolveInfo res = new ResolveInfo();
9163            res.providerInfo = pi;
9164            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9165                res.filter = filter;
9166            }
9167            res.priority = info.getPriority();
9168            res.preferredOrder = provider.owner.mPreferredOrder;
9169            res.match = match;
9170            res.isDefault = info.hasDefault;
9171            res.labelRes = info.labelRes;
9172            res.nonLocalizedLabel = info.nonLocalizedLabel;
9173            res.icon = info.icon;
9174            res.system = res.providerInfo.applicationInfo.isSystemApp();
9175            return res;
9176        }
9177
9178        @Override
9179        protected void sortResults(List<ResolveInfo> results) {
9180            Collections.sort(results, mResolvePrioritySorter);
9181        }
9182
9183        @Override
9184        protected void dumpFilter(PrintWriter out, String prefix,
9185                PackageParser.ProviderIntentInfo filter) {
9186            out.print(prefix);
9187            out.print(
9188                    Integer.toHexString(System.identityHashCode(filter.provider)));
9189            out.print(' ');
9190            filter.provider.printComponentShortName(out);
9191            out.print(" filter ");
9192            out.println(Integer.toHexString(System.identityHashCode(filter)));
9193        }
9194
9195        @Override
9196        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9197            return filter.provider;
9198        }
9199
9200        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9201            PackageParser.Provider provider = (PackageParser.Provider)label;
9202            out.print(prefix); out.print(
9203                    Integer.toHexString(System.identityHashCode(provider)));
9204                    out.print(' ');
9205                    provider.printComponentShortName(out);
9206            if (count > 1) {
9207                out.print(" ("); out.print(count); out.print(" filters)");
9208            }
9209            out.println();
9210        }
9211
9212        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9213                = new ArrayMap<ComponentName, PackageParser.Provider>();
9214        private int mFlags;
9215    };
9216
9217    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9218            new Comparator<ResolveInfo>() {
9219        public int compare(ResolveInfo r1, ResolveInfo r2) {
9220            int v1 = r1.priority;
9221            int v2 = r2.priority;
9222            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9223            if (v1 != v2) {
9224                return (v1 > v2) ? -1 : 1;
9225            }
9226            v1 = r1.preferredOrder;
9227            v2 = r2.preferredOrder;
9228            if (v1 != v2) {
9229                return (v1 > v2) ? -1 : 1;
9230            }
9231            if (r1.isDefault != r2.isDefault) {
9232                return r1.isDefault ? -1 : 1;
9233            }
9234            v1 = r1.match;
9235            v2 = r2.match;
9236            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9237            if (v1 != v2) {
9238                return (v1 > v2) ? -1 : 1;
9239            }
9240            if (r1.system != r2.system) {
9241                return r1.system ? -1 : 1;
9242            }
9243            return 0;
9244        }
9245    };
9246
9247    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9248            new Comparator<ProviderInfo>() {
9249        public int compare(ProviderInfo p1, ProviderInfo p2) {
9250            final int v1 = p1.initOrder;
9251            final int v2 = p2.initOrder;
9252            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9253        }
9254    };
9255
9256    final void sendPackageBroadcast(final String action, final String pkg,
9257            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9258            final int[] userIds) {
9259        mHandler.post(new Runnable() {
9260            @Override
9261            public void run() {
9262                try {
9263                    final IActivityManager am = ActivityManagerNative.getDefault();
9264                    if (am == null) return;
9265                    final int[] resolvedUserIds;
9266                    if (userIds == null) {
9267                        resolvedUserIds = am.getRunningUserIds();
9268                    } else {
9269                        resolvedUserIds = userIds;
9270                    }
9271                    for (int id : resolvedUserIds) {
9272                        final Intent intent = new Intent(action,
9273                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9274                        if (extras != null) {
9275                            intent.putExtras(extras);
9276                        }
9277                        if (targetPkg != null) {
9278                            intent.setPackage(targetPkg);
9279                        }
9280                        // Modify the UID when posting to other users
9281                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9282                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9283                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9284                            intent.putExtra(Intent.EXTRA_UID, uid);
9285                        }
9286                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9287                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9288                        if (DEBUG_BROADCASTS) {
9289                            RuntimeException here = new RuntimeException("here");
9290                            here.fillInStackTrace();
9291                            Slog.d(TAG, "Sending to user " + id + ": "
9292                                    + intent.toShortString(false, true, false, false)
9293                                    + " " + intent.getExtras(), here);
9294                        }
9295                        am.broadcastIntent(null, intent, null, finishedReceiver,
9296                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9297                                null, finishedReceiver != null, false, id);
9298                    }
9299                } catch (RemoteException ex) {
9300                }
9301            }
9302        });
9303    }
9304
9305    /**
9306     * Check if the external storage media is available. This is true if there
9307     * is a mounted external storage medium or if the external storage is
9308     * emulated.
9309     */
9310    private boolean isExternalMediaAvailable() {
9311        return mMediaMounted || Environment.isExternalStorageEmulated();
9312    }
9313
9314    @Override
9315    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9316        // writer
9317        synchronized (mPackages) {
9318            if (!isExternalMediaAvailable()) {
9319                // If the external storage is no longer mounted at this point,
9320                // the caller may not have been able to delete all of this
9321                // packages files and can not delete any more.  Bail.
9322                return null;
9323            }
9324            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9325            if (lastPackage != null) {
9326                pkgs.remove(lastPackage);
9327            }
9328            if (pkgs.size() > 0) {
9329                return pkgs.get(0);
9330            }
9331        }
9332        return null;
9333    }
9334
9335    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9336        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9337                userId, andCode ? 1 : 0, packageName);
9338        if (mSystemReady) {
9339            msg.sendToTarget();
9340        } else {
9341            if (mPostSystemReadyMessages == null) {
9342                mPostSystemReadyMessages = new ArrayList<>();
9343            }
9344            mPostSystemReadyMessages.add(msg);
9345        }
9346    }
9347
9348    void startCleaningPackages() {
9349        // reader
9350        synchronized (mPackages) {
9351            if (!isExternalMediaAvailable()) {
9352                return;
9353            }
9354            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9355                return;
9356            }
9357        }
9358        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9359        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9360        IActivityManager am = ActivityManagerNative.getDefault();
9361        if (am != null) {
9362            try {
9363                am.startService(null, intent, null, mContext.getOpPackageName(),
9364                        UserHandle.USER_OWNER);
9365            } catch (RemoteException e) {
9366            }
9367        }
9368    }
9369
9370    @Override
9371    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9372            int installFlags, String installerPackageName, VerificationParams verificationParams,
9373            String packageAbiOverride) {
9374        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9375                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9376    }
9377
9378    @Override
9379    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9380            int installFlags, String installerPackageName, VerificationParams verificationParams,
9381            String packageAbiOverride, int userId) {
9382        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9383
9384        final int callingUid = Binder.getCallingUid();
9385        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9386
9387        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9388            try {
9389                if (observer != null) {
9390                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9391                }
9392            } catch (RemoteException re) {
9393            }
9394            return;
9395        }
9396
9397        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9398            installFlags |= PackageManager.INSTALL_FROM_ADB;
9399
9400        } else {
9401            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9402            // about installerPackageName.
9403
9404            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9405            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9406        }
9407
9408        UserHandle user;
9409        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9410            user = UserHandle.ALL;
9411        } else {
9412            user = new UserHandle(userId);
9413        }
9414
9415        // Only system components can circumvent runtime permissions when installing.
9416        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9417                && mContext.checkCallingOrSelfPermission(Manifest.permission
9418                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9419            throw new SecurityException("You need the "
9420                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9421                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9422        }
9423
9424        verificationParams.setInstallerUid(callingUid);
9425
9426        final File originFile = new File(originPath);
9427        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9428
9429        final Message msg = mHandler.obtainMessage(INIT_COPY);
9430        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9431                null, verificationParams, user, packageAbiOverride);
9432        mHandler.sendMessage(msg);
9433    }
9434
9435    void installStage(String packageName, File stagedDir, String stagedCid,
9436            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9437            String installerPackageName, int installerUid, UserHandle user) {
9438        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9439                params.referrerUri, installerUid, null);
9440        verifParams.setInstallerUid(installerUid);
9441
9442        final OriginInfo origin;
9443        if (stagedDir != null) {
9444            origin = OriginInfo.fromStagedFile(stagedDir);
9445        } else {
9446            origin = OriginInfo.fromStagedContainer(stagedCid);
9447        }
9448
9449        final Message msg = mHandler.obtainMessage(INIT_COPY);
9450        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9451                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9452        mHandler.sendMessage(msg);
9453    }
9454
9455    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9456        Bundle extras = new Bundle(1);
9457        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9458
9459        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9460                packageName, extras, null, null, new int[] {userId});
9461        try {
9462            IActivityManager am = ActivityManagerNative.getDefault();
9463            final boolean isSystem =
9464                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9465            if (isSystem && am.isUserRunning(userId, false)) {
9466                // The just-installed/enabled app is bundled on the system, so presumed
9467                // to be able to run automatically without needing an explicit launch.
9468                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9469                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9470                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9471                        .setPackage(packageName);
9472                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9473                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9474            }
9475        } catch (RemoteException e) {
9476            // shouldn't happen
9477            Slog.w(TAG, "Unable to bootstrap installed package", e);
9478        }
9479    }
9480
9481    @Override
9482    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9483            int userId) {
9484        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9485        PackageSetting pkgSetting;
9486        final int uid = Binder.getCallingUid();
9487        enforceCrossUserPermission(uid, userId, true, true,
9488                "setApplicationHiddenSetting for user " + userId);
9489
9490        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9491            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9492            return false;
9493        }
9494
9495        long callingId = Binder.clearCallingIdentity();
9496        try {
9497            boolean sendAdded = false;
9498            boolean sendRemoved = false;
9499            // writer
9500            synchronized (mPackages) {
9501                pkgSetting = mSettings.mPackages.get(packageName);
9502                if (pkgSetting == null) {
9503                    return false;
9504                }
9505                if (pkgSetting.getHidden(userId) != hidden) {
9506                    pkgSetting.setHidden(hidden, userId);
9507                    mSettings.writePackageRestrictionsLPr(userId);
9508                    if (hidden) {
9509                        sendRemoved = true;
9510                    } else {
9511                        sendAdded = true;
9512                    }
9513                }
9514            }
9515            if (sendAdded) {
9516                sendPackageAddedForUser(packageName, pkgSetting, userId);
9517                return true;
9518            }
9519            if (sendRemoved) {
9520                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9521                        "hiding pkg");
9522                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9523            }
9524        } finally {
9525            Binder.restoreCallingIdentity(callingId);
9526        }
9527        return false;
9528    }
9529
9530    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9531            int userId) {
9532        final PackageRemovedInfo info = new PackageRemovedInfo();
9533        info.removedPackage = packageName;
9534        info.removedUsers = new int[] {userId};
9535        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9536        info.sendBroadcast(false, false, false);
9537    }
9538
9539    /**
9540     * Returns true if application is not found or there was an error. Otherwise it returns
9541     * the hidden state of the package for the given user.
9542     */
9543    @Override
9544    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9545        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9546        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9547                false, "getApplicationHidden for user " + userId);
9548        PackageSetting pkgSetting;
9549        long callingId = Binder.clearCallingIdentity();
9550        try {
9551            // writer
9552            synchronized (mPackages) {
9553                pkgSetting = mSettings.mPackages.get(packageName);
9554                if (pkgSetting == null) {
9555                    return true;
9556                }
9557                return pkgSetting.getHidden(userId);
9558            }
9559        } finally {
9560            Binder.restoreCallingIdentity(callingId);
9561        }
9562    }
9563
9564    /**
9565     * @hide
9566     */
9567    @Override
9568    public int installExistingPackageAsUser(String packageName, int userId) {
9569        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9570                null);
9571        PackageSetting pkgSetting;
9572        final int uid = Binder.getCallingUid();
9573        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9574                + userId);
9575        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9576            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9577        }
9578
9579        long callingId = Binder.clearCallingIdentity();
9580        try {
9581            boolean sendAdded = false;
9582
9583            // writer
9584            synchronized (mPackages) {
9585                pkgSetting = mSettings.mPackages.get(packageName);
9586                if (pkgSetting == null) {
9587                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9588                }
9589                if (!pkgSetting.getInstalled(userId)) {
9590                    pkgSetting.setInstalled(true, userId);
9591                    pkgSetting.setHidden(false, userId);
9592                    mSettings.writePackageRestrictionsLPr(userId);
9593                    sendAdded = true;
9594                }
9595            }
9596
9597            if (sendAdded) {
9598                sendPackageAddedForUser(packageName, pkgSetting, userId);
9599            }
9600        } finally {
9601            Binder.restoreCallingIdentity(callingId);
9602        }
9603
9604        return PackageManager.INSTALL_SUCCEEDED;
9605    }
9606
9607    boolean isUserRestricted(int userId, String restrictionKey) {
9608        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9609        if (restrictions.getBoolean(restrictionKey, false)) {
9610            Log.w(TAG, "User is restricted: " + restrictionKey);
9611            return true;
9612        }
9613        return false;
9614    }
9615
9616    @Override
9617    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9618        mContext.enforceCallingOrSelfPermission(
9619                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9620                "Only package verification agents can verify applications");
9621
9622        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9623        final PackageVerificationResponse response = new PackageVerificationResponse(
9624                verificationCode, Binder.getCallingUid());
9625        msg.arg1 = id;
9626        msg.obj = response;
9627        mHandler.sendMessage(msg);
9628    }
9629
9630    @Override
9631    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9632            long millisecondsToDelay) {
9633        mContext.enforceCallingOrSelfPermission(
9634                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9635                "Only package verification agents can extend verification timeouts");
9636
9637        final PackageVerificationState state = mPendingVerification.get(id);
9638        final PackageVerificationResponse response = new PackageVerificationResponse(
9639                verificationCodeAtTimeout, Binder.getCallingUid());
9640
9641        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9642            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9643        }
9644        if (millisecondsToDelay < 0) {
9645            millisecondsToDelay = 0;
9646        }
9647        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9648                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9649            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9650        }
9651
9652        if ((state != null) && !state.timeoutExtended()) {
9653            state.extendTimeout();
9654
9655            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9656            msg.arg1 = id;
9657            msg.obj = response;
9658            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9659        }
9660    }
9661
9662    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9663            int verificationCode, UserHandle user) {
9664        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9665        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9666        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9667        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9668        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9669
9670        mContext.sendBroadcastAsUser(intent, user,
9671                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9672    }
9673
9674    private ComponentName matchComponentForVerifier(String packageName,
9675            List<ResolveInfo> receivers) {
9676        ActivityInfo targetReceiver = null;
9677
9678        final int NR = receivers.size();
9679        for (int i = 0; i < NR; i++) {
9680            final ResolveInfo info = receivers.get(i);
9681            if (info.activityInfo == null) {
9682                continue;
9683            }
9684
9685            if (packageName.equals(info.activityInfo.packageName)) {
9686                targetReceiver = info.activityInfo;
9687                break;
9688            }
9689        }
9690
9691        if (targetReceiver == null) {
9692            return null;
9693        }
9694
9695        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9696    }
9697
9698    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9699            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9700        if (pkgInfo.verifiers.length == 0) {
9701            return null;
9702        }
9703
9704        final int N = pkgInfo.verifiers.length;
9705        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9706        for (int i = 0; i < N; i++) {
9707            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9708
9709            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9710                    receivers);
9711            if (comp == null) {
9712                continue;
9713            }
9714
9715            final int verifierUid = getUidForVerifier(verifierInfo);
9716            if (verifierUid == -1) {
9717                continue;
9718            }
9719
9720            if (DEBUG_VERIFY) {
9721                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9722                        + " with the correct signature");
9723            }
9724            sufficientVerifiers.add(comp);
9725            verificationState.addSufficientVerifier(verifierUid);
9726        }
9727
9728        return sufficientVerifiers;
9729    }
9730
9731    private int getUidForVerifier(VerifierInfo verifierInfo) {
9732        synchronized (mPackages) {
9733            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9734            if (pkg == null) {
9735                return -1;
9736            } else if (pkg.mSignatures.length != 1) {
9737                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9738                        + " has more than one signature; ignoring");
9739                return -1;
9740            }
9741
9742            /*
9743             * If the public key of the package's signature does not match
9744             * our expected public key, then this is a different package and
9745             * we should skip.
9746             */
9747
9748            final byte[] expectedPublicKey;
9749            try {
9750                final Signature verifierSig = pkg.mSignatures[0];
9751                final PublicKey publicKey = verifierSig.getPublicKey();
9752                expectedPublicKey = publicKey.getEncoded();
9753            } catch (CertificateException e) {
9754                return -1;
9755            }
9756
9757            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9758
9759            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9760                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9761                        + " does not have the expected public key; ignoring");
9762                return -1;
9763            }
9764
9765            return pkg.applicationInfo.uid;
9766        }
9767    }
9768
9769    @Override
9770    public void finishPackageInstall(int token) {
9771        enforceSystemOrRoot("Only the system is allowed to finish installs");
9772
9773        if (DEBUG_INSTALL) {
9774            Slog.v(TAG, "BM finishing package install for " + token);
9775        }
9776
9777        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9778        mHandler.sendMessage(msg);
9779    }
9780
9781    /**
9782     * Get the verification agent timeout.
9783     *
9784     * @return verification timeout in milliseconds
9785     */
9786    private long getVerificationTimeout() {
9787        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9788                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9789                DEFAULT_VERIFICATION_TIMEOUT);
9790    }
9791
9792    /**
9793     * Get the default verification agent response code.
9794     *
9795     * @return default verification response code
9796     */
9797    private int getDefaultVerificationResponse() {
9798        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9799                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9800                DEFAULT_VERIFICATION_RESPONSE);
9801    }
9802
9803    /**
9804     * Check whether or not package verification has been enabled.
9805     *
9806     * @return true if verification should be performed
9807     */
9808    private boolean isVerificationEnabled(int userId, int installFlags) {
9809        if (!DEFAULT_VERIFY_ENABLE) {
9810            return false;
9811        }
9812
9813        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9814
9815        // Check if installing from ADB
9816        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9817            // Do not run verification in a test harness environment
9818            if (ActivityManager.isRunningInTestHarness()) {
9819                return false;
9820            }
9821            if (ensureVerifyAppsEnabled) {
9822                return true;
9823            }
9824            // Check if the developer does not want package verification for ADB installs
9825            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9826                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9827                return false;
9828            }
9829        }
9830
9831        if (ensureVerifyAppsEnabled) {
9832            return true;
9833        }
9834
9835        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9836                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9837    }
9838
9839    @Override
9840    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9841            throws RemoteException {
9842        mContext.enforceCallingOrSelfPermission(
9843                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9844                "Only intentfilter verification agents can verify applications");
9845
9846        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9847        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9848                Binder.getCallingUid(), verificationCode, failedDomains);
9849        msg.arg1 = id;
9850        msg.obj = response;
9851        mHandler.sendMessage(msg);
9852    }
9853
9854    @Override
9855    public int getIntentVerificationStatus(String packageName, int userId) {
9856        synchronized (mPackages) {
9857            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9858        }
9859    }
9860
9861    @Override
9862    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9863        mContext.enforceCallingOrSelfPermission(
9864                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9865
9866        boolean result = false;
9867        synchronized (mPackages) {
9868            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9869        }
9870        if (result) {
9871            scheduleWritePackageRestrictionsLocked(userId);
9872        }
9873        return result;
9874    }
9875
9876    @Override
9877    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9878        synchronized (mPackages) {
9879            return mSettings.getIntentFilterVerificationsLPr(packageName);
9880        }
9881    }
9882
9883    @Override
9884    public List<IntentFilter> getAllIntentFilters(String packageName) {
9885        if (TextUtils.isEmpty(packageName)) {
9886            return Collections.<IntentFilter>emptyList();
9887        }
9888        synchronized (mPackages) {
9889            PackageParser.Package pkg = mPackages.get(packageName);
9890            if (pkg == null || pkg.activities == null) {
9891                return Collections.<IntentFilter>emptyList();
9892            }
9893            final int count = pkg.activities.size();
9894            ArrayList<IntentFilter> result = new ArrayList<>();
9895            for (int n=0; n<count; n++) {
9896                PackageParser.Activity activity = pkg.activities.get(n);
9897                if (activity.intents != null || activity.intents.size() > 0) {
9898                    result.addAll(activity.intents);
9899                }
9900            }
9901            return result;
9902        }
9903    }
9904
9905    @Override
9906    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9907        mContext.enforceCallingOrSelfPermission(
9908                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9909
9910        synchronized (mPackages) {
9911            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9912            if (packageName != null) {
9913                result |= updateIntentVerificationStatus(packageName,
9914                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9915                        UserHandle.myUserId());
9916                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9917                        packageName, userId);
9918            }
9919            return result;
9920        }
9921    }
9922
9923    @Override
9924    public String getDefaultBrowserPackageName(int userId) {
9925        synchronized (mPackages) {
9926            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9927        }
9928    }
9929
9930    /**
9931     * Get the "allow unknown sources" setting.
9932     *
9933     * @return the current "allow unknown sources" setting
9934     */
9935    private int getUnknownSourcesSettings() {
9936        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9937                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9938                -1);
9939    }
9940
9941    @Override
9942    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9943        final int uid = Binder.getCallingUid();
9944        // writer
9945        synchronized (mPackages) {
9946            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9947            if (targetPackageSetting == null) {
9948                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9949            }
9950
9951            PackageSetting installerPackageSetting;
9952            if (installerPackageName != null) {
9953                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9954                if (installerPackageSetting == null) {
9955                    throw new IllegalArgumentException("Unknown installer package: "
9956                            + installerPackageName);
9957                }
9958            } else {
9959                installerPackageSetting = null;
9960            }
9961
9962            Signature[] callerSignature;
9963            Object obj = mSettings.getUserIdLPr(uid);
9964            if (obj != null) {
9965                if (obj instanceof SharedUserSetting) {
9966                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9967                } else if (obj instanceof PackageSetting) {
9968                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9969                } else {
9970                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9971                }
9972            } else {
9973                throw new SecurityException("Unknown calling uid " + uid);
9974            }
9975
9976            // Verify: can't set installerPackageName to a package that is
9977            // not signed with the same cert as the caller.
9978            if (installerPackageSetting != null) {
9979                if (compareSignatures(callerSignature,
9980                        installerPackageSetting.signatures.mSignatures)
9981                        != PackageManager.SIGNATURE_MATCH) {
9982                    throw new SecurityException(
9983                            "Caller does not have same cert as new installer package "
9984                            + installerPackageName);
9985                }
9986            }
9987
9988            // Verify: if target already has an installer package, it must
9989            // be signed with the same cert as the caller.
9990            if (targetPackageSetting.installerPackageName != null) {
9991                PackageSetting setting = mSettings.mPackages.get(
9992                        targetPackageSetting.installerPackageName);
9993                // If the currently set package isn't valid, then it's always
9994                // okay to change it.
9995                if (setting != null) {
9996                    if (compareSignatures(callerSignature,
9997                            setting.signatures.mSignatures)
9998                            != PackageManager.SIGNATURE_MATCH) {
9999                        throw new SecurityException(
10000                                "Caller does not have same cert as old installer package "
10001                                + targetPackageSetting.installerPackageName);
10002                    }
10003                }
10004            }
10005
10006            // Okay!
10007            targetPackageSetting.installerPackageName = installerPackageName;
10008            scheduleWriteSettingsLocked();
10009        }
10010    }
10011
10012    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10013        // Queue up an async operation since the package installation may take a little while.
10014        mHandler.post(new Runnable() {
10015            public void run() {
10016                mHandler.removeCallbacks(this);
10017                 // Result object to be returned
10018                PackageInstalledInfo res = new PackageInstalledInfo();
10019                res.returnCode = currentStatus;
10020                res.uid = -1;
10021                res.pkg = null;
10022                res.removedInfo = new PackageRemovedInfo();
10023                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10024                    args.doPreInstall(res.returnCode);
10025                    synchronized (mInstallLock) {
10026                        installPackageLI(args, res);
10027                    }
10028                    args.doPostInstall(res.returnCode, res.uid);
10029                }
10030
10031                // A restore should be performed at this point if (a) the install
10032                // succeeded, (b) the operation is not an update, and (c) the new
10033                // package has not opted out of backup participation.
10034                final boolean update = res.removedInfo.removedPackage != null;
10035                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10036                boolean doRestore = !update
10037                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10038
10039                // Set up the post-install work request bookkeeping.  This will be used
10040                // and cleaned up by the post-install event handling regardless of whether
10041                // there's a restore pass performed.  Token values are >= 1.
10042                int token;
10043                if (mNextInstallToken < 0) mNextInstallToken = 1;
10044                token = mNextInstallToken++;
10045
10046                PostInstallData data = new PostInstallData(args, res);
10047                mRunningInstalls.put(token, data);
10048                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10049
10050                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10051                    // Pass responsibility to the Backup Manager.  It will perform a
10052                    // restore if appropriate, then pass responsibility back to the
10053                    // Package Manager to run the post-install observer callbacks
10054                    // and broadcasts.
10055                    IBackupManager bm = IBackupManager.Stub.asInterface(
10056                            ServiceManager.getService(Context.BACKUP_SERVICE));
10057                    if (bm != null) {
10058                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10059                                + " to BM for possible restore");
10060                        try {
10061                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10062                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10063                            } else {
10064                                doRestore = false;
10065                            }
10066                        } catch (RemoteException e) {
10067                            // can't happen; the backup manager is local
10068                        } catch (Exception e) {
10069                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10070                            doRestore = false;
10071                        }
10072                    } else {
10073                        Slog.e(TAG, "Backup Manager not found!");
10074                        doRestore = false;
10075                    }
10076                }
10077
10078                if (!doRestore) {
10079                    // No restore possible, or the Backup Manager was mysteriously not
10080                    // available -- just fire the post-install work request directly.
10081                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10082                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10083                    mHandler.sendMessage(msg);
10084                }
10085            }
10086        });
10087    }
10088
10089    private abstract class HandlerParams {
10090        private static final int MAX_RETRIES = 4;
10091
10092        /**
10093         * Number of times startCopy() has been attempted and had a non-fatal
10094         * error.
10095         */
10096        private int mRetries = 0;
10097
10098        /** User handle for the user requesting the information or installation. */
10099        private final UserHandle mUser;
10100
10101        HandlerParams(UserHandle user) {
10102            mUser = user;
10103        }
10104
10105        UserHandle getUser() {
10106            return mUser;
10107        }
10108
10109        final boolean startCopy() {
10110            boolean res;
10111            try {
10112                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10113
10114                if (++mRetries > MAX_RETRIES) {
10115                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10116                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10117                    handleServiceError();
10118                    return false;
10119                } else {
10120                    handleStartCopy();
10121                    res = true;
10122                }
10123            } catch (RemoteException e) {
10124                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10125                mHandler.sendEmptyMessage(MCS_RECONNECT);
10126                res = false;
10127            }
10128            handleReturnCode();
10129            return res;
10130        }
10131
10132        final void serviceError() {
10133            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10134            handleServiceError();
10135            handleReturnCode();
10136        }
10137
10138        abstract void handleStartCopy() throws RemoteException;
10139        abstract void handleServiceError();
10140        abstract void handleReturnCode();
10141    }
10142
10143    class MeasureParams extends HandlerParams {
10144        private final PackageStats mStats;
10145        private boolean mSuccess;
10146
10147        private final IPackageStatsObserver mObserver;
10148
10149        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10150            super(new UserHandle(stats.userHandle));
10151            mObserver = observer;
10152            mStats = stats;
10153        }
10154
10155        @Override
10156        public String toString() {
10157            return "MeasureParams{"
10158                + Integer.toHexString(System.identityHashCode(this))
10159                + " " + mStats.packageName + "}";
10160        }
10161
10162        @Override
10163        void handleStartCopy() throws RemoteException {
10164            synchronized (mInstallLock) {
10165                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10166            }
10167
10168            if (mSuccess) {
10169                final boolean mounted;
10170                if (Environment.isExternalStorageEmulated()) {
10171                    mounted = true;
10172                } else {
10173                    final String status = Environment.getExternalStorageState();
10174                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10175                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10176                }
10177
10178                if (mounted) {
10179                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10180
10181                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10182                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10183
10184                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10185                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10186
10187                    // Always subtract cache size, since it's a subdirectory
10188                    mStats.externalDataSize -= mStats.externalCacheSize;
10189
10190                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10191                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10192
10193                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10194                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10195                }
10196            }
10197        }
10198
10199        @Override
10200        void handleReturnCode() {
10201            if (mObserver != null) {
10202                try {
10203                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10204                } catch (RemoteException e) {
10205                    Slog.i(TAG, "Observer no longer exists.");
10206                }
10207            }
10208        }
10209
10210        @Override
10211        void handleServiceError() {
10212            Slog.e(TAG, "Could not measure application " + mStats.packageName
10213                            + " external storage");
10214        }
10215    }
10216
10217    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10218            throws RemoteException {
10219        long result = 0;
10220        for (File path : paths) {
10221            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10222        }
10223        return result;
10224    }
10225
10226    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10227        for (File path : paths) {
10228            try {
10229                mcs.clearDirectory(path.getAbsolutePath());
10230            } catch (RemoteException e) {
10231            }
10232        }
10233    }
10234
10235    static class OriginInfo {
10236        /**
10237         * Location where install is coming from, before it has been
10238         * copied/renamed into place. This could be a single monolithic APK
10239         * file, or a cluster directory. This location may be untrusted.
10240         */
10241        final File file;
10242        final String cid;
10243
10244        /**
10245         * Flag indicating that {@link #file} or {@link #cid} has already been
10246         * staged, meaning downstream users don't need to defensively copy the
10247         * contents.
10248         */
10249        final boolean staged;
10250
10251        /**
10252         * Flag indicating that {@link #file} or {@link #cid} is an already
10253         * installed app that is being moved.
10254         */
10255        final boolean existing;
10256
10257        final String resolvedPath;
10258        final File resolvedFile;
10259
10260        static OriginInfo fromNothing() {
10261            return new OriginInfo(null, null, false, false);
10262        }
10263
10264        static OriginInfo fromUntrustedFile(File file) {
10265            return new OriginInfo(file, null, false, false);
10266        }
10267
10268        static OriginInfo fromExistingFile(File file) {
10269            return new OriginInfo(file, null, false, true);
10270        }
10271
10272        static OriginInfo fromStagedFile(File file) {
10273            return new OriginInfo(file, null, true, false);
10274        }
10275
10276        static OriginInfo fromStagedContainer(String cid) {
10277            return new OriginInfo(null, cid, true, false);
10278        }
10279
10280        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10281            this.file = file;
10282            this.cid = cid;
10283            this.staged = staged;
10284            this.existing = existing;
10285
10286            if (cid != null) {
10287                resolvedPath = PackageHelper.getSdDir(cid);
10288                resolvedFile = new File(resolvedPath);
10289            } else if (file != null) {
10290                resolvedPath = file.getAbsolutePath();
10291                resolvedFile = file;
10292            } else {
10293                resolvedPath = null;
10294                resolvedFile = null;
10295            }
10296        }
10297    }
10298
10299    class MoveInfo {
10300        final int moveId;
10301        final String fromUuid;
10302        final String toUuid;
10303        final String packageName;
10304        final String dataAppName;
10305        final int appId;
10306        final String seinfo;
10307
10308        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10309                String dataAppName, int appId, String seinfo) {
10310            this.moveId = moveId;
10311            this.fromUuid = fromUuid;
10312            this.toUuid = toUuid;
10313            this.packageName = packageName;
10314            this.dataAppName = dataAppName;
10315            this.appId = appId;
10316            this.seinfo = seinfo;
10317        }
10318    }
10319
10320    class InstallParams extends HandlerParams {
10321        final OriginInfo origin;
10322        final MoveInfo move;
10323        final IPackageInstallObserver2 observer;
10324        int installFlags;
10325        final String installerPackageName;
10326        final String volumeUuid;
10327        final VerificationParams verificationParams;
10328        private InstallArgs mArgs;
10329        private int mRet;
10330        final String packageAbiOverride;
10331
10332        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10333                int installFlags, String installerPackageName, String volumeUuid,
10334                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10335            super(user);
10336            this.origin = origin;
10337            this.move = move;
10338            this.observer = observer;
10339            this.installFlags = installFlags;
10340            this.installerPackageName = installerPackageName;
10341            this.volumeUuid = volumeUuid;
10342            this.verificationParams = verificationParams;
10343            this.packageAbiOverride = packageAbiOverride;
10344        }
10345
10346        @Override
10347        public String toString() {
10348            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10349                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10350        }
10351
10352        public ManifestDigest getManifestDigest() {
10353            if (verificationParams == null) {
10354                return null;
10355            }
10356            return verificationParams.getManifestDigest();
10357        }
10358
10359        private int installLocationPolicy(PackageInfoLite pkgLite) {
10360            String packageName = pkgLite.packageName;
10361            int installLocation = pkgLite.installLocation;
10362            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10363            // reader
10364            synchronized (mPackages) {
10365                PackageParser.Package pkg = mPackages.get(packageName);
10366                if (pkg != null) {
10367                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10368                        // Check for downgrading.
10369                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10370                            try {
10371                                checkDowngrade(pkg, pkgLite);
10372                            } catch (PackageManagerException e) {
10373                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10374                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10375                            }
10376                        }
10377                        // Check for updated system application.
10378                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10379                            if (onSd) {
10380                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10381                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10382                            }
10383                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10384                        } else {
10385                            if (onSd) {
10386                                // Install flag overrides everything.
10387                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10388                            }
10389                            // If current upgrade specifies particular preference
10390                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10391                                // Application explicitly specified internal.
10392                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10393                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10394                                // App explictly prefers external. Let policy decide
10395                            } else {
10396                                // Prefer previous location
10397                                if (isExternal(pkg)) {
10398                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10399                                }
10400                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10401                            }
10402                        }
10403                    } else {
10404                        // Invalid install. Return error code
10405                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10406                    }
10407                }
10408            }
10409            // All the special cases have been taken care of.
10410            // Return result based on recommended install location.
10411            if (onSd) {
10412                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10413            }
10414            return pkgLite.recommendedInstallLocation;
10415        }
10416
10417        /*
10418         * Invoke remote method to get package information and install
10419         * location values. Override install location based on default
10420         * policy if needed and then create install arguments based
10421         * on the install location.
10422         */
10423        public void handleStartCopy() throws RemoteException {
10424            int ret = PackageManager.INSTALL_SUCCEEDED;
10425
10426            // If we're already staged, we've firmly committed to an install location
10427            if (origin.staged) {
10428                if (origin.file != null) {
10429                    installFlags |= PackageManager.INSTALL_INTERNAL;
10430                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10431                } else if (origin.cid != null) {
10432                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10433                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10434                } else {
10435                    throw new IllegalStateException("Invalid stage location");
10436                }
10437            }
10438
10439            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10440            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10441
10442            PackageInfoLite pkgLite = null;
10443
10444            if (onInt && onSd) {
10445                // Check if both bits are set.
10446                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10447                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10448            } else {
10449                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10450                        packageAbiOverride);
10451
10452                /*
10453                 * If we have too little free space, try to free cache
10454                 * before giving up.
10455                 */
10456                if (!origin.staged && pkgLite.recommendedInstallLocation
10457                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10458                    // TODO: focus freeing disk space on the target device
10459                    final StorageManager storage = StorageManager.from(mContext);
10460                    final long lowThreshold = storage.getStorageLowBytes(
10461                            Environment.getDataDirectory());
10462
10463                    final long sizeBytes = mContainerService.calculateInstalledSize(
10464                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10465
10466                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10467                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10468                                installFlags, packageAbiOverride);
10469                    }
10470
10471                    /*
10472                     * The cache free must have deleted the file we
10473                     * downloaded to install.
10474                     *
10475                     * TODO: fix the "freeCache" call to not delete
10476                     *       the file we care about.
10477                     */
10478                    if (pkgLite.recommendedInstallLocation
10479                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10480                        pkgLite.recommendedInstallLocation
10481                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10482                    }
10483                }
10484            }
10485
10486            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10487                int loc = pkgLite.recommendedInstallLocation;
10488                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10489                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10490                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10491                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10492                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10493                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10494                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10495                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10496                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10497                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10498                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10499                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10500                } else {
10501                    // Override with defaults if needed.
10502                    loc = installLocationPolicy(pkgLite);
10503                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10504                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10505                    } else if (!onSd && !onInt) {
10506                        // Override install location with flags
10507                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10508                            // Set the flag to install on external media.
10509                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10510                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10511                        } else {
10512                            // Make sure the flag for installing on external
10513                            // media is unset
10514                            installFlags |= PackageManager.INSTALL_INTERNAL;
10515                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10516                        }
10517                    }
10518                }
10519            }
10520
10521            final InstallArgs args = createInstallArgs(this);
10522            mArgs = args;
10523
10524            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10525                 /*
10526                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10527                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10528                 */
10529                int userIdentifier = getUser().getIdentifier();
10530                if (userIdentifier == UserHandle.USER_ALL
10531                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10532                    userIdentifier = UserHandle.USER_OWNER;
10533                }
10534
10535                /*
10536                 * Determine if we have any installed package verifiers. If we
10537                 * do, then we'll defer to them to verify the packages.
10538                 */
10539                final int requiredUid = mRequiredVerifierPackage == null ? -1
10540                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10541                if (!origin.existing && requiredUid != -1
10542                        && isVerificationEnabled(userIdentifier, installFlags)) {
10543                    final Intent verification = new Intent(
10544                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10545                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10546                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10547                            PACKAGE_MIME_TYPE);
10548                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10549
10550                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10551                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10552                            0 /* TODO: Which userId? */);
10553
10554                    if (DEBUG_VERIFY) {
10555                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10556                                + verification.toString() + " with " + pkgLite.verifiers.length
10557                                + " optional verifiers");
10558                    }
10559
10560                    final int verificationId = mPendingVerificationToken++;
10561
10562                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10563
10564                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10565                            installerPackageName);
10566
10567                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10568                            installFlags);
10569
10570                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10571                            pkgLite.packageName);
10572
10573                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10574                            pkgLite.versionCode);
10575
10576                    if (verificationParams != null) {
10577                        if (verificationParams.getVerificationURI() != null) {
10578                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10579                                 verificationParams.getVerificationURI());
10580                        }
10581                        if (verificationParams.getOriginatingURI() != null) {
10582                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10583                                  verificationParams.getOriginatingURI());
10584                        }
10585                        if (verificationParams.getReferrer() != null) {
10586                            verification.putExtra(Intent.EXTRA_REFERRER,
10587                                  verificationParams.getReferrer());
10588                        }
10589                        if (verificationParams.getOriginatingUid() >= 0) {
10590                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10591                                  verificationParams.getOriginatingUid());
10592                        }
10593                        if (verificationParams.getInstallerUid() >= 0) {
10594                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10595                                  verificationParams.getInstallerUid());
10596                        }
10597                    }
10598
10599                    final PackageVerificationState verificationState = new PackageVerificationState(
10600                            requiredUid, args);
10601
10602                    mPendingVerification.append(verificationId, verificationState);
10603
10604                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10605                            receivers, verificationState);
10606
10607                    /*
10608                     * If any sufficient verifiers were listed in the package
10609                     * manifest, attempt to ask them.
10610                     */
10611                    if (sufficientVerifiers != null) {
10612                        final int N = sufficientVerifiers.size();
10613                        if (N == 0) {
10614                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10615                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10616                        } else {
10617                            for (int i = 0; i < N; i++) {
10618                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10619
10620                                final Intent sufficientIntent = new Intent(verification);
10621                                sufficientIntent.setComponent(verifierComponent);
10622
10623                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10624                            }
10625                        }
10626                    }
10627
10628                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10629                            mRequiredVerifierPackage, receivers);
10630                    if (ret == PackageManager.INSTALL_SUCCEEDED
10631                            && mRequiredVerifierPackage != null) {
10632                        /*
10633                         * Send the intent to the required verification agent,
10634                         * but only start the verification timeout after the
10635                         * target BroadcastReceivers have run.
10636                         */
10637                        verification.setComponent(requiredVerifierComponent);
10638                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10639                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10640                                new BroadcastReceiver() {
10641                                    @Override
10642                                    public void onReceive(Context context, Intent intent) {
10643                                        final Message msg = mHandler
10644                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10645                                        msg.arg1 = verificationId;
10646                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10647                                    }
10648                                }, null, 0, null, null);
10649
10650                        /*
10651                         * We don't want the copy to proceed until verification
10652                         * succeeds, so null out this field.
10653                         */
10654                        mArgs = null;
10655                    }
10656                } else {
10657                    /*
10658                     * No package verification is enabled, so immediately start
10659                     * the remote call to initiate copy using temporary file.
10660                     */
10661                    ret = args.copyApk(mContainerService, true);
10662                }
10663            }
10664
10665            mRet = ret;
10666        }
10667
10668        @Override
10669        void handleReturnCode() {
10670            // If mArgs is null, then MCS couldn't be reached. When it
10671            // reconnects, it will try again to install. At that point, this
10672            // will succeed.
10673            if (mArgs != null) {
10674                processPendingInstall(mArgs, mRet);
10675            }
10676        }
10677
10678        @Override
10679        void handleServiceError() {
10680            mArgs = createInstallArgs(this);
10681            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10682        }
10683
10684        public boolean isForwardLocked() {
10685            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10686        }
10687    }
10688
10689    /**
10690     * Used during creation of InstallArgs
10691     *
10692     * @param installFlags package installation flags
10693     * @return true if should be installed on external storage
10694     */
10695    private static boolean installOnExternalAsec(int installFlags) {
10696        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10697            return false;
10698        }
10699        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10700            return true;
10701        }
10702        return false;
10703    }
10704
10705    /**
10706     * Used during creation of InstallArgs
10707     *
10708     * @param installFlags package installation flags
10709     * @return true if should be installed as forward locked
10710     */
10711    private static boolean installForwardLocked(int installFlags) {
10712        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10713    }
10714
10715    private InstallArgs createInstallArgs(InstallParams params) {
10716        if (params.move != null) {
10717            return new MoveInstallArgs(params);
10718        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10719            return new AsecInstallArgs(params);
10720        } else {
10721            return new FileInstallArgs(params);
10722        }
10723    }
10724
10725    /**
10726     * Create args that describe an existing installed package. Typically used
10727     * when cleaning up old installs, or used as a move source.
10728     */
10729    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10730            String resourcePath, String[] instructionSets) {
10731        final boolean isInAsec;
10732        if (installOnExternalAsec(installFlags)) {
10733            /* Apps on SD card are always in ASEC containers. */
10734            isInAsec = true;
10735        } else if (installForwardLocked(installFlags)
10736                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10737            /*
10738             * Forward-locked apps are only in ASEC containers if they're the
10739             * new style
10740             */
10741            isInAsec = true;
10742        } else {
10743            isInAsec = false;
10744        }
10745
10746        if (isInAsec) {
10747            return new AsecInstallArgs(codePath, instructionSets,
10748                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10749        } else {
10750            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10751        }
10752    }
10753
10754    static abstract class InstallArgs {
10755        /** @see InstallParams#origin */
10756        final OriginInfo origin;
10757        /** @see InstallParams#move */
10758        final MoveInfo move;
10759
10760        final IPackageInstallObserver2 observer;
10761        // Always refers to PackageManager flags only
10762        final int installFlags;
10763        final String installerPackageName;
10764        final String volumeUuid;
10765        final ManifestDigest manifestDigest;
10766        final UserHandle user;
10767        final String abiOverride;
10768
10769        // The list of instruction sets supported by this app. This is currently
10770        // only used during the rmdex() phase to clean up resources. We can get rid of this
10771        // if we move dex files under the common app path.
10772        /* nullable */ String[] instructionSets;
10773
10774        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10775                int installFlags, String installerPackageName, String volumeUuid,
10776                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10777                String abiOverride) {
10778            this.origin = origin;
10779            this.move = move;
10780            this.installFlags = installFlags;
10781            this.observer = observer;
10782            this.installerPackageName = installerPackageName;
10783            this.volumeUuid = volumeUuid;
10784            this.manifestDigest = manifestDigest;
10785            this.user = user;
10786            this.instructionSets = instructionSets;
10787            this.abiOverride = abiOverride;
10788        }
10789
10790        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10791        abstract int doPreInstall(int status);
10792
10793        /**
10794         * Rename package into final resting place. All paths on the given
10795         * scanned package should be updated to reflect the rename.
10796         */
10797        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10798        abstract int doPostInstall(int status, int uid);
10799
10800        /** @see PackageSettingBase#codePathString */
10801        abstract String getCodePath();
10802        /** @see PackageSettingBase#resourcePathString */
10803        abstract String getResourcePath();
10804
10805        // Need installer lock especially for dex file removal.
10806        abstract void cleanUpResourcesLI();
10807        abstract boolean doPostDeleteLI(boolean delete);
10808
10809        /**
10810         * Called before the source arguments are copied. This is used mostly
10811         * for MoveParams when it needs to read the source file to put it in the
10812         * destination.
10813         */
10814        int doPreCopy() {
10815            return PackageManager.INSTALL_SUCCEEDED;
10816        }
10817
10818        /**
10819         * Called after the source arguments are copied. This is used mostly for
10820         * MoveParams when it needs to read the source file to put it in the
10821         * destination.
10822         *
10823         * @return
10824         */
10825        int doPostCopy(int uid) {
10826            return PackageManager.INSTALL_SUCCEEDED;
10827        }
10828
10829        protected boolean isFwdLocked() {
10830            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10831        }
10832
10833        protected boolean isExternalAsec() {
10834            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10835        }
10836
10837        UserHandle getUser() {
10838            return user;
10839        }
10840    }
10841
10842    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10843        if (!allCodePaths.isEmpty()) {
10844            if (instructionSets == null) {
10845                throw new IllegalStateException("instructionSet == null");
10846            }
10847            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10848            for (String codePath : allCodePaths) {
10849                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10850                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10851                    if (retCode < 0) {
10852                        Slog.w(TAG, "Couldn't remove dex file for package: "
10853                                + " at location " + codePath + ", retcode=" + retCode);
10854                        // we don't consider this to be a failure of the core package deletion
10855                    }
10856                }
10857            }
10858        }
10859    }
10860
10861    /**
10862     * Logic to handle installation of non-ASEC applications, including copying
10863     * and renaming logic.
10864     */
10865    class FileInstallArgs extends InstallArgs {
10866        private File codeFile;
10867        private File resourceFile;
10868
10869        // Example topology:
10870        // /data/app/com.example/base.apk
10871        // /data/app/com.example/split_foo.apk
10872        // /data/app/com.example/lib/arm/libfoo.so
10873        // /data/app/com.example/lib/arm64/libfoo.so
10874        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10875
10876        /** New install */
10877        FileInstallArgs(InstallParams params) {
10878            super(params.origin, params.move, params.observer, params.installFlags,
10879                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10880                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10881            if (isFwdLocked()) {
10882                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10883            }
10884        }
10885
10886        /** Existing install */
10887        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10888            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10889                    null);
10890            this.codeFile = (codePath != null) ? new File(codePath) : null;
10891            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10892        }
10893
10894        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10895            if (origin.staged) {
10896                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10897                codeFile = origin.file;
10898                resourceFile = origin.file;
10899                return PackageManager.INSTALL_SUCCEEDED;
10900            }
10901
10902            try {
10903                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10904                codeFile = tempDir;
10905                resourceFile = tempDir;
10906            } catch (IOException e) {
10907                Slog.w(TAG, "Failed to create copy file: " + e);
10908                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10909            }
10910
10911            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10912                @Override
10913                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10914                    if (!FileUtils.isValidExtFilename(name)) {
10915                        throw new IllegalArgumentException("Invalid filename: " + name);
10916                    }
10917                    try {
10918                        final File file = new File(codeFile, name);
10919                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10920                                O_RDWR | O_CREAT, 0644);
10921                        Os.chmod(file.getAbsolutePath(), 0644);
10922                        return new ParcelFileDescriptor(fd);
10923                    } catch (ErrnoException e) {
10924                        throw new RemoteException("Failed to open: " + e.getMessage());
10925                    }
10926                }
10927            };
10928
10929            int ret = PackageManager.INSTALL_SUCCEEDED;
10930            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10931            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10932                Slog.e(TAG, "Failed to copy package");
10933                return ret;
10934            }
10935
10936            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10937            NativeLibraryHelper.Handle handle = null;
10938            try {
10939                handle = NativeLibraryHelper.Handle.create(codeFile);
10940                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10941                        abiOverride);
10942            } catch (IOException e) {
10943                Slog.e(TAG, "Copying native libraries failed", e);
10944                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10945            } finally {
10946                IoUtils.closeQuietly(handle);
10947            }
10948
10949            return ret;
10950        }
10951
10952        int doPreInstall(int status) {
10953            if (status != PackageManager.INSTALL_SUCCEEDED) {
10954                cleanUp();
10955            }
10956            return status;
10957        }
10958
10959        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10960            if (status != PackageManager.INSTALL_SUCCEEDED) {
10961                cleanUp();
10962                return false;
10963            }
10964
10965            final File targetDir = codeFile.getParentFile();
10966            final File beforeCodeFile = codeFile;
10967            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10968
10969            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10970            try {
10971                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10972            } catch (ErrnoException e) {
10973                Slog.w(TAG, "Failed to rename", e);
10974                return false;
10975            }
10976
10977            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10978                Slog.w(TAG, "Failed to restorecon");
10979                return false;
10980            }
10981
10982            // Reflect the rename internally
10983            codeFile = afterCodeFile;
10984            resourceFile = afterCodeFile;
10985
10986            // Reflect the rename in scanned details
10987            pkg.codePath = afterCodeFile.getAbsolutePath();
10988            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10989                    pkg.baseCodePath);
10990            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10991                    pkg.splitCodePaths);
10992
10993            // Reflect the rename in app info
10994            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10995            pkg.applicationInfo.setCodePath(pkg.codePath);
10996            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10997            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10998            pkg.applicationInfo.setResourcePath(pkg.codePath);
10999            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11000            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11001
11002            return true;
11003        }
11004
11005        int doPostInstall(int status, int uid) {
11006            if (status != PackageManager.INSTALL_SUCCEEDED) {
11007                cleanUp();
11008            }
11009            return status;
11010        }
11011
11012        @Override
11013        String getCodePath() {
11014            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11015        }
11016
11017        @Override
11018        String getResourcePath() {
11019            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11020        }
11021
11022        private boolean cleanUp() {
11023            if (codeFile == null || !codeFile.exists()) {
11024                return false;
11025            }
11026
11027            if (codeFile.isDirectory()) {
11028                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11029            } else {
11030                codeFile.delete();
11031            }
11032
11033            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11034                resourceFile.delete();
11035            }
11036
11037            return true;
11038        }
11039
11040        void cleanUpResourcesLI() {
11041            // Try enumerating all code paths before deleting
11042            List<String> allCodePaths = Collections.EMPTY_LIST;
11043            if (codeFile != null && codeFile.exists()) {
11044                try {
11045                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11046                    allCodePaths = pkg.getAllCodePaths();
11047                } catch (PackageParserException e) {
11048                    // Ignored; we tried our best
11049                }
11050            }
11051
11052            cleanUp();
11053            removeDexFiles(allCodePaths, instructionSets);
11054        }
11055
11056        boolean doPostDeleteLI(boolean delete) {
11057            // XXX err, shouldn't we respect the delete flag?
11058            cleanUpResourcesLI();
11059            return true;
11060        }
11061    }
11062
11063    private boolean isAsecExternal(String cid) {
11064        final String asecPath = PackageHelper.getSdFilesystem(cid);
11065        return !asecPath.startsWith(mAsecInternalPath);
11066    }
11067
11068    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11069            PackageManagerException {
11070        if (copyRet < 0) {
11071            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11072                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11073                throw new PackageManagerException(copyRet, message);
11074            }
11075        }
11076    }
11077
11078    /**
11079     * Extract the MountService "container ID" from the full code path of an
11080     * .apk.
11081     */
11082    static String cidFromCodePath(String fullCodePath) {
11083        int eidx = fullCodePath.lastIndexOf("/");
11084        String subStr1 = fullCodePath.substring(0, eidx);
11085        int sidx = subStr1.lastIndexOf("/");
11086        return subStr1.substring(sidx+1, eidx);
11087    }
11088
11089    /**
11090     * Logic to handle installation of ASEC applications, including copying and
11091     * renaming logic.
11092     */
11093    class AsecInstallArgs extends InstallArgs {
11094        static final String RES_FILE_NAME = "pkg.apk";
11095        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11096
11097        String cid;
11098        String packagePath;
11099        String resourcePath;
11100
11101        /** New install */
11102        AsecInstallArgs(InstallParams params) {
11103            super(params.origin, params.move, params.observer, params.installFlags,
11104                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11105                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11106        }
11107
11108        /** Existing install */
11109        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11110                        boolean isExternal, boolean isForwardLocked) {
11111            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11112                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11113                    instructionSets, null);
11114            // Hackily pretend we're still looking at a full code path
11115            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11116                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11117            }
11118
11119            // Extract cid from fullCodePath
11120            int eidx = fullCodePath.lastIndexOf("/");
11121            String subStr1 = fullCodePath.substring(0, eidx);
11122            int sidx = subStr1.lastIndexOf("/");
11123            cid = subStr1.substring(sidx+1, eidx);
11124            setMountPath(subStr1);
11125        }
11126
11127        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11128            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11129                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11130                    instructionSets, null);
11131            this.cid = cid;
11132            setMountPath(PackageHelper.getSdDir(cid));
11133        }
11134
11135        void createCopyFile() {
11136            cid = mInstallerService.allocateExternalStageCidLegacy();
11137        }
11138
11139        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11140            if (origin.staged) {
11141                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11142                cid = origin.cid;
11143                setMountPath(PackageHelper.getSdDir(cid));
11144                return PackageManager.INSTALL_SUCCEEDED;
11145            }
11146
11147            if (temp) {
11148                createCopyFile();
11149            } else {
11150                /*
11151                 * Pre-emptively destroy the container since it's destroyed if
11152                 * copying fails due to it existing anyway.
11153                 */
11154                PackageHelper.destroySdDir(cid);
11155            }
11156
11157            final String newMountPath = imcs.copyPackageToContainer(
11158                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11159                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11160
11161            if (newMountPath != null) {
11162                setMountPath(newMountPath);
11163                return PackageManager.INSTALL_SUCCEEDED;
11164            } else {
11165                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11166            }
11167        }
11168
11169        @Override
11170        String getCodePath() {
11171            return packagePath;
11172        }
11173
11174        @Override
11175        String getResourcePath() {
11176            return resourcePath;
11177        }
11178
11179        int doPreInstall(int status) {
11180            if (status != PackageManager.INSTALL_SUCCEEDED) {
11181                // Destroy container
11182                PackageHelper.destroySdDir(cid);
11183            } else {
11184                boolean mounted = PackageHelper.isContainerMounted(cid);
11185                if (!mounted) {
11186                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11187                            Process.SYSTEM_UID);
11188                    if (newMountPath != null) {
11189                        setMountPath(newMountPath);
11190                    } else {
11191                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11192                    }
11193                }
11194            }
11195            return status;
11196        }
11197
11198        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11199            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11200            String newMountPath = null;
11201            if (PackageHelper.isContainerMounted(cid)) {
11202                // Unmount the container
11203                if (!PackageHelper.unMountSdDir(cid)) {
11204                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11205                    return false;
11206                }
11207            }
11208            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11209                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11210                        " which might be stale. Will try to clean up.");
11211                // Clean up the stale container and proceed to recreate.
11212                if (!PackageHelper.destroySdDir(newCacheId)) {
11213                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11214                    return false;
11215                }
11216                // Successfully cleaned up stale container. Try to rename again.
11217                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11218                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11219                            + " inspite of cleaning it up.");
11220                    return false;
11221                }
11222            }
11223            if (!PackageHelper.isContainerMounted(newCacheId)) {
11224                Slog.w(TAG, "Mounting container " + newCacheId);
11225                newMountPath = PackageHelper.mountSdDir(newCacheId,
11226                        getEncryptKey(), Process.SYSTEM_UID);
11227            } else {
11228                newMountPath = PackageHelper.getSdDir(newCacheId);
11229            }
11230            if (newMountPath == null) {
11231                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11232                return false;
11233            }
11234            Log.i(TAG, "Succesfully renamed " + cid +
11235                    " to " + newCacheId +
11236                    " at new path: " + newMountPath);
11237            cid = newCacheId;
11238
11239            final File beforeCodeFile = new File(packagePath);
11240            setMountPath(newMountPath);
11241            final File afterCodeFile = new File(packagePath);
11242
11243            // Reflect the rename in scanned details
11244            pkg.codePath = afterCodeFile.getAbsolutePath();
11245            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11246                    pkg.baseCodePath);
11247            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11248                    pkg.splitCodePaths);
11249
11250            // Reflect the rename in app info
11251            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11252            pkg.applicationInfo.setCodePath(pkg.codePath);
11253            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11254            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11255            pkg.applicationInfo.setResourcePath(pkg.codePath);
11256            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11257            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11258
11259            return true;
11260        }
11261
11262        private void setMountPath(String mountPath) {
11263            final File mountFile = new File(mountPath);
11264
11265            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11266            if (monolithicFile.exists()) {
11267                packagePath = monolithicFile.getAbsolutePath();
11268                if (isFwdLocked()) {
11269                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11270                } else {
11271                    resourcePath = packagePath;
11272                }
11273            } else {
11274                packagePath = mountFile.getAbsolutePath();
11275                resourcePath = packagePath;
11276            }
11277        }
11278
11279        int doPostInstall(int status, int uid) {
11280            if (status != PackageManager.INSTALL_SUCCEEDED) {
11281                cleanUp();
11282            } else {
11283                final int groupOwner;
11284                final String protectedFile;
11285                if (isFwdLocked()) {
11286                    groupOwner = UserHandle.getSharedAppGid(uid);
11287                    protectedFile = RES_FILE_NAME;
11288                } else {
11289                    groupOwner = -1;
11290                    protectedFile = null;
11291                }
11292
11293                if (uid < Process.FIRST_APPLICATION_UID
11294                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11295                    Slog.e(TAG, "Failed to finalize " + cid);
11296                    PackageHelper.destroySdDir(cid);
11297                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11298                }
11299
11300                boolean mounted = PackageHelper.isContainerMounted(cid);
11301                if (!mounted) {
11302                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11303                }
11304            }
11305            return status;
11306        }
11307
11308        private void cleanUp() {
11309            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11310
11311            // Destroy secure container
11312            PackageHelper.destroySdDir(cid);
11313        }
11314
11315        private List<String> getAllCodePaths() {
11316            final File codeFile = new File(getCodePath());
11317            if (codeFile != null && codeFile.exists()) {
11318                try {
11319                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11320                    return pkg.getAllCodePaths();
11321                } catch (PackageParserException e) {
11322                    // Ignored; we tried our best
11323                }
11324            }
11325            return Collections.EMPTY_LIST;
11326        }
11327
11328        void cleanUpResourcesLI() {
11329            // Enumerate all code paths before deleting
11330            cleanUpResourcesLI(getAllCodePaths());
11331        }
11332
11333        private void cleanUpResourcesLI(List<String> allCodePaths) {
11334            cleanUp();
11335            removeDexFiles(allCodePaths, instructionSets);
11336        }
11337
11338        String getPackageName() {
11339            return getAsecPackageName(cid);
11340        }
11341
11342        boolean doPostDeleteLI(boolean delete) {
11343            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11344            final List<String> allCodePaths = getAllCodePaths();
11345            boolean mounted = PackageHelper.isContainerMounted(cid);
11346            if (mounted) {
11347                // Unmount first
11348                if (PackageHelper.unMountSdDir(cid)) {
11349                    mounted = false;
11350                }
11351            }
11352            if (!mounted && delete) {
11353                cleanUpResourcesLI(allCodePaths);
11354            }
11355            return !mounted;
11356        }
11357
11358        @Override
11359        int doPreCopy() {
11360            if (isFwdLocked()) {
11361                if (!PackageHelper.fixSdPermissions(cid,
11362                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11363                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11364                }
11365            }
11366
11367            return PackageManager.INSTALL_SUCCEEDED;
11368        }
11369
11370        @Override
11371        int doPostCopy(int uid) {
11372            if (isFwdLocked()) {
11373                if (uid < Process.FIRST_APPLICATION_UID
11374                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11375                                RES_FILE_NAME)) {
11376                    Slog.e(TAG, "Failed to finalize " + cid);
11377                    PackageHelper.destroySdDir(cid);
11378                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11379                }
11380            }
11381
11382            return PackageManager.INSTALL_SUCCEEDED;
11383        }
11384    }
11385
11386    /**
11387     * Logic to handle movement of existing installed applications.
11388     */
11389    class MoveInstallArgs extends InstallArgs {
11390        private File codeFile;
11391        private File resourceFile;
11392
11393        /** New install */
11394        MoveInstallArgs(InstallParams params) {
11395            super(params.origin, params.move, params.observer, params.installFlags,
11396                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11397                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11398        }
11399
11400        int copyApk(IMediaContainerService imcs, boolean temp) {
11401            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11402                    + move.fromUuid + " to " + move.toUuid);
11403            synchronized (mInstaller) {
11404                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11405                        move.dataAppName, move.appId, move.seinfo) != 0) {
11406                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11407                }
11408            }
11409
11410            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11411            resourceFile = codeFile;
11412            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11413
11414            return PackageManager.INSTALL_SUCCEEDED;
11415        }
11416
11417        int doPreInstall(int status) {
11418            if (status != PackageManager.INSTALL_SUCCEEDED) {
11419                cleanUp(move.toUuid);
11420            }
11421            return status;
11422        }
11423
11424        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11425            if (status != PackageManager.INSTALL_SUCCEEDED) {
11426                cleanUp(move.toUuid);
11427                return false;
11428            }
11429
11430            // Reflect the move in app info
11431            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11432            pkg.applicationInfo.setCodePath(pkg.codePath);
11433            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11434            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11435            pkg.applicationInfo.setResourcePath(pkg.codePath);
11436            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11437            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11438
11439            return true;
11440        }
11441
11442        int doPostInstall(int status, int uid) {
11443            if (status == PackageManager.INSTALL_SUCCEEDED) {
11444                cleanUp(move.fromUuid);
11445            } else {
11446                cleanUp(move.toUuid);
11447            }
11448            return status;
11449        }
11450
11451        @Override
11452        String getCodePath() {
11453            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11454        }
11455
11456        @Override
11457        String getResourcePath() {
11458            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11459        }
11460
11461        private boolean cleanUp(String volumeUuid) {
11462            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11463                    move.dataAppName);
11464            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11465            synchronized (mInstallLock) {
11466                // Clean up both app data and code
11467                removeDataDirsLI(volumeUuid, move.packageName);
11468                if (codeFile.isDirectory()) {
11469                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11470                } else {
11471                    codeFile.delete();
11472                }
11473            }
11474            return true;
11475        }
11476
11477        void cleanUpResourcesLI() {
11478            throw new UnsupportedOperationException();
11479        }
11480
11481        boolean doPostDeleteLI(boolean delete) {
11482            throw new UnsupportedOperationException();
11483        }
11484    }
11485
11486    static String getAsecPackageName(String packageCid) {
11487        int idx = packageCid.lastIndexOf("-");
11488        if (idx == -1) {
11489            return packageCid;
11490        }
11491        return packageCid.substring(0, idx);
11492    }
11493
11494    // Utility method used to create code paths based on package name and available index.
11495    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11496        String idxStr = "";
11497        int idx = 1;
11498        // Fall back to default value of idx=1 if prefix is not
11499        // part of oldCodePath
11500        if (oldCodePath != null) {
11501            String subStr = oldCodePath;
11502            // Drop the suffix right away
11503            if (suffix != null && subStr.endsWith(suffix)) {
11504                subStr = subStr.substring(0, subStr.length() - suffix.length());
11505            }
11506            // If oldCodePath already contains prefix find out the
11507            // ending index to either increment or decrement.
11508            int sidx = subStr.lastIndexOf(prefix);
11509            if (sidx != -1) {
11510                subStr = subStr.substring(sidx + prefix.length());
11511                if (subStr != null) {
11512                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11513                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11514                    }
11515                    try {
11516                        idx = Integer.parseInt(subStr);
11517                        if (idx <= 1) {
11518                            idx++;
11519                        } else {
11520                            idx--;
11521                        }
11522                    } catch(NumberFormatException e) {
11523                    }
11524                }
11525            }
11526        }
11527        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11528        return prefix + idxStr;
11529    }
11530
11531    private File getNextCodePath(File targetDir, String packageName) {
11532        int suffix = 1;
11533        File result;
11534        do {
11535            result = new File(targetDir, packageName + "-" + suffix);
11536            suffix++;
11537        } while (result.exists());
11538        return result;
11539    }
11540
11541    // Utility method that returns the relative package path with respect
11542    // to the installation directory. Like say for /data/data/com.test-1.apk
11543    // string com.test-1 is returned.
11544    static String deriveCodePathName(String codePath) {
11545        if (codePath == null) {
11546            return null;
11547        }
11548        final File codeFile = new File(codePath);
11549        final String name = codeFile.getName();
11550        if (codeFile.isDirectory()) {
11551            return name;
11552        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11553            final int lastDot = name.lastIndexOf('.');
11554            return name.substring(0, lastDot);
11555        } else {
11556            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11557            return null;
11558        }
11559    }
11560
11561    class PackageInstalledInfo {
11562        String name;
11563        int uid;
11564        // The set of users that originally had this package installed.
11565        int[] origUsers;
11566        // The set of users that now have this package installed.
11567        int[] newUsers;
11568        PackageParser.Package pkg;
11569        int returnCode;
11570        String returnMsg;
11571        PackageRemovedInfo removedInfo;
11572
11573        public void setError(int code, String msg) {
11574            returnCode = code;
11575            returnMsg = msg;
11576            Slog.w(TAG, msg);
11577        }
11578
11579        public void setError(String msg, PackageParserException e) {
11580            returnCode = e.error;
11581            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11582            Slog.w(TAG, msg, e);
11583        }
11584
11585        public void setError(String msg, PackageManagerException e) {
11586            returnCode = e.error;
11587            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11588            Slog.w(TAG, msg, e);
11589        }
11590
11591        // In some error cases we want to convey more info back to the observer
11592        String origPackage;
11593        String origPermission;
11594    }
11595
11596    /*
11597     * Install a non-existing package.
11598     */
11599    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11600            UserHandle user, String installerPackageName, String volumeUuid,
11601            PackageInstalledInfo res) {
11602        // Remember this for later, in case we need to rollback this install
11603        String pkgName = pkg.packageName;
11604
11605        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11606        final boolean dataDirExists = Environment
11607                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11608        synchronized(mPackages) {
11609            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11610                // A package with the same name is already installed, though
11611                // it has been renamed to an older name.  The package we
11612                // are trying to install should be installed as an update to
11613                // the existing one, but that has not been requested, so bail.
11614                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11615                        + " without first uninstalling package running as "
11616                        + mSettings.mRenamedPackages.get(pkgName));
11617                return;
11618            }
11619            if (mPackages.containsKey(pkgName)) {
11620                // Don't allow installation over an existing package with the same name.
11621                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11622                        + " without first uninstalling.");
11623                return;
11624            }
11625        }
11626
11627        try {
11628            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11629                    System.currentTimeMillis(), user);
11630
11631            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11632            // delete the partially installed application. the data directory will have to be
11633            // restored if it was already existing
11634            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11635                // remove package from internal structures.  Note that we want deletePackageX to
11636                // delete the package data and cache directories that it created in
11637                // scanPackageLocked, unless those directories existed before we even tried to
11638                // install.
11639                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11640                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11641                                res.removedInfo, true);
11642            }
11643
11644        } catch (PackageManagerException e) {
11645            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11646        }
11647    }
11648
11649    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11650        // Can't rotate keys during boot or if sharedUser.
11651        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11652                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11653            return false;
11654        }
11655        // app is using upgradeKeySets; make sure all are valid
11656        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11657        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11658        for (int i = 0; i < upgradeKeySets.length; i++) {
11659            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11660                Slog.wtf(TAG, "Package "
11661                         + (oldPs.name != null ? oldPs.name : "<null>")
11662                         + " contains upgrade-key-set reference to unknown key-set: "
11663                         + upgradeKeySets[i]
11664                         + " reverting to signatures check.");
11665                return false;
11666            }
11667        }
11668        return true;
11669    }
11670
11671    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11672        // Upgrade keysets are being used.  Determine if new package has a superset of the
11673        // required keys.
11674        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11675        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11676        for (int i = 0; i < upgradeKeySets.length; i++) {
11677            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11678            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11679                return true;
11680            }
11681        }
11682        return false;
11683    }
11684
11685    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11686            UserHandle user, String installerPackageName, String volumeUuid,
11687            PackageInstalledInfo res) {
11688        final PackageParser.Package oldPackage;
11689        final String pkgName = pkg.packageName;
11690        final int[] allUsers;
11691        final boolean[] perUserInstalled;
11692        final boolean weFroze;
11693
11694        // First find the old package info and check signatures
11695        synchronized(mPackages) {
11696            oldPackage = mPackages.get(pkgName);
11697            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11698            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11699            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11700                if(!checkUpgradeKeySetLP(ps, pkg)) {
11701                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11702                            "New package not signed by keys specified by upgrade-keysets: "
11703                            + pkgName);
11704                    return;
11705                }
11706            } else {
11707                // default to original signature matching
11708                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11709                    != PackageManager.SIGNATURE_MATCH) {
11710                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11711                            "New package has a different signature: " + pkgName);
11712                    return;
11713                }
11714            }
11715
11716            // In case of rollback, remember per-user/profile install state
11717            allUsers = sUserManager.getUserIds();
11718            perUserInstalled = new boolean[allUsers.length];
11719            for (int i = 0; i < allUsers.length; i++) {
11720                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11721            }
11722
11723            // Mark the app as frozen to prevent launching during the upgrade
11724            // process, and then kill all running instances
11725            if (!ps.frozen) {
11726                ps.frozen = true;
11727                weFroze = true;
11728            } else {
11729                weFroze = false;
11730            }
11731        }
11732
11733        // Now that we're guarded by frozen state, kill app during upgrade
11734        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11735
11736        try {
11737            boolean sysPkg = (isSystemApp(oldPackage));
11738            if (sysPkg) {
11739                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11740                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11741            } else {
11742                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11743                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11744            }
11745        } finally {
11746            // Regardless of success or failure of upgrade steps above, always
11747            // unfreeze the package if we froze it
11748            if (weFroze) {
11749                unfreezePackage(pkgName);
11750            }
11751        }
11752    }
11753
11754    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11755            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11756            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11757            String volumeUuid, PackageInstalledInfo res) {
11758        String pkgName = deletedPackage.packageName;
11759        boolean deletedPkg = true;
11760        boolean updatedSettings = false;
11761
11762        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11763                + deletedPackage);
11764        long origUpdateTime;
11765        if (pkg.mExtras != null) {
11766            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11767        } else {
11768            origUpdateTime = 0;
11769        }
11770
11771        // First delete the existing package while retaining the data directory
11772        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11773                res.removedInfo, true)) {
11774            // If the existing package wasn't successfully deleted
11775            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11776            deletedPkg = false;
11777        } else {
11778            // Successfully deleted the old package; proceed with replace.
11779
11780            // If deleted package lived in a container, give users a chance to
11781            // relinquish resources before killing.
11782            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11783                if (DEBUG_INSTALL) {
11784                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11785                }
11786                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11787                final ArrayList<String> pkgList = new ArrayList<String>(1);
11788                pkgList.add(deletedPackage.applicationInfo.packageName);
11789                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11790            }
11791
11792            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11793            try {
11794                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11795                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11796                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11797                        perUserInstalled, res, user);
11798                updatedSettings = true;
11799            } catch (PackageManagerException e) {
11800                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11801            }
11802        }
11803
11804        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11805            // remove package from internal structures.  Note that we want deletePackageX to
11806            // delete the package data and cache directories that it created in
11807            // scanPackageLocked, unless those directories existed before we even tried to
11808            // install.
11809            if(updatedSettings) {
11810                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11811                deletePackageLI(
11812                        pkgName, null, true, allUsers, perUserInstalled,
11813                        PackageManager.DELETE_KEEP_DATA,
11814                                res.removedInfo, true);
11815            }
11816            // Since we failed to install the new package we need to restore the old
11817            // package that we deleted.
11818            if (deletedPkg) {
11819                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11820                File restoreFile = new File(deletedPackage.codePath);
11821                // Parse old package
11822                boolean oldExternal = isExternal(deletedPackage);
11823                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11824                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11825                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11826                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11827                try {
11828                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11829                } catch (PackageManagerException e) {
11830                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11831                            + e.getMessage());
11832                    return;
11833                }
11834                // Restore of old package succeeded. Update permissions.
11835                // writer
11836                synchronized (mPackages) {
11837                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11838                            UPDATE_PERMISSIONS_ALL);
11839                    // can downgrade to reader
11840                    mSettings.writeLPr();
11841                }
11842                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11843            }
11844        }
11845    }
11846
11847    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11848            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11849            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11850            String volumeUuid, PackageInstalledInfo res) {
11851        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11852                + ", old=" + deletedPackage);
11853        boolean disabledSystem = false;
11854        boolean updatedSettings = false;
11855        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11856        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11857                != 0) {
11858            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11859        }
11860        String packageName = deletedPackage.packageName;
11861        if (packageName == null) {
11862            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11863                    "Attempt to delete null packageName.");
11864            return;
11865        }
11866        PackageParser.Package oldPkg;
11867        PackageSetting oldPkgSetting;
11868        // reader
11869        synchronized (mPackages) {
11870            oldPkg = mPackages.get(packageName);
11871            oldPkgSetting = mSettings.mPackages.get(packageName);
11872            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11873                    (oldPkgSetting == null)) {
11874                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11875                        "Couldn't find package:" + packageName + " information");
11876                return;
11877            }
11878        }
11879
11880        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11881        res.removedInfo.removedPackage = packageName;
11882        // Remove existing system package
11883        removePackageLI(oldPkgSetting, true);
11884        // writer
11885        synchronized (mPackages) {
11886            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11887            if (!disabledSystem && deletedPackage != null) {
11888                // We didn't need to disable the .apk as a current system package,
11889                // which means we are replacing another update that is already
11890                // installed.  We need to make sure to delete the older one's .apk.
11891                res.removedInfo.args = createInstallArgsForExisting(0,
11892                        deletedPackage.applicationInfo.getCodePath(),
11893                        deletedPackage.applicationInfo.getResourcePath(),
11894                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11895            } else {
11896                res.removedInfo.args = null;
11897            }
11898        }
11899
11900        // Successfully disabled the old package. Now proceed with re-installation
11901        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11902
11903        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11904        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11905
11906        PackageParser.Package newPackage = null;
11907        try {
11908            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11909            if (newPackage.mExtras != null) {
11910                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11911                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11912                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11913
11914                // is the update attempting to change shared user? that isn't going to work...
11915                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11916                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11917                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11918                            + " to " + newPkgSetting.sharedUser);
11919                    updatedSettings = true;
11920                }
11921            }
11922
11923            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11924                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11925                        perUserInstalled, res, user);
11926                updatedSettings = true;
11927            }
11928
11929        } catch (PackageManagerException e) {
11930            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11931        }
11932
11933        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11934            // Re installation failed. Restore old information
11935            // Remove new pkg information
11936            if (newPackage != null) {
11937                removeInstalledPackageLI(newPackage, true);
11938            }
11939            // Add back the old system package
11940            try {
11941                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11942            } catch (PackageManagerException e) {
11943                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11944            }
11945            // Restore the old system information in Settings
11946            synchronized (mPackages) {
11947                if (disabledSystem) {
11948                    mSettings.enableSystemPackageLPw(packageName);
11949                }
11950                if (updatedSettings) {
11951                    mSettings.setInstallerPackageName(packageName,
11952                            oldPkgSetting.installerPackageName);
11953                }
11954                mSettings.writeLPr();
11955            }
11956        }
11957    }
11958
11959    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11960            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11961            UserHandle user) {
11962        String pkgName = newPackage.packageName;
11963        synchronized (mPackages) {
11964            //write settings. the installStatus will be incomplete at this stage.
11965            //note that the new package setting would have already been
11966            //added to mPackages. It hasn't been persisted yet.
11967            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11968            mSettings.writeLPr();
11969        }
11970
11971        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11972
11973        synchronized (mPackages) {
11974            updatePermissionsLPw(newPackage.packageName, newPackage,
11975                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11976                            ? UPDATE_PERMISSIONS_ALL : 0));
11977            // For system-bundled packages, we assume that installing an upgraded version
11978            // of the package implies that the user actually wants to run that new code,
11979            // so we enable the package.
11980            PackageSetting ps = mSettings.mPackages.get(pkgName);
11981            if (ps != null) {
11982                if (isSystemApp(newPackage)) {
11983                    // NB: implicit assumption that system package upgrades apply to all users
11984                    if (DEBUG_INSTALL) {
11985                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11986                    }
11987                    if (res.origUsers != null) {
11988                        for (int userHandle : res.origUsers) {
11989                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11990                                    userHandle, installerPackageName);
11991                        }
11992                    }
11993                    // Also convey the prior install/uninstall state
11994                    if (allUsers != null && perUserInstalled != null) {
11995                        for (int i = 0; i < allUsers.length; i++) {
11996                            if (DEBUG_INSTALL) {
11997                                Slog.d(TAG, "    user " + allUsers[i]
11998                                        + " => " + perUserInstalled[i]);
11999                            }
12000                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12001                        }
12002                        // these install state changes will be persisted in the
12003                        // upcoming call to mSettings.writeLPr().
12004                    }
12005                }
12006                // It's implied that when a user requests installation, they want the app to be
12007                // installed and enabled.
12008                int userId = user.getIdentifier();
12009                if (userId != UserHandle.USER_ALL) {
12010                    ps.setInstalled(true, userId);
12011                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12012                }
12013            }
12014            res.name = pkgName;
12015            res.uid = newPackage.applicationInfo.uid;
12016            res.pkg = newPackage;
12017            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12018            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12019            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12020            //to update install status
12021            mSettings.writeLPr();
12022        }
12023    }
12024
12025    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12026        final int installFlags = args.installFlags;
12027        final String installerPackageName = args.installerPackageName;
12028        final String volumeUuid = args.volumeUuid;
12029        final File tmpPackageFile = new File(args.getCodePath());
12030        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12031        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12032                || (args.volumeUuid != null));
12033        boolean replace = false;
12034        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12035        if (args.move != null) {
12036            // moving a complete application; perfom an initial scan on the new install location
12037            scanFlags |= SCAN_INITIAL;
12038        }
12039        // Result object to be returned
12040        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12041
12042        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12043        // Retrieve PackageSettings and parse package
12044        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12045                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12046                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12047        PackageParser pp = new PackageParser();
12048        pp.setSeparateProcesses(mSeparateProcesses);
12049        pp.setDisplayMetrics(mMetrics);
12050
12051        final PackageParser.Package pkg;
12052        try {
12053            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12054        } catch (PackageParserException e) {
12055            res.setError("Failed parse during installPackageLI", e);
12056            return;
12057        }
12058
12059        // Mark that we have an install time CPU ABI override.
12060        pkg.cpuAbiOverride = args.abiOverride;
12061
12062        String pkgName = res.name = pkg.packageName;
12063        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12064            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12065                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12066                return;
12067            }
12068        }
12069
12070        try {
12071            pp.collectCertificates(pkg, parseFlags);
12072            pp.collectManifestDigest(pkg);
12073        } catch (PackageParserException e) {
12074            res.setError("Failed collect during installPackageLI", e);
12075            return;
12076        }
12077
12078        /* If the installer passed in a manifest digest, compare it now. */
12079        if (args.manifestDigest != null) {
12080            if (DEBUG_INSTALL) {
12081                final String parsedManifest = pkg.manifestDigest == null ? "null"
12082                        : pkg.manifestDigest.toString();
12083                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12084                        + parsedManifest);
12085            }
12086
12087            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12088                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12089                return;
12090            }
12091        } else if (DEBUG_INSTALL) {
12092            final String parsedManifest = pkg.manifestDigest == null
12093                    ? "null" : pkg.manifestDigest.toString();
12094            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12095        }
12096
12097        // Get rid of all references to package scan path via parser.
12098        pp = null;
12099        String oldCodePath = null;
12100        boolean systemApp = false;
12101        synchronized (mPackages) {
12102            // Check if installing already existing package
12103            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12104                String oldName = mSettings.mRenamedPackages.get(pkgName);
12105                if (pkg.mOriginalPackages != null
12106                        && pkg.mOriginalPackages.contains(oldName)
12107                        && mPackages.containsKey(oldName)) {
12108                    // This package is derived from an original package,
12109                    // and this device has been updating from that original
12110                    // name.  We must continue using the original name, so
12111                    // rename the new package here.
12112                    pkg.setPackageName(oldName);
12113                    pkgName = pkg.packageName;
12114                    replace = true;
12115                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12116                            + oldName + " pkgName=" + pkgName);
12117                } else if (mPackages.containsKey(pkgName)) {
12118                    // This package, under its official name, already exists
12119                    // on the device; we should replace it.
12120                    replace = true;
12121                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12122                }
12123
12124                // Prevent apps opting out from runtime permissions
12125                if (replace) {
12126                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12127                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12128                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12129                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12130                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12131                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12132                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12133                                        + " doesn't support runtime permissions but the old"
12134                                        + " target SDK " + oldTargetSdk + " does.");
12135                        return;
12136                    }
12137                }
12138            }
12139
12140            PackageSetting ps = mSettings.mPackages.get(pkgName);
12141            if (ps != null) {
12142                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12143
12144                // Quick sanity check that we're signed correctly if updating;
12145                // we'll check this again later when scanning, but we want to
12146                // bail early here before tripping over redefined permissions.
12147                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12148                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12149                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12150                                + pkg.packageName + " upgrade keys do not match the "
12151                                + "previously installed version");
12152                        return;
12153                    }
12154                } else {
12155                    try {
12156                        verifySignaturesLP(ps, pkg);
12157                    } catch (PackageManagerException e) {
12158                        res.setError(e.error, e.getMessage());
12159                        return;
12160                    }
12161                }
12162
12163                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12164                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12165                    systemApp = (ps.pkg.applicationInfo.flags &
12166                            ApplicationInfo.FLAG_SYSTEM) != 0;
12167                }
12168                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12169            }
12170
12171            // Check whether the newly-scanned package wants to define an already-defined perm
12172            int N = pkg.permissions.size();
12173            for (int i = N-1; i >= 0; i--) {
12174                PackageParser.Permission perm = pkg.permissions.get(i);
12175                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12176                if (bp != null) {
12177                    // If the defining package is signed with our cert, it's okay.  This
12178                    // also includes the "updating the same package" case, of course.
12179                    // "updating same package" could also involve key-rotation.
12180                    final boolean sigsOk;
12181                    if (bp.sourcePackage.equals(pkg.packageName)
12182                            && (bp.packageSetting instanceof PackageSetting)
12183                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12184                                    scanFlags))) {
12185                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12186                    } else {
12187                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12188                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12189                    }
12190                    if (!sigsOk) {
12191                        // If the owning package is the system itself, we log but allow
12192                        // install to proceed; we fail the install on all other permission
12193                        // redefinitions.
12194                        if (!bp.sourcePackage.equals("android")) {
12195                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12196                                    + pkg.packageName + " attempting to redeclare permission "
12197                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12198                            res.origPermission = perm.info.name;
12199                            res.origPackage = bp.sourcePackage;
12200                            return;
12201                        } else {
12202                            Slog.w(TAG, "Package " + pkg.packageName
12203                                    + " attempting to redeclare system permission "
12204                                    + perm.info.name + "; ignoring new declaration");
12205                            pkg.permissions.remove(i);
12206                        }
12207                    }
12208                }
12209            }
12210
12211        }
12212
12213        if (systemApp && onExternal) {
12214            // Disable updates to system apps on sdcard
12215            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12216                    "Cannot install updates to system apps on sdcard");
12217            return;
12218        }
12219
12220        if (args.move != null) {
12221            // We did an in-place move, so dex is ready to roll
12222            scanFlags |= SCAN_NO_DEX;
12223            scanFlags |= SCAN_MOVE;
12224        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12225            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12226            scanFlags |= SCAN_NO_DEX;
12227
12228            try {
12229                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12230                        true /* extract libs */);
12231            } catch (PackageManagerException pme) {
12232                Slog.e(TAG, "Error deriving application ABI", pme);
12233                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12234                return;
12235            }
12236
12237            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12238            int result = mPackageDexOptimizer
12239                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12240                            false /* defer */, false /* inclDependencies */);
12241            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12242                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12243                return;
12244            }
12245        }
12246
12247        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12248            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12249            return;
12250        }
12251
12252        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12253
12254        if (replace) {
12255            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12256                    installerPackageName, volumeUuid, res);
12257        } else {
12258            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12259                    args.user, installerPackageName, volumeUuid, res);
12260        }
12261        synchronized (mPackages) {
12262            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12263            if (ps != null) {
12264                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12265            }
12266        }
12267    }
12268
12269    private void startIntentFilterVerifications(int userId, boolean replacing,
12270            PackageParser.Package pkg) {
12271        if (mIntentFilterVerifierComponent == null) {
12272            Slog.w(TAG, "No IntentFilter verification will not be done as "
12273                    + "there is no IntentFilterVerifier available!");
12274            return;
12275        }
12276
12277        final int verifierUid = getPackageUid(
12278                mIntentFilterVerifierComponent.getPackageName(),
12279                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12280
12281        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12282        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12283        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12284        mHandler.sendMessage(msg);
12285    }
12286
12287    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12288            PackageParser.Package pkg) {
12289        int size = pkg.activities.size();
12290        if (size == 0) {
12291            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12292                    "No activity, so no need to verify any IntentFilter!");
12293            return;
12294        }
12295
12296        final boolean hasDomainURLs = hasDomainURLs(pkg);
12297        if (!hasDomainURLs) {
12298            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12299                    "No domain URLs, so no need to verify any IntentFilter!");
12300            return;
12301        }
12302
12303        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12304                + " if any IntentFilter from the " + size
12305                + " Activities needs verification ...");
12306
12307        int count = 0;
12308        final String packageName = pkg.packageName;
12309
12310        synchronized (mPackages) {
12311            // If this is a new install and we see that we've already run verification for this
12312            // package, we have nothing to do: it means the state was restored from backup.
12313            if (!replacing) {
12314                IntentFilterVerificationInfo ivi =
12315                        mSettings.getIntentFilterVerificationLPr(packageName);
12316                if (ivi != null) {
12317                    if (DEBUG_DOMAIN_VERIFICATION) {
12318                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12319                                + ivi.getStatusString());
12320                    }
12321                    return;
12322                }
12323            }
12324
12325            // If any filters need to be verified, then all need to be.
12326            boolean needToVerify = false;
12327            for (PackageParser.Activity a : pkg.activities) {
12328                for (ActivityIntentInfo filter : a.intents) {
12329                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12330                        if (DEBUG_DOMAIN_VERIFICATION) {
12331                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12332                        }
12333                        needToVerify = true;
12334                        break;
12335                    }
12336                }
12337            }
12338
12339            if (needToVerify) {
12340                final int verificationId = mIntentFilterVerificationToken++;
12341                for (PackageParser.Activity a : pkg.activities) {
12342                    for (ActivityIntentInfo filter : a.intents) {
12343                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12344                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12345                                    "Verification needed for IntentFilter:" + filter.toString());
12346                            mIntentFilterVerifier.addOneIntentFilterVerification(
12347                                    verifierUid, userId, verificationId, filter, packageName);
12348                            count++;
12349                        }
12350                    }
12351                }
12352            }
12353        }
12354
12355        if (count > 0) {
12356            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12357                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12358                    +  " for userId:" + userId);
12359            mIntentFilterVerifier.startVerifications(userId);
12360        } else {
12361            if (DEBUG_DOMAIN_VERIFICATION) {
12362                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12363            }
12364        }
12365    }
12366
12367    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12368        final ComponentName cn  = filter.activity.getComponentName();
12369        final String packageName = cn.getPackageName();
12370
12371        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12372                packageName);
12373        if (ivi == null) {
12374            return true;
12375        }
12376        int status = ivi.getStatus();
12377        switch (status) {
12378            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12379            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12380                return true;
12381
12382            default:
12383                // Nothing to do
12384                return false;
12385        }
12386    }
12387
12388    private static boolean isMultiArch(PackageSetting ps) {
12389        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12390    }
12391
12392    private static boolean isMultiArch(ApplicationInfo info) {
12393        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12394    }
12395
12396    private static boolean isExternal(PackageParser.Package pkg) {
12397        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12398    }
12399
12400    private static boolean isExternal(PackageSetting ps) {
12401        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12402    }
12403
12404    private static boolean isExternal(ApplicationInfo info) {
12405        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12406    }
12407
12408    private static boolean isSystemApp(PackageParser.Package pkg) {
12409        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12410    }
12411
12412    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12413        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12414    }
12415
12416    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12417        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12418    }
12419
12420    private static boolean isSystemApp(PackageSetting ps) {
12421        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12422    }
12423
12424    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12425        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12426    }
12427
12428    private int packageFlagsToInstallFlags(PackageSetting ps) {
12429        int installFlags = 0;
12430        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12431            // This existing package was an external ASEC install when we have
12432            // the external flag without a UUID
12433            installFlags |= PackageManager.INSTALL_EXTERNAL;
12434        }
12435        if (ps.isForwardLocked()) {
12436            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12437        }
12438        return installFlags;
12439    }
12440
12441    private void deleteTempPackageFiles() {
12442        final FilenameFilter filter = new FilenameFilter() {
12443            public boolean accept(File dir, String name) {
12444                return name.startsWith("vmdl") && name.endsWith(".tmp");
12445            }
12446        };
12447        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12448            file.delete();
12449        }
12450    }
12451
12452    @Override
12453    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12454            int flags) {
12455        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12456                flags);
12457    }
12458
12459    @Override
12460    public void deletePackage(final String packageName,
12461            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12462        mContext.enforceCallingOrSelfPermission(
12463                android.Manifest.permission.DELETE_PACKAGES, null);
12464        Preconditions.checkNotNull(packageName);
12465        Preconditions.checkNotNull(observer);
12466        final int uid = Binder.getCallingUid();
12467        if (UserHandle.getUserId(uid) != userId) {
12468            mContext.enforceCallingPermission(
12469                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12470                    "deletePackage for user " + userId);
12471        }
12472        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12473            try {
12474                observer.onPackageDeleted(packageName,
12475                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12476            } catch (RemoteException re) {
12477            }
12478            return;
12479        }
12480
12481        boolean uninstallBlocked = false;
12482        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12483            int[] users = sUserManager.getUserIds();
12484            for (int i = 0; i < users.length; ++i) {
12485                if (getBlockUninstallForUser(packageName, users[i])) {
12486                    uninstallBlocked = true;
12487                    break;
12488                }
12489            }
12490        } else {
12491            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12492        }
12493        if (uninstallBlocked) {
12494            try {
12495                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12496                        null);
12497            } catch (RemoteException re) {
12498            }
12499            return;
12500        }
12501
12502        if (DEBUG_REMOVE) {
12503            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12504        }
12505        // Queue up an async operation since the package deletion may take a little while.
12506        mHandler.post(new Runnable() {
12507            public void run() {
12508                mHandler.removeCallbacks(this);
12509                final int returnCode = deletePackageX(packageName, userId, flags);
12510                if (observer != null) {
12511                    try {
12512                        observer.onPackageDeleted(packageName, returnCode, null);
12513                    } catch (RemoteException e) {
12514                        Log.i(TAG, "Observer no longer exists.");
12515                    } //end catch
12516                } //end if
12517            } //end run
12518        });
12519    }
12520
12521    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12522        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12523                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12524        try {
12525            if (dpm != null) {
12526                if (dpm.isDeviceOwner(packageName)) {
12527                    return true;
12528                }
12529                int[] users;
12530                if (userId == UserHandle.USER_ALL) {
12531                    users = sUserManager.getUserIds();
12532                } else {
12533                    users = new int[]{userId};
12534                }
12535                for (int i = 0; i < users.length; ++i) {
12536                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12537                        return true;
12538                    }
12539                }
12540            }
12541        } catch (RemoteException e) {
12542        }
12543        return false;
12544    }
12545
12546    /**
12547     *  This method is an internal method that could be get invoked either
12548     *  to delete an installed package or to clean up a failed installation.
12549     *  After deleting an installed package, a broadcast is sent to notify any
12550     *  listeners that the package has been installed. For cleaning up a failed
12551     *  installation, the broadcast is not necessary since the package's
12552     *  installation wouldn't have sent the initial broadcast either
12553     *  The key steps in deleting a package are
12554     *  deleting the package information in internal structures like mPackages,
12555     *  deleting the packages base directories through installd
12556     *  updating mSettings to reflect current status
12557     *  persisting settings for later use
12558     *  sending a broadcast if necessary
12559     */
12560    private int deletePackageX(String packageName, int userId, int flags) {
12561        final PackageRemovedInfo info = new PackageRemovedInfo();
12562        final boolean res;
12563
12564        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12565                ? UserHandle.ALL : new UserHandle(userId);
12566
12567        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12568            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12569            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12570        }
12571
12572        boolean removedForAllUsers = false;
12573        boolean systemUpdate = false;
12574
12575        // for the uninstall-updates case and restricted profiles, remember the per-
12576        // userhandle installed state
12577        int[] allUsers;
12578        boolean[] perUserInstalled;
12579        synchronized (mPackages) {
12580            PackageSetting ps = mSettings.mPackages.get(packageName);
12581            allUsers = sUserManager.getUserIds();
12582            perUserInstalled = new boolean[allUsers.length];
12583            for (int i = 0; i < allUsers.length; i++) {
12584                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12585            }
12586        }
12587
12588        synchronized (mInstallLock) {
12589            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12590            res = deletePackageLI(packageName, removeForUser,
12591                    true, allUsers, perUserInstalled,
12592                    flags | REMOVE_CHATTY, info, true);
12593            systemUpdate = info.isRemovedPackageSystemUpdate;
12594            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12595                removedForAllUsers = true;
12596            }
12597            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12598                    + " removedForAllUsers=" + removedForAllUsers);
12599        }
12600
12601        if (res) {
12602            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12603
12604            // If the removed package was a system update, the old system package
12605            // was re-enabled; we need to broadcast this information
12606            if (systemUpdate) {
12607                Bundle extras = new Bundle(1);
12608                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12609                        ? info.removedAppId : info.uid);
12610                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12611
12612                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12613                        extras, null, null, null);
12614                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12615                        extras, null, null, null);
12616                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12617                        null, packageName, null, null);
12618            }
12619        }
12620        // Force a gc here.
12621        Runtime.getRuntime().gc();
12622        // Delete the resources here after sending the broadcast to let
12623        // other processes clean up before deleting resources.
12624        if (info.args != null) {
12625            synchronized (mInstallLock) {
12626                info.args.doPostDeleteLI(true);
12627            }
12628        }
12629
12630        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12631    }
12632
12633    class PackageRemovedInfo {
12634        String removedPackage;
12635        int uid = -1;
12636        int removedAppId = -1;
12637        int[] removedUsers = null;
12638        boolean isRemovedPackageSystemUpdate = false;
12639        // Clean up resources deleted packages.
12640        InstallArgs args = null;
12641
12642        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12643            Bundle extras = new Bundle(1);
12644            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12645            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12646            if (replacing) {
12647                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12648            }
12649            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12650            if (removedPackage != null) {
12651                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12652                        extras, null, null, removedUsers);
12653                if (fullRemove && !replacing) {
12654                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12655                            extras, null, null, removedUsers);
12656                }
12657            }
12658            if (removedAppId >= 0) {
12659                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12660                        removedUsers);
12661            }
12662        }
12663    }
12664
12665    /*
12666     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12667     * flag is not set, the data directory is removed as well.
12668     * make sure this flag is set for partially installed apps. If not its meaningless to
12669     * delete a partially installed application.
12670     */
12671    private void removePackageDataLI(PackageSetting ps,
12672            int[] allUserHandles, boolean[] perUserInstalled,
12673            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12674        String packageName = ps.name;
12675        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12676        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12677        // Retrieve object to delete permissions for shared user later on
12678        final PackageSetting deletedPs;
12679        // reader
12680        synchronized (mPackages) {
12681            deletedPs = mSettings.mPackages.get(packageName);
12682            if (outInfo != null) {
12683                outInfo.removedPackage = packageName;
12684                outInfo.removedUsers = deletedPs != null
12685                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12686                        : null;
12687            }
12688        }
12689        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12690            removeDataDirsLI(ps.volumeUuid, packageName);
12691            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12692        }
12693        // writer
12694        synchronized (mPackages) {
12695            if (deletedPs != null) {
12696                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12697                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12698                    clearDefaultBrowserIfNeeded(packageName);
12699                    if (outInfo != null) {
12700                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12701                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12702                    }
12703                    updatePermissionsLPw(deletedPs.name, null, 0);
12704                    if (deletedPs.sharedUser != null) {
12705                        // Remove permissions associated with package. Since runtime
12706                        // permissions are per user we have to kill the removed package
12707                        // or packages running under the shared user of the removed
12708                        // package if revoking the permissions requested only by the removed
12709                        // package is successful and this causes a change in gids.
12710                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12711                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12712                                    userId);
12713                            if (userIdToKill == UserHandle.USER_ALL
12714                                    || userIdToKill >= UserHandle.USER_OWNER) {
12715                                // If gids changed for this user, kill all affected packages.
12716                                mHandler.post(new Runnable() {
12717                                    @Override
12718                                    public void run() {
12719                                        // This has to happen with no lock held.
12720                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12721                                                KILL_APP_REASON_GIDS_CHANGED);
12722                                    }
12723                                });
12724                                break;
12725                            }
12726                        }
12727                    }
12728                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12729                }
12730                // make sure to preserve per-user disabled state if this removal was just
12731                // a downgrade of a system app to the factory package
12732                if (allUserHandles != null && perUserInstalled != null) {
12733                    if (DEBUG_REMOVE) {
12734                        Slog.d(TAG, "Propagating install state across downgrade");
12735                    }
12736                    for (int i = 0; i < allUserHandles.length; i++) {
12737                        if (DEBUG_REMOVE) {
12738                            Slog.d(TAG, "    user " + allUserHandles[i]
12739                                    + " => " + perUserInstalled[i]);
12740                        }
12741                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12742                    }
12743                }
12744            }
12745            // can downgrade to reader
12746            if (writeSettings) {
12747                // Save settings now
12748                mSettings.writeLPr();
12749            }
12750        }
12751        if (outInfo != null) {
12752            // A user ID was deleted here. Go through all users and remove it
12753            // from KeyStore.
12754            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12755        }
12756    }
12757
12758    static boolean locationIsPrivileged(File path) {
12759        try {
12760            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12761                    .getCanonicalPath();
12762            return path.getCanonicalPath().startsWith(privilegedAppDir);
12763        } catch (IOException e) {
12764            Slog.e(TAG, "Unable to access code path " + path);
12765        }
12766        return false;
12767    }
12768
12769    /*
12770     * Tries to delete system package.
12771     */
12772    private boolean deleteSystemPackageLI(PackageSetting newPs,
12773            int[] allUserHandles, boolean[] perUserInstalled,
12774            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12775        final boolean applyUserRestrictions
12776                = (allUserHandles != null) && (perUserInstalled != null);
12777        PackageSetting disabledPs = null;
12778        // Confirm if the system package has been updated
12779        // An updated system app can be deleted. This will also have to restore
12780        // the system pkg from system partition
12781        // reader
12782        synchronized (mPackages) {
12783            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12784        }
12785        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12786                + " disabledPs=" + disabledPs);
12787        if (disabledPs == null) {
12788            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12789            return false;
12790        } else if (DEBUG_REMOVE) {
12791            Slog.d(TAG, "Deleting system pkg from data partition");
12792        }
12793        if (DEBUG_REMOVE) {
12794            if (applyUserRestrictions) {
12795                Slog.d(TAG, "Remembering install states:");
12796                for (int i = 0; i < allUserHandles.length; i++) {
12797                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12798                }
12799            }
12800        }
12801        // Delete the updated package
12802        outInfo.isRemovedPackageSystemUpdate = true;
12803        if (disabledPs.versionCode < newPs.versionCode) {
12804            // Delete data for downgrades
12805            flags &= ~PackageManager.DELETE_KEEP_DATA;
12806        } else {
12807            // Preserve data by setting flag
12808            flags |= PackageManager.DELETE_KEEP_DATA;
12809        }
12810        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12811                allUserHandles, perUserInstalled, outInfo, writeSettings);
12812        if (!ret) {
12813            return false;
12814        }
12815        // writer
12816        synchronized (mPackages) {
12817            // Reinstate the old system package
12818            mSettings.enableSystemPackageLPw(newPs.name);
12819            // Remove any native libraries from the upgraded package.
12820            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12821        }
12822        // Install the system package
12823        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12824        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12825        if (locationIsPrivileged(disabledPs.codePath)) {
12826            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12827        }
12828
12829        final PackageParser.Package newPkg;
12830        try {
12831            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12832        } catch (PackageManagerException e) {
12833            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12834            return false;
12835        }
12836
12837        // writer
12838        synchronized (mPackages) {
12839            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12840
12841            // Propagate the permissions state as we do want to drop on the floor
12842            // runtime permissions. The update permissions method below will take
12843            // care of removing obsolete permissions and grant install permissions.
12844            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12845            updatePermissionsLPw(newPkg.packageName, newPkg,
12846                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12847
12848            if (applyUserRestrictions) {
12849                if (DEBUG_REMOVE) {
12850                    Slog.d(TAG, "Propagating install state across reinstall");
12851                }
12852                for (int i = 0; i < allUserHandles.length; i++) {
12853                    if (DEBUG_REMOVE) {
12854                        Slog.d(TAG, "    user " + allUserHandles[i]
12855                                + " => " + perUserInstalled[i]);
12856                    }
12857                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12858                }
12859                // Regardless of writeSettings we need to ensure that this restriction
12860                // state propagation is persisted
12861                mSettings.writeAllUsersPackageRestrictionsLPr();
12862            }
12863            // can downgrade to reader here
12864            if (writeSettings) {
12865                mSettings.writeLPr();
12866            }
12867        }
12868        return true;
12869    }
12870
12871    private boolean deleteInstalledPackageLI(PackageSetting ps,
12872            boolean deleteCodeAndResources, int flags,
12873            int[] allUserHandles, boolean[] perUserInstalled,
12874            PackageRemovedInfo outInfo, boolean writeSettings) {
12875        if (outInfo != null) {
12876            outInfo.uid = ps.appId;
12877        }
12878
12879        // Delete package data from internal structures and also remove data if flag is set
12880        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12881
12882        // Delete application code and resources
12883        if (deleteCodeAndResources && (outInfo != null)) {
12884            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12885                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12886            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12887        }
12888        return true;
12889    }
12890
12891    @Override
12892    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12893            int userId) {
12894        mContext.enforceCallingOrSelfPermission(
12895                android.Manifest.permission.DELETE_PACKAGES, null);
12896        synchronized (mPackages) {
12897            PackageSetting ps = mSettings.mPackages.get(packageName);
12898            if (ps == null) {
12899                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12900                return false;
12901            }
12902            if (!ps.getInstalled(userId)) {
12903                // Can't block uninstall for an app that is not installed or enabled.
12904                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12905                return false;
12906            }
12907            ps.setBlockUninstall(blockUninstall, userId);
12908            mSettings.writePackageRestrictionsLPr(userId);
12909        }
12910        return true;
12911    }
12912
12913    @Override
12914    public boolean getBlockUninstallForUser(String packageName, int userId) {
12915        synchronized (mPackages) {
12916            PackageSetting ps = mSettings.mPackages.get(packageName);
12917            if (ps == null) {
12918                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12919                return false;
12920            }
12921            return ps.getBlockUninstall(userId);
12922        }
12923    }
12924
12925    /*
12926     * This method handles package deletion in general
12927     */
12928    private boolean deletePackageLI(String packageName, UserHandle user,
12929            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12930            int flags, PackageRemovedInfo outInfo,
12931            boolean writeSettings) {
12932        if (packageName == null) {
12933            Slog.w(TAG, "Attempt to delete null packageName.");
12934            return false;
12935        }
12936        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12937        PackageSetting ps;
12938        boolean dataOnly = false;
12939        int removeUser = -1;
12940        int appId = -1;
12941        synchronized (mPackages) {
12942            ps = mSettings.mPackages.get(packageName);
12943            if (ps == null) {
12944                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12945                return false;
12946            }
12947            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12948                    && user.getIdentifier() != UserHandle.USER_ALL) {
12949                // The caller is asking that the package only be deleted for a single
12950                // user.  To do this, we just mark its uninstalled state and delete
12951                // its data.  If this is a system app, we only allow this to happen if
12952                // they have set the special DELETE_SYSTEM_APP which requests different
12953                // semantics than normal for uninstalling system apps.
12954                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12955                ps.setUserState(user.getIdentifier(),
12956                        COMPONENT_ENABLED_STATE_DEFAULT,
12957                        false, //installed
12958                        true,  //stopped
12959                        true,  //notLaunched
12960                        false, //hidden
12961                        null, null, null,
12962                        false, // blockUninstall
12963                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12964                if (!isSystemApp(ps)) {
12965                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12966                        // Other user still have this package installed, so all
12967                        // we need to do is clear this user's data and save that
12968                        // it is uninstalled.
12969                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12970                        removeUser = user.getIdentifier();
12971                        appId = ps.appId;
12972                        scheduleWritePackageRestrictionsLocked(removeUser);
12973                    } else {
12974                        // We need to set it back to 'installed' so the uninstall
12975                        // broadcasts will be sent correctly.
12976                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12977                        ps.setInstalled(true, user.getIdentifier());
12978                    }
12979                } else {
12980                    // This is a system app, so we assume that the
12981                    // other users still have this package installed, so all
12982                    // we need to do is clear this user's data and save that
12983                    // it is uninstalled.
12984                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12985                    removeUser = user.getIdentifier();
12986                    appId = ps.appId;
12987                    scheduleWritePackageRestrictionsLocked(removeUser);
12988                }
12989            }
12990        }
12991
12992        if (removeUser >= 0) {
12993            // From above, we determined that we are deleting this only
12994            // for a single user.  Continue the work here.
12995            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12996            if (outInfo != null) {
12997                outInfo.removedPackage = packageName;
12998                outInfo.removedAppId = appId;
12999                outInfo.removedUsers = new int[] {removeUser};
13000            }
13001            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13002            removeKeystoreDataIfNeeded(removeUser, appId);
13003            schedulePackageCleaning(packageName, removeUser, false);
13004            synchronized (mPackages) {
13005                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13006                    scheduleWritePackageRestrictionsLocked(removeUser);
13007                }
13008                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13009            }
13010            return true;
13011        }
13012
13013        if (dataOnly) {
13014            // Delete application data first
13015            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13016            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13017            return true;
13018        }
13019
13020        boolean ret = false;
13021        if (isSystemApp(ps)) {
13022            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13023            // When an updated system application is deleted we delete the existing resources as well and
13024            // fall back to existing code in system partition
13025            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13026                    flags, outInfo, writeSettings);
13027        } else {
13028            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13029            // Kill application pre-emptively especially for apps on sd.
13030            killApplication(packageName, ps.appId, "uninstall pkg");
13031            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13032                    allUserHandles, perUserInstalled,
13033                    outInfo, writeSettings);
13034        }
13035
13036        return ret;
13037    }
13038
13039    private final class ClearStorageConnection implements ServiceConnection {
13040        IMediaContainerService mContainerService;
13041
13042        @Override
13043        public void onServiceConnected(ComponentName name, IBinder service) {
13044            synchronized (this) {
13045                mContainerService = IMediaContainerService.Stub.asInterface(service);
13046                notifyAll();
13047            }
13048        }
13049
13050        @Override
13051        public void onServiceDisconnected(ComponentName name) {
13052        }
13053    }
13054
13055    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13056        final boolean mounted;
13057        if (Environment.isExternalStorageEmulated()) {
13058            mounted = true;
13059        } else {
13060            final String status = Environment.getExternalStorageState();
13061
13062            mounted = status.equals(Environment.MEDIA_MOUNTED)
13063                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13064        }
13065
13066        if (!mounted) {
13067            return;
13068        }
13069
13070        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13071        int[] users;
13072        if (userId == UserHandle.USER_ALL) {
13073            users = sUserManager.getUserIds();
13074        } else {
13075            users = new int[] { userId };
13076        }
13077        final ClearStorageConnection conn = new ClearStorageConnection();
13078        if (mContext.bindServiceAsUser(
13079                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13080            try {
13081                for (int curUser : users) {
13082                    long timeout = SystemClock.uptimeMillis() + 5000;
13083                    synchronized (conn) {
13084                        long now = SystemClock.uptimeMillis();
13085                        while (conn.mContainerService == null && now < timeout) {
13086                            try {
13087                                conn.wait(timeout - now);
13088                            } catch (InterruptedException e) {
13089                            }
13090                        }
13091                    }
13092                    if (conn.mContainerService == null) {
13093                        return;
13094                    }
13095
13096                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13097                    clearDirectory(conn.mContainerService,
13098                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13099                    if (allData) {
13100                        clearDirectory(conn.mContainerService,
13101                                userEnv.buildExternalStorageAppDataDirs(packageName));
13102                        clearDirectory(conn.mContainerService,
13103                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13104                    }
13105                }
13106            } finally {
13107                mContext.unbindService(conn);
13108            }
13109        }
13110    }
13111
13112    @Override
13113    public void clearApplicationUserData(final String packageName,
13114            final IPackageDataObserver observer, final int userId) {
13115        mContext.enforceCallingOrSelfPermission(
13116                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13117        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13118        // Queue up an async operation since the package deletion may take a little while.
13119        mHandler.post(new Runnable() {
13120            public void run() {
13121                mHandler.removeCallbacks(this);
13122                final boolean succeeded;
13123                synchronized (mInstallLock) {
13124                    succeeded = clearApplicationUserDataLI(packageName, userId);
13125                }
13126                clearExternalStorageDataSync(packageName, userId, true);
13127                if (succeeded) {
13128                    // invoke DeviceStorageMonitor's update method to clear any notifications
13129                    DeviceStorageMonitorInternal
13130                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13131                    if (dsm != null) {
13132                        dsm.checkMemory();
13133                    }
13134                }
13135                if(observer != null) {
13136                    try {
13137                        observer.onRemoveCompleted(packageName, succeeded);
13138                    } catch (RemoteException e) {
13139                        Log.i(TAG, "Observer no longer exists.");
13140                    }
13141                } //end if observer
13142            } //end run
13143        });
13144    }
13145
13146    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13147        if (packageName == null) {
13148            Slog.w(TAG, "Attempt to delete null packageName.");
13149            return false;
13150        }
13151
13152        // Try finding details about the requested package
13153        PackageParser.Package pkg;
13154        synchronized (mPackages) {
13155            pkg = mPackages.get(packageName);
13156            if (pkg == null) {
13157                final PackageSetting ps = mSettings.mPackages.get(packageName);
13158                if (ps != null) {
13159                    pkg = ps.pkg;
13160                }
13161            }
13162
13163            if (pkg == null) {
13164                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13165                return false;
13166            }
13167
13168            PackageSetting ps = (PackageSetting) pkg.mExtras;
13169            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13170        }
13171
13172        // Always delete data directories for package, even if we found no other
13173        // record of app. This helps users recover from UID mismatches without
13174        // resorting to a full data wipe.
13175        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13176        if (retCode < 0) {
13177            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13178            return false;
13179        }
13180
13181        final int appId = pkg.applicationInfo.uid;
13182        removeKeystoreDataIfNeeded(userId, appId);
13183
13184        // Create a native library symlink only if we have native libraries
13185        // and if the native libraries are 32 bit libraries. We do not provide
13186        // this symlink for 64 bit libraries.
13187        if (pkg.applicationInfo.primaryCpuAbi != null &&
13188                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13189            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13190            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13191                    nativeLibPath, userId) < 0) {
13192                Slog.w(TAG, "Failed linking native library dir");
13193                return false;
13194            }
13195        }
13196
13197        return true;
13198    }
13199
13200    /**
13201     * Reverts user permission state changes (permissions and flags).
13202     *
13203     * @param ps The package for which to reset.
13204     * @param userId The device user for which to do a reset.
13205     */
13206    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13207            final PackageSetting ps, final int userId) {
13208        if (ps.pkg == null) {
13209            return;
13210        }
13211
13212        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13213                | FLAG_PERMISSION_USER_FIXED
13214                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13215
13216        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13217                | FLAG_PERMISSION_POLICY_FIXED;
13218
13219        boolean writeInstallPermissions = false;
13220        boolean writeRuntimePermissions = false;
13221
13222        final int permissionCount = ps.pkg.requestedPermissions.size();
13223        for (int i = 0; i < permissionCount; i++) {
13224            String permission = ps.pkg.requestedPermissions.get(i);
13225
13226            BasePermission bp = mSettings.mPermissions.get(permission);
13227            if (bp == null) {
13228                continue;
13229            }
13230
13231            // If shared user we just reset the state to which only this app contributed.
13232            if (ps.sharedUser != null) {
13233                boolean used = false;
13234                final int packageCount = ps.sharedUser.packages.size();
13235                for (int j = 0; j < packageCount; j++) {
13236                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13237                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13238                            && pkg.pkg.requestedPermissions.contains(permission)) {
13239                        used = true;
13240                        break;
13241                    }
13242                }
13243                if (used) {
13244                    continue;
13245                }
13246            }
13247
13248            PermissionsState permissionsState = ps.getPermissionsState();
13249
13250            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13251
13252            // Always clear the user settable flags.
13253            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13254                    bp.name) != null;
13255            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13256                if (hasInstallState) {
13257                    writeInstallPermissions = true;
13258                } else {
13259                    writeRuntimePermissions = true;
13260                }
13261            }
13262
13263            // Below is only runtime permission handling.
13264            if (!bp.isRuntime()) {
13265                continue;
13266            }
13267
13268            // Never clobber system or policy.
13269            if ((oldFlags & policyOrSystemFlags) != 0) {
13270                continue;
13271            }
13272
13273            // If this permission was granted by default, make sure it is.
13274            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13275                if (permissionsState.grantRuntimePermission(bp, userId)
13276                        != PERMISSION_OPERATION_FAILURE) {
13277                    writeRuntimePermissions = true;
13278                }
13279            } else {
13280                // Otherwise, reset the permission.
13281                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13282                switch (revokeResult) {
13283                    case PERMISSION_OPERATION_SUCCESS: {
13284                        writeRuntimePermissions = true;
13285                    } break;
13286
13287                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13288                        writeRuntimePermissions = true;
13289                        // If gids changed for this user, kill all affected packages.
13290                        mHandler.post(new Runnable() {
13291                            @Override
13292                            public void run() {
13293                                // This has to happen with no lock held.
13294                                killSettingPackagesForUser(ps, userId,
13295                                        KILL_APP_REASON_GIDS_CHANGED);
13296                            }
13297                        });
13298                    } break;
13299                }
13300            }
13301        }
13302
13303        // Synchronously write as we are taking permissions away.
13304        if (writeRuntimePermissions) {
13305            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13306        }
13307
13308        // Synchronously write as we are taking permissions away.
13309        if (writeInstallPermissions) {
13310            mSettings.writeLPr();
13311        }
13312    }
13313
13314    /**
13315     * Remove entries from the keystore daemon. Will only remove it if the
13316     * {@code appId} is valid.
13317     */
13318    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13319        if (appId < 0) {
13320            return;
13321        }
13322
13323        final KeyStore keyStore = KeyStore.getInstance();
13324        if (keyStore != null) {
13325            if (userId == UserHandle.USER_ALL) {
13326                for (final int individual : sUserManager.getUserIds()) {
13327                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13328                }
13329            } else {
13330                keyStore.clearUid(UserHandle.getUid(userId, appId));
13331            }
13332        } else {
13333            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13334        }
13335    }
13336
13337    @Override
13338    public void deleteApplicationCacheFiles(final String packageName,
13339            final IPackageDataObserver observer) {
13340        mContext.enforceCallingOrSelfPermission(
13341                android.Manifest.permission.DELETE_CACHE_FILES, null);
13342        // Queue up an async operation since the package deletion may take a little while.
13343        final int userId = UserHandle.getCallingUserId();
13344        mHandler.post(new Runnable() {
13345            public void run() {
13346                mHandler.removeCallbacks(this);
13347                final boolean succeded;
13348                synchronized (mInstallLock) {
13349                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13350                }
13351                clearExternalStorageDataSync(packageName, userId, false);
13352                if (observer != null) {
13353                    try {
13354                        observer.onRemoveCompleted(packageName, succeded);
13355                    } catch (RemoteException e) {
13356                        Log.i(TAG, "Observer no longer exists.");
13357                    }
13358                } //end if observer
13359            } //end run
13360        });
13361    }
13362
13363    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13364        if (packageName == null) {
13365            Slog.w(TAG, "Attempt to delete null packageName.");
13366            return false;
13367        }
13368        PackageParser.Package p;
13369        synchronized (mPackages) {
13370            p = mPackages.get(packageName);
13371        }
13372        if (p == null) {
13373            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13374            return false;
13375        }
13376        final ApplicationInfo applicationInfo = p.applicationInfo;
13377        if (applicationInfo == null) {
13378            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13379            return false;
13380        }
13381        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13382        if (retCode < 0) {
13383            Slog.w(TAG, "Couldn't remove cache files for package: "
13384                       + packageName + " u" + userId);
13385            return false;
13386        }
13387        return true;
13388    }
13389
13390    @Override
13391    public void getPackageSizeInfo(final String packageName, int userHandle,
13392            final IPackageStatsObserver observer) {
13393        mContext.enforceCallingOrSelfPermission(
13394                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13395        if (packageName == null) {
13396            throw new IllegalArgumentException("Attempt to get size of null packageName");
13397        }
13398
13399        PackageStats stats = new PackageStats(packageName, userHandle);
13400
13401        /*
13402         * Queue up an async operation since the package measurement may take a
13403         * little while.
13404         */
13405        Message msg = mHandler.obtainMessage(INIT_COPY);
13406        msg.obj = new MeasureParams(stats, observer);
13407        mHandler.sendMessage(msg);
13408    }
13409
13410    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13411            PackageStats pStats) {
13412        if (packageName == null) {
13413            Slog.w(TAG, "Attempt to get size of null packageName.");
13414            return false;
13415        }
13416        PackageParser.Package p;
13417        boolean dataOnly = false;
13418        String libDirRoot = null;
13419        String asecPath = null;
13420        PackageSetting ps = null;
13421        synchronized (mPackages) {
13422            p = mPackages.get(packageName);
13423            ps = mSettings.mPackages.get(packageName);
13424            if(p == null) {
13425                dataOnly = true;
13426                if((ps == null) || (ps.pkg == null)) {
13427                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13428                    return false;
13429                }
13430                p = ps.pkg;
13431            }
13432            if (ps != null) {
13433                libDirRoot = ps.legacyNativeLibraryPathString;
13434            }
13435            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13436                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13437                if (secureContainerId != null) {
13438                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13439                }
13440            }
13441        }
13442        String publicSrcDir = null;
13443        if(!dataOnly) {
13444            final ApplicationInfo applicationInfo = p.applicationInfo;
13445            if (applicationInfo == null) {
13446                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13447                return false;
13448            }
13449            if (p.isForwardLocked()) {
13450                publicSrcDir = applicationInfo.getBaseResourcePath();
13451            }
13452        }
13453        // TODO: extend to measure size of split APKs
13454        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13455        // not just the first level.
13456        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13457        // just the primary.
13458        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13459        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13460                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13461        if (res < 0) {
13462            return false;
13463        }
13464
13465        // Fix-up for forward-locked applications in ASEC containers.
13466        if (!isExternal(p)) {
13467            pStats.codeSize += pStats.externalCodeSize;
13468            pStats.externalCodeSize = 0L;
13469        }
13470
13471        return true;
13472    }
13473
13474
13475    @Override
13476    public void addPackageToPreferred(String packageName) {
13477        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13478    }
13479
13480    @Override
13481    public void removePackageFromPreferred(String packageName) {
13482        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13483    }
13484
13485    @Override
13486    public List<PackageInfo> getPreferredPackages(int flags) {
13487        return new ArrayList<PackageInfo>();
13488    }
13489
13490    private int getUidTargetSdkVersionLockedLPr(int uid) {
13491        Object obj = mSettings.getUserIdLPr(uid);
13492        if (obj instanceof SharedUserSetting) {
13493            final SharedUserSetting sus = (SharedUserSetting) obj;
13494            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13495            final Iterator<PackageSetting> it = sus.packages.iterator();
13496            while (it.hasNext()) {
13497                final PackageSetting ps = it.next();
13498                if (ps.pkg != null) {
13499                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13500                    if (v < vers) vers = v;
13501                }
13502            }
13503            return vers;
13504        } else if (obj instanceof PackageSetting) {
13505            final PackageSetting ps = (PackageSetting) obj;
13506            if (ps.pkg != null) {
13507                return ps.pkg.applicationInfo.targetSdkVersion;
13508            }
13509        }
13510        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13511    }
13512
13513    @Override
13514    public void addPreferredActivity(IntentFilter filter, int match,
13515            ComponentName[] set, ComponentName activity, int userId) {
13516        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13517                "Adding preferred");
13518    }
13519
13520    private void addPreferredActivityInternal(IntentFilter filter, int match,
13521            ComponentName[] set, ComponentName activity, boolean always, int userId,
13522            String opname) {
13523        // writer
13524        int callingUid = Binder.getCallingUid();
13525        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13526        if (filter.countActions() == 0) {
13527            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13528            return;
13529        }
13530        synchronized (mPackages) {
13531            if (mContext.checkCallingOrSelfPermission(
13532                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13533                    != PackageManager.PERMISSION_GRANTED) {
13534                if (getUidTargetSdkVersionLockedLPr(callingUid)
13535                        < Build.VERSION_CODES.FROYO) {
13536                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13537                            + callingUid);
13538                    return;
13539                }
13540                mContext.enforceCallingOrSelfPermission(
13541                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13542            }
13543
13544            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13545            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13546                    + userId + ":");
13547            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13548            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13549            scheduleWritePackageRestrictionsLocked(userId);
13550        }
13551    }
13552
13553    @Override
13554    public void replacePreferredActivity(IntentFilter filter, int match,
13555            ComponentName[] set, ComponentName activity, int userId) {
13556        if (filter.countActions() != 1) {
13557            throw new IllegalArgumentException(
13558                    "replacePreferredActivity expects filter to have only 1 action.");
13559        }
13560        if (filter.countDataAuthorities() != 0
13561                || filter.countDataPaths() != 0
13562                || filter.countDataSchemes() > 1
13563                || filter.countDataTypes() != 0) {
13564            throw new IllegalArgumentException(
13565                    "replacePreferredActivity expects filter to have no data authorities, " +
13566                    "paths, or types; and at most one scheme.");
13567        }
13568
13569        final int callingUid = Binder.getCallingUid();
13570        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13571        synchronized (mPackages) {
13572            if (mContext.checkCallingOrSelfPermission(
13573                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13574                    != PackageManager.PERMISSION_GRANTED) {
13575                if (getUidTargetSdkVersionLockedLPr(callingUid)
13576                        < Build.VERSION_CODES.FROYO) {
13577                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13578                            + Binder.getCallingUid());
13579                    return;
13580                }
13581                mContext.enforceCallingOrSelfPermission(
13582                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13583            }
13584
13585            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13586            if (pir != null) {
13587                // Get all of the existing entries that exactly match this filter.
13588                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13589                if (existing != null && existing.size() == 1) {
13590                    PreferredActivity cur = existing.get(0);
13591                    if (DEBUG_PREFERRED) {
13592                        Slog.i(TAG, "Checking replace of preferred:");
13593                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13594                        if (!cur.mPref.mAlways) {
13595                            Slog.i(TAG, "  -- CUR; not mAlways!");
13596                        } else {
13597                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13598                            Slog.i(TAG, "  -- CUR: mSet="
13599                                    + Arrays.toString(cur.mPref.mSetComponents));
13600                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13601                            Slog.i(TAG, "  -- NEW: mMatch="
13602                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13603                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13604                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13605                        }
13606                    }
13607                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13608                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13609                            && cur.mPref.sameSet(set)) {
13610                        // Setting the preferred activity to what it happens to be already
13611                        if (DEBUG_PREFERRED) {
13612                            Slog.i(TAG, "Replacing with same preferred activity "
13613                                    + cur.mPref.mShortComponent + " for user "
13614                                    + userId + ":");
13615                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13616                        }
13617                        return;
13618                    }
13619                }
13620
13621                if (existing != null) {
13622                    if (DEBUG_PREFERRED) {
13623                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13624                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13625                    }
13626                    for (int i = 0; i < existing.size(); i++) {
13627                        PreferredActivity pa = existing.get(i);
13628                        if (DEBUG_PREFERRED) {
13629                            Slog.i(TAG, "Removing existing preferred activity "
13630                                    + pa.mPref.mComponent + ":");
13631                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13632                        }
13633                        pir.removeFilter(pa);
13634                    }
13635                }
13636            }
13637            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13638                    "Replacing preferred");
13639        }
13640    }
13641
13642    @Override
13643    public void clearPackagePreferredActivities(String packageName) {
13644        final int uid = Binder.getCallingUid();
13645        // writer
13646        synchronized (mPackages) {
13647            PackageParser.Package pkg = mPackages.get(packageName);
13648            if (pkg == null || pkg.applicationInfo.uid != uid) {
13649                if (mContext.checkCallingOrSelfPermission(
13650                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13651                        != PackageManager.PERMISSION_GRANTED) {
13652                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13653                            < Build.VERSION_CODES.FROYO) {
13654                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13655                                + Binder.getCallingUid());
13656                        return;
13657                    }
13658                    mContext.enforceCallingOrSelfPermission(
13659                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13660                }
13661            }
13662
13663            int user = UserHandle.getCallingUserId();
13664            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13665                scheduleWritePackageRestrictionsLocked(user);
13666            }
13667        }
13668    }
13669
13670    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13671    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13672        ArrayList<PreferredActivity> removed = null;
13673        boolean changed = false;
13674        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13675            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13676            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13677            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13678                continue;
13679            }
13680            Iterator<PreferredActivity> it = pir.filterIterator();
13681            while (it.hasNext()) {
13682                PreferredActivity pa = it.next();
13683                // Mark entry for removal only if it matches the package name
13684                // and the entry is of type "always".
13685                if (packageName == null ||
13686                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13687                                && pa.mPref.mAlways)) {
13688                    if (removed == null) {
13689                        removed = new ArrayList<PreferredActivity>();
13690                    }
13691                    removed.add(pa);
13692                }
13693            }
13694            if (removed != null) {
13695                for (int j=0; j<removed.size(); j++) {
13696                    PreferredActivity pa = removed.get(j);
13697                    pir.removeFilter(pa);
13698                }
13699                changed = true;
13700            }
13701        }
13702        return changed;
13703    }
13704
13705    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13706    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13707        if (userId == UserHandle.USER_ALL) {
13708            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13709                    sUserManager.getUserIds())) {
13710                for (int oneUserId : sUserManager.getUserIds()) {
13711                    scheduleWritePackageRestrictionsLocked(oneUserId);
13712                }
13713            }
13714        } else {
13715            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13716                scheduleWritePackageRestrictionsLocked(userId);
13717            }
13718        }
13719    }
13720
13721
13722    void clearDefaultBrowserIfNeeded(String packageName) {
13723        for (int oneUserId : sUserManager.getUserIds()) {
13724            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13725            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13726            if (packageName.equals(defaultBrowserPackageName)) {
13727                setDefaultBrowserPackageName(null, oneUserId);
13728            }
13729        }
13730    }
13731
13732    @Override
13733    public void resetPreferredActivities(int userId) {
13734        mContext.enforceCallingOrSelfPermission(
13735                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13736        // writer
13737        synchronized (mPackages) {
13738            clearPackagePreferredActivitiesLPw(null, userId);
13739            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13740            applyFactoryDefaultBrowserLPw(userId);
13741            primeDomainVerificationsLPw(userId);
13742
13743            scheduleWritePackageRestrictionsLocked(userId);
13744        }
13745    }
13746
13747    @Override
13748    public int getPreferredActivities(List<IntentFilter> outFilters,
13749            List<ComponentName> outActivities, String packageName) {
13750
13751        int num = 0;
13752        final int userId = UserHandle.getCallingUserId();
13753        // reader
13754        synchronized (mPackages) {
13755            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13756            if (pir != null) {
13757                final Iterator<PreferredActivity> it = pir.filterIterator();
13758                while (it.hasNext()) {
13759                    final PreferredActivity pa = it.next();
13760                    if (packageName == null
13761                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13762                                    && pa.mPref.mAlways)) {
13763                        if (outFilters != null) {
13764                            outFilters.add(new IntentFilter(pa));
13765                        }
13766                        if (outActivities != null) {
13767                            outActivities.add(pa.mPref.mComponent);
13768                        }
13769                    }
13770                }
13771            }
13772        }
13773
13774        return num;
13775    }
13776
13777    @Override
13778    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13779            int userId) {
13780        int callingUid = Binder.getCallingUid();
13781        if (callingUid != Process.SYSTEM_UID) {
13782            throw new SecurityException(
13783                    "addPersistentPreferredActivity can only be run by the system");
13784        }
13785        if (filter.countActions() == 0) {
13786            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13787            return;
13788        }
13789        synchronized (mPackages) {
13790            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13791                    " :");
13792            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13793            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13794                    new PersistentPreferredActivity(filter, activity));
13795            scheduleWritePackageRestrictionsLocked(userId);
13796        }
13797    }
13798
13799    @Override
13800    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13801        int callingUid = Binder.getCallingUid();
13802        if (callingUid != Process.SYSTEM_UID) {
13803            throw new SecurityException(
13804                    "clearPackagePersistentPreferredActivities can only be run by the system");
13805        }
13806        ArrayList<PersistentPreferredActivity> removed = null;
13807        boolean changed = false;
13808        synchronized (mPackages) {
13809            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13810                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13811                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13812                        .valueAt(i);
13813                if (userId != thisUserId) {
13814                    continue;
13815                }
13816                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13817                while (it.hasNext()) {
13818                    PersistentPreferredActivity ppa = it.next();
13819                    // Mark entry for removal only if it matches the package name.
13820                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13821                        if (removed == null) {
13822                            removed = new ArrayList<PersistentPreferredActivity>();
13823                        }
13824                        removed.add(ppa);
13825                    }
13826                }
13827                if (removed != null) {
13828                    for (int j=0; j<removed.size(); j++) {
13829                        PersistentPreferredActivity ppa = removed.get(j);
13830                        ppir.removeFilter(ppa);
13831                    }
13832                    changed = true;
13833                }
13834            }
13835
13836            if (changed) {
13837                scheduleWritePackageRestrictionsLocked(userId);
13838            }
13839        }
13840    }
13841
13842    /**
13843     * Common machinery for picking apart a restored XML blob and passing
13844     * it to a caller-supplied functor to be applied to the running system.
13845     */
13846    private void restoreFromXml(XmlPullParser parser, int userId,
13847            String expectedStartTag, BlobXmlRestorer functor)
13848            throws IOException, XmlPullParserException {
13849        int type;
13850        while ((type = parser.next()) != XmlPullParser.START_TAG
13851                && type != XmlPullParser.END_DOCUMENT) {
13852        }
13853        if (type != XmlPullParser.START_TAG) {
13854            // oops didn't find a start tag?!
13855            if (DEBUG_BACKUP) {
13856                Slog.e(TAG, "Didn't find start tag during restore");
13857            }
13858            return;
13859        }
13860
13861        // this is supposed to be TAG_PREFERRED_BACKUP
13862        if (!expectedStartTag.equals(parser.getName())) {
13863            if (DEBUG_BACKUP) {
13864                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13865            }
13866            return;
13867        }
13868
13869        // skip interfering stuff, then we're aligned with the backing implementation
13870        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13871        functor.apply(parser, userId);
13872    }
13873
13874    private interface BlobXmlRestorer {
13875        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13876    }
13877
13878    /**
13879     * Non-Binder method, support for the backup/restore mechanism: write the
13880     * full set of preferred activities in its canonical XML format.  Returns the
13881     * XML output as a byte array, or null if there is none.
13882     */
13883    @Override
13884    public byte[] getPreferredActivityBackup(int userId) {
13885        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13886            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13887        }
13888
13889        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13890        try {
13891            final XmlSerializer serializer = new FastXmlSerializer();
13892            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13893            serializer.startDocument(null, true);
13894            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13895
13896            synchronized (mPackages) {
13897                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13898            }
13899
13900            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13901            serializer.endDocument();
13902            serializer.flush();
13903        } catch (Exception e) {
13904            if (DEBUG_BACKUP) {
13905                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13906            }
13907            return null;
13908        }
13909
13910        return dataStream.toByteArray();
13911    }
13912
13913    @Override
13914    public void restorePreferredActivities(byte[] backup, int userId) {
13915        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13916            throw new SecurityException("Only the system may call restorePreferredActivities()");
13917        }
13918
13919        try {
13920            final XmlPullParser parser = Xml.newPullParser();
13921            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13922            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13923                    new BlobXmlRestorer() {
13924                        @Override
13925                        public void apply(XmlPullParser parser, int userId)
13926                                throws XmlPullParserException, IOException {
13927                            synchronized (mPackages) {
13928                                mSettings.readPreferredActivitiesLPw(parser, userId);
13929                            }
13930                        }
13931                    } );
13932        } catch (Exception e) {
13933            if (DEBUG_BACKUP) {
13934                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13935            }
13936        }
13937    }
13938
13939    /**
13940     * Non-Binder method, support for the backup/restore mechanism: write the
13941     * default browser (etc) settings in its canonical XML format.  Returns the default
13942     * browser XML representation as a byte array, or null if there is none.
13943     */
13944    @Override
13945    public byte[] getDefaultAppsBackup(int userId) {
13946        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13947            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13948        }
13949
13950        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13951        try {
13952            final XmlSerializer serializer = new FastXmlSerializer();
13953            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13954            serializer.startDocument(null, true);
13955            serializer.startTag(null, TAG_DEFAULT_APPS);
13956
13957            synchronized (mPackages) {
13958                mSettings.writeDefaultAppsLPr(serializer, userId);
13959            }
13960
13961            serializer.endTag(null, TAG_DEFAULT_APPS);
13962            serializer.endDocument();
13963            serializer.flush();
13964        } catch (Exception e) {
13965            if (DEBUG_BACKUP) {
13966                Slog.e(TAG, "Unable to write default apps for backup", e);
13967            }
13968            return null;
13969        }
13970
13971        return dataStream.toByteArray();
13972    }
13973
13974    @Override
13975    public void restoreDefaultApps(byte[] backup, int userId) {
13976        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13977            throw new SecurityException("Only the system may call restoreDefaultApps()");
13978        }
13979
13980        try {
13981            final XmlPullParser parser = Xml.newPullParser();
13982            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13983            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13984                    new BlobXmlRestorer() {
13985                        @Override
13986                        public void apply(XmlPullParser parser, int userId)
13987                                throws XmlPullParserException, IOException {
13988                            synchronized (mPackages) {
13989                                mSettings.readDefaultAppsLPw(parser, userId);
13990                            }
13991                        }
13992                    } );
13993        } catch (Exception e) {
13994            if (DEBUG_BACKUP) {
13995                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13996            }
13997        }
13998    }
13999
14000    @Override
14001    public byte[] getIntentFilterVerificationBackup(int userId) {
14002        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14003            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14004        }
14005
14006        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14007        try {
14008            final XmlSerializer serializer = new FastXmlSerializer();
14009            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14010            serializer.startDocument(null, true);
14011            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14012
14013            synchronized (mPackages) {
14014                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14015            }
14016
14017            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14018            serializer.endDocument();
14019            serializer.flush();
14020        } catch (Exception e) {
14021            if (DEBUG_BACKUP) {
14022                Slog.e(TAG, "Unable to write default apps for backup", e);
14023            }
14024            return null;
14025        }
14026
14027        return dataStream.toByteArray();
14028    }
14029
14030    @Override
14031    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14032        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14033            throw new SecurityException("Only the system may call restorePreferredActivities()");
14034        }
14035
14036        try {
14037            final XmlPullParser parser = Xml.newPullParser();
14038            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14039            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14040                    new BlobXmlRestorer() {
14041                        @Override
14042                        public void apply(XmlPullParser parser, int userId)
14043                                throws XmlPullParserException, IOException {
14044                            synchronized (mPackages) {
14045                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14046                                mSettings.writeLPr();
14047                            }
14048                        }
14049                    } );
14050        } catch (Exception e) {
14051            if (DEBUG_BACKUP) {
14052                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14053            }
14054        }
14055    }
14056
14057    @Override
14058    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14059            int sourceUserId, int targetUserId, int flags) {
14060        mContext.enforceCallingOrSelfPermission(
14061                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14062        int callingUid = Binder.getCallingUid();
14063        enforceOwnerRights(ownerPackage, callingUid);
14064        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14065        if (intentFilter.countActions() == 0) {
14066            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14067            return;
14068        }
14069        synchronized (mPackages) {
14070            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14071                    ownerPackage, targetUserId, flags);
14072            CrossProfileIntentResolver resolver =
14073                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14074            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14075            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14076            if (existing != null) {
14077                int size = existing.size();
14078                for (int i = 0; i < size; i++) {
14079                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14080                        return;
14081                    }
14082                }
14083            }
14084            resolver.addFilter(newFilter);
14085            scheduleWritePackageRestrictionsLocked(sourceUserId);
14086        }
14087    }
14088
14089    @Override
14090    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14091        mContext.enforceCallingOrSelfPermission(
14092                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14093        int callingUid = Binder.getCallingUid();
14094        enforceOwnerRights(ownerPackage, callingUid);
14095        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14096        synchronized (mPackages) {
14097            CrossProfileIntentResolver resolver =
14098                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14099            ArraySet<CrossProfileIntentFilter> set =
14100                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14101            for (CrossProfileIntentFilter filter : set) {
14102                if (filter.getOwnerPackage().equals(ownerPackage)) {
14103                    resolver.removeFilter(filter);
14104                }
14105            }
14106            scheduleWritePackageRestrictionsLocked(sourceUserId);
14107        }
14108    }
14109
14110    // Enforcing that callingUid is owning pkg on userId
14111    private void enforceOwnerRights(String pkg, int callingUid) {
14112        // The system owns everything.
14113        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14114            return;
14115        }
14116        int callingUserId = UserHandle.getUserId(callingUid);
14117        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14118        if (pi == null) {
14119            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14120                    + callingUserId);
14121        }
14122        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14123            throw new SecurityException("Calling uid " + callingUid
14124                    + " does not own package " + pkg);
14125        }
14126    }
14127
14128    @Override
14129    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14130        Intent intent = new Intent(Intent.ACTION_MAIN);
14131        intent.addCategory(Intent.CATEGORY_HOME);
14132
14133        final int callingUserId = UserHandle.getCallingUserId();
14134        List<ResolveInfo> list = queryIntentActivities(intent, null,
14135                PackageManager.GET_META_DATA, callingUserId);
14136        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14137                true, false, false, callingUserId);
14138
14139        allHomeCandidates.clear();
14140        if (list != null) {
14141            for (ResolveInfo ri : list) {
14142                allHomeCandidates.add(ri);
14143            }
14144        }
14145        return (preferred == null || preferred.activityInfo == null)
14146                ? null
14147                : new ComponentName(preferred.activityInfo.packageName,
14148                        preferred.activityInfo.name);
14149    }
14150
14151    @Override
14152    public void setApplicationEnabledSetting(String appPackageName,
14153            int newState, int flags, int userId, String callingPackage) {
14154        if (!sUserManager.exists(userId)) return;
14155        if (callingPackage == null) {
14156            callingPackage = Integer.toString(Binder.getCallingUid());
14157        }
14158        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14159    }
14160
14161    @Override
14162    public void setComponentEnabledSetting(ComponentName componentName,
14163            int newState, int flags, int userId) {
14164        if (!sUserManager.exists(userId)) return;
14165        setEnabledSetting(componentName.getPackageName(),
14166                componentName.getClassName(), newState, flags, userId, null);
14167    }
14168
14169    private void setEnabledSetting(final String packageName, String className, int newState,
14170            final int flags, int userId, String callingPackage) {
14171        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14172              || newState == COMPONENT_ENABLED_STATE_ENABLED
14173              || newState == COMPONENT_ENABLED_STATE_DISABLED
14174              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14175              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14176            throw new IllegalArgumentException("Invalid new component state: "
14177                    + newState);
14178        }
14179        PackageSetting pkgSetting;
14180        final int uid = Binder.getCallingUid();
14181        final int permission = mContext.checkCallingOrSelfPermission(
14182                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14183        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14184        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14185        boolean sendNow = false;
14186        boolean isApp = (className == null);
14187        String componentName = isApp ? packageName : className;
14188        int packageUid = -1;
14189        ArrayList<String> components;
14190
14191        // writer
14192        synchronized (mPackages) {
14193            pkgSetting = mSettings.mPackages.get(packageName);
14194            if (pkgSetting == null) {
14195                if (className == null) {
14196                    throw new IllegalArgumentException(
14197                            "Unknown package: " + packageName);
14198                }
14199                throw new IllegalArgumentException(
14200                        "Unknown component: " + packageName
14201                        + "/" + className);
14202            }
14203            // Allow root and verify that userId is not being specified by a different user
14204            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14205                throw new SecurityException(
14206                        "Permission Denial: attempt to change component state from pid="
14207                        + Binder.getCallingPid()
14208                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14209            }
14210            if (className == null) {
14211                // We're dealing with an application/package level state change
14212                if (pkgSetting.getEnabled(userId) == newState) {
14213                    // Nothing to do
14214                    return;
14215                }
14216                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14217                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14218                    // Don't care about who enables an app.
14219                    callingPackage = null;
14220                }
14221                pkgSetting.setEnabled(newState, userId, callingPackage);
14222                // pkgSetting.pkg.mSetEnabled = newState;
14223            } else {
14224                // We're dealing with a component level state change
14225                // First, verify that this is a valid class name.
14226                PackageParser.Package pkg = pkgSetting.pkg;
14227                if (pkg == null || !pkg.hasComponentClassName(className)) {
14228                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14229                        throw new IllegalArgumentException("Component class " + className
14230                                + " does not exist in " + packageName);
14231                    } else {
14232                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14233                                + className + " does not exist in " + packageName);
14234                    }
14235                }
14236                switch (newState) {
14237                case COMPONENT_ENABLED_STATE_ENABLED:
14238                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14239                        return;
14240                    }
14241                    break;
14242                case COMPONENT_ENABLED_STATE_DISABLED:
14243                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14244                        return;
14245                    }
14246                    break;
14247                case COMPONENT_ENABLED_STATE_DEFAULT:
14248                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14249                        return;
14250                    }
14251                    break;
14252                default:
14253                    Slog.e(TAG, "Invalid new component state: " + newState);
14254                    return;
14255                }
14256            }
14257            scheduleWritePackageRestrictionsLocked(userId);
14258            components = mPendingBroadcasts.get(userId, packageName);
14259            final boolean newPackage = components == null;
14260            if (newPackage) {
14261                components = new ArrayList<String>();
14262            }
14263            if (!components.contains(componentName)) {
14264                components.add(componentName);
14265            }
14266            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14267                sendNow = true;
14268                // Purge entry from pending broadcast list if another one exists already
14269                // since we are sending one right away.
14270                mPendingBroadcasts.remove(userId, packageName);
14271            } else {
14272                if (newPackage) {
14273                    mPendingBroadcasts.put(userId, packageName, components);
14274                }
14275                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14276                    // Schedule a message
14277                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14278                }
14279            }
14280        }
14281
14282        long callingId = Binder.clearCallingIdentity();
14283        try {
14284            if (sendNow) {
14285                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14286                sendPackageChangedBroadcast(packageName,
14287                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14288            }
14289        } finally {
14290            Binder.restoreCallingIdentity(callingId);
14291        }
14292    }
14293
14294    private void sendPackageChangedBroadcast(String packageName,
14295            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14296        if (DEBUG_INSTALL)
14297            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14298                    + componentNames);
14299        Bundle extras = new Bundle(4);
14300        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14301        String nameList[] = new String[componentNames.size()];
14302        componentNames.toArray(nameList);
14303        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14304        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14305        extras.putInt(Intent.EXTRA_UID, packageUid);
14306        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14307                new int[] {UserHandle.getUserId(packageUid)});
14308    }
14309
14310    @Override
14311    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14312        if (!sUserManager.exists(userId)) return;
14313        final int uid = Binder.getCallingUid();
14314        final int permission = mContext.checkCallingOrSelfPermission(
14315                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14316        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14317        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14318        // writer
14319        synchronized (mPackages) {
14320            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14321                    allowedByPermission, uid, userId)) {
14322                scheduleWritePackageRestrictionsLocked(userId);
14323            }
14324        }
14325    }
14326
14327    @Override
14328    public String getInstallerPackageName(String packageName) {
14329        // reader
14330        synchronized (mPackages) {
14331            return mSettings.getInstallerPackageNameLPr(packageName);
14332        }
14333    }
14334
14335    @Override
14336    public int getApplicationEnabledSetting(String packageName, int userId) {
14337        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14338        int uid = Binder.getCallingUid();
14339        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14340        // reader
14341        synchronized (mPackages) {
14342            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14343        }
14344    }
14345
14346    @Override
14347    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14348        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14349        int uid = Binder.getCallingUid();
14350        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14351        // reader
14352        synchronized (mPackages) {
14353            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14354        }
14355    }
14356
14357    @Override
14358    public void enterSafeMode() {
14359        enforceSystemOrRoot("Only the system can request entering safe mode");
14360
14361        if (!mSystemReady) {
14362            mSafeMode = true;
14363        }
14364    }
14365
14366    @Override
14367    public void systemReady() {
14368        mSystemReady = true;
14369
14370        // Read the compatibilty setting when the system is ready.
14371        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14372                mContext.getContentResolver(),
14373                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14374        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14375        if (DEBUG_SETTINGS) {
14376            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14377        }
14378
14379        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14380
14381        synchronized (mPackages) {
14382            // Verify that all of the preferred activity components actually
14383            // exist.  It is possible for applications to be updated and at
14384            // that point remove a previously declared activity component that
14385            // had been set as a preferred activity.  We try to clean this up
14386            // the next time we encounter that preferred activity, but it is
14387            // possible for the user flow to never be able to return to that
14388            // situation so here we do a sanity check to make sure we haven't
14389            // left any junk around.
14390            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14391            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14392                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14393                removed.clear();
14394                for (PreferredActivity pa : pir.filterSet()) {
14395                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14396                        removed.add(pa);
14397                    }
14398                }
14399                if (removed.size() > 0) {
14400                    for (int r=0; r<removed.size(); r++) {
14401                        PreferredActivity pa = removed.get(r);
14402                        Slog.w(TAG, "Removing dangling preferred activity: "
14403                                + pa.mPref.mComponent);
14404                        pir.removeFilter(pa);
14405                    }
14406                    mSettings.writePackageRestrictionsLPr(
14407                            mSettings.mPreferredActivities.keyAt(i));
14408                }
14409            }
14410
14411            for (int userId : UserManagerService.getInstance().getUserIds()) {
14412                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14413                    grantPermissionsUserIds = ArrayUtils.appendInt(
14414                            grantPermissionsUserIds, userId);
14415                }
14416            }
14417        }
14418        sUserManager.systemReady();
14419
14420        // If we upgraded grant all default permissions before kicking off.
14421        for (int userId : grantPermissionsUserIds) {
14422            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14423        }
14424
14425        // Kick off any messages waiting for system ready
14426        if (mPostSystemReadyMessages != null) {
14427            for (Message msg : mPostSystemReadyMessages) {
14428                msg.sendToTarget();
14429            }
14430            mPostSystemReadyMessages = null;
14431        }
14432
14433        // Watch for external volumes that come and go over time
14434        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14435        storage.registerListener(mStorageListener);
14436
14437        mInstallerService.systemReady();
14438        mPackageDexOptimizer.systemReady();
14439    }
14440
14441    @Override
14442    public boolean isSafeMode() {
14443        return mSafeMode;
14444    }
14445
14446    @Override
14447    public boolean hasSystemUidErrors() {
14448        return mHasSystemUidErrors;
14449    }
14450
14451    static String arrayToString(int[] array) {
14452        StringBuffer buf = new StringBuffer(128);
14453        buf.append('[');
14454        if (array != null) {
14455            for (int i=0; i<array.length; i++) {
14456                if (i > 0) buf.append(", ");
14457                buf.append(array[i]);
14458            }
14459        }
14460        buf.append(']');
14461        return buf.toString();
14462    }
14463
14464    static class DumpState {
14465        public static final int DUMP_LIBS = 1 << 0;
14466        public static final int DUMP_FEATURES = 1 << 1;
14467        public static final int DUMP_RESOLVERS = 1 << 2;
14468        public static final int DUMP_PERMISSIONS = 1 << 3;
14469        public static final int DUMP_PACKAGES = 1 << 4;
14470        public static final int DUMP_SHARED_USERS = 1 << 5;
14471        public static final int DUMP_MESSAGES = 1 << 6;
14472        public static final int DUMP_PROVIDERS = 1 << 7;
14473        public static final int DUMP_VERIFIERS = 1 << 8;
14474        public static final int DUMP_PREFERRED = 1 << 9;
14475        public static final int DUMP_PREFERRED_XML = 1 << 10;
14476        public static final int DUMP_KEYSETS = 1 << 11;
14477        public static final int DUMP_VERSION = 1 << 12;
14478        public static final int DUMP_INSTALLS = 1 << 13;
14479        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14480        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14481
14482        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14483
14484        private int mTypes;
14485
14486        private int mOptions;
14487
14488        private boolean mTitlePrinted;
14489
14490        private SharedUserSetting mSharedUser;
14491
14492        public boolean isDumping(int type) {
14493            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14494                return true;
14495            }
14496
14497            return (mTypes & type) != 0;
14498        }
14499
14500        public void setDump(int type) {
14501            mTypes |= type;
14502        }
14503
14504        public boolean isOptionEnabled(int option) {
14505            return (mOptions & option) != 0;
14506        }
14507
14508        public void setOptionEnabled(int option) {
14509            mOptions |= option;
14510        }
14511
14512        public boolean onTitlePrinted() {
14513            final boolean printed = mTitlePrinted;
14514            mTitlePrinted = true;
14515            return printed;
14516        }
14517
14518        public boolean getTitlePrinted() {
14519            return mTitlePrinted;
14520        }
14521
14522        public void setTitlePrinted(boolean enabled) {
14523            mTitlePrinted = enabled;
14524        }
14525
14526        public SharedUserSetting getSharedUser() {
14527            return mSharedUser;
14528        }
14529
14530        public void setSharedUser(SharedUserSetting user) {
14531            mSharedUser = user;
14532        }
14533    }
14534
14535    @Override
14536    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14537        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14538                != PackageManager.PERMISSION_GRANTED) {
14539            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14540                    + Binder.getCallingPid()
14541                    + ", uid=" + Binder.getCallingUid()
14542                    + " without permission "
14543                    + android.Manifest.permission.DUMP);
14544            return;
14545        }
14546
14547        DumpState dumpState = new DumpState();
14548        boolean fullPreferred = false;
14549        boolean checkin = false;
14550
14551        String packageName = null;
14552        ArraySet<String> permissionNames = null;
14553
14554        int opti = 0;
14555        while (opti < args.length) {
14556            String opt = args[opti];
14557            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14558                break;
14559            }
14560            opti++;
14561
14562            if ("-a".equals(opt)) {
14563                // Right now we only know how to print all.
14564            } else if ("-h".equals(opt)) {
14565                pw.println("Package manager dump options:");
14566                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14567                pw.println("    --checkin: dump for a checkin");
14568                pw.println("    -f: print details of intent filters");
14569                pw.println("    -h: print this help");
14570                pw.println("  cmd may be one of:");
14571                pw.println("    l[ibraries]: list known shared libraries");
14572                pw.println("    f[ibraries]: list device features");
14573                pw.println("    k[eysets]: print known keysets");
14574                pw.println("    r[esolvers]: dump intent resolvers");
14575                pw.println("    perm[issions]: dump permissions");
14576                pw.println("    permission [name ...]: dump declaration and use of given permission");
14577                pw.println("    pref[erred]: print preferred package settings");
14578                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14579                pw.println("    prov[iders]: dump content providers");
14580                pw.println("    p[ackages]: dump installed packages");
14581                pw.println("    s[hared-users]: dump shared user IDs");
14582                pw.println("    m[essages]: print collected runtime messages");
14583                pw.println("    v[erifiers]: print package verifier info");
14584                pw.println("    version: print database version info");
14585                pw.println("    write: write current settings now");
14586                pw.println("    <package.name>: info about given package");
14587                pw.println("    installs: details about install sessions");
14588                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14589                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14590                return;
14591            } else if ("--checkin".equals(opt)) {
14592                checkin = true;
14593            } else if ("-f".equals(opt)) {
14594                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14595            } else {
14596                pw.println("Unknown argument: " + opt + "; use -h for help");
14597            }
14598        }
14599
14600        // Is the caller requesting to dump a particular piece of data?
14601        if (opti < args.length) {
14602            String cmd = args[opti];
14603            opti++;
14604            // Is this a package name?
14605            if ("android".equals(cmd) || cmd.contains(".")) {
14606                packageName = cmd;
14607                // When dumping a single package, we always dump all of its
14608                // filter information since the amount of data will be reasonable.
14609                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14610            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14611                dumpState.setDump(DumpState.DUMP_LIBS);
14612            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14613                dumpState.setDump(DumpState.DUMP_FEATURES);
14614            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14615                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14616            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14617                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14618            } else if ("permission".equals(cmd)) {
14619                if (opti >= args.length) {
14620                    pw.println("Error: permission requires permission name");
14621                    return;
14622                }
14623                permissionNames = new ArraySet<>();
14624                while (opti < args.length) {
14625                    permissionNames.add(args[opti]);
14626                    opti++;
14627                }
14628                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14629                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14630            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14631                dumpState.setDump(DumpState.DUMP_PREFERRED);
14632            } else if ("preferred-xml".equals(cmd)) {
14633                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14634                if (opti < args.length && "--full".equals(args[opti])) {
14635                    fullPreferred = true;
14636                    opti++;
14637                }
14638            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14639                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14640            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14641                dumpState.setDump(DumpState.DUMP_PACKAGES);
14642            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14643                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14644            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14645                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14646            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14647                dumpState.setDump(DumpState.DUMP_MESSAGES);
14648            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14649                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14650            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14651                    || "intent-filter-verifiers".equals(cmd)) {
14652                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14653            } else if ("version".equals(cmd)) {
14654                dumpState.setDump(DumpState.DUMP_VERSION);
14655            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14656                dumpState.setDump(DumpState.DUMP_KEYSETS);
14657            } else if ("installs".equals(cmd)) {
14658                dumpState.setDump(DumpState.DUMP_INSTALLS);
14659            } else if ("write".equals(cmd)) {
14660                synchronized (mPackages) {
14661                    mSettings.writeLPr();
14662                    pw.println("Settings written.");
14663                    return;
14664                }
14665            }
14666        }
14667
14668        if (checkin) {
14669            pw.println("vers,1");
14670        }
14671
14672        // reader
14673        synchronized (mPackages) {
14674            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14675                if (!checkin) {
14676                    if (dumpState.onTitlePrinted())
14677                        pw.println();
14678                    pw.println("Database versions:");
14679                    pw.print("  SDK Version:");
14680                    pw.print(" internal=");
14681                    pw.print(mSettings.mInternalSdkPlatform);
14682                    pw.print(" external=");
14683                    pw.println(mSettings.mExternalSdkPlatform);
14684                    pw.print("  DB Version:");
14685                    pw.print(" internal=");
14686                    pw.print(mSettings.mInternalDatabaseVersion);
14687                    pw.print(" external=");
14688                    pw.println(mSettings.mExternalDatabaseVersion);
14689                }
14690            }
14691
14692            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14693                if (!checkin) {
14694                    if (dumpState.onTitlePrinted())
14695                        pw.println();
14696                    pw.println("Verifiers:");
14697                    pw.print("  Required: ");
14698                    pw.print(mRequiredVerifierPackage);
14699                    pw.print(" (uid=");
14700                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14701                    pw.println(")");
14702                } else if (mRequiredVerifierPackage != null) {
14703                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14704                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14705                }
14706            }
14707
14708            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14709                    packageName == null) {
14710                if (mIntentFilterVerifierComponent != null) {
14711                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14712                    if (!checkin) {
14713                        if (dumpState.onTitlePrinted())
14714                            pw.println();
14715                        pw.println("Intent Filter Verifier:");
14716                        pw.print("  Using: ");
14717                        pw.print(verifierPackageName);
14718                        pw.print(" (uid=");
14719                        pw.print(getPackageUid(verifierPackageName, 0));
14720                        pw.println(")");
14721                    } else if (verifierPackageName != null) {
14722                        pw.print("ifv,"); pw.print(verifierPackageName);
14723                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14724                    }
14725                } else {
14726                    pw.println();
14727                    pw.println("No Intent Filter Verifier available!");
14728                }
14729            }
14730
14731            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14732                boolean printedHeader = false;
14733                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14734                while (it.hasNext()) {
14735                    String name = it.next();
14736                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14737                    if (!checkin) {
14738                        if (!printedHeader) {
14739                            if (dumpState.onTitlePrinted())
14740                                pw.println();
14741                            pw.println("Libraries:");
14742                            printedHeader = true;
14743                        }
14744                        pw.print("  ");
14745                    } else {
14746                        pw.print("lib,");
14747                    }
14748                    pw.print(name);
14749                    if (!checkin) {
14750                        pw.print(" -> ");
14751                    }
14752                    if (ent.path != null) {
14753                        if (!checkin) {
14754                            pw.print("(jar) ");
14755                            pw.print(ent.path);
14756                        } else {
14757                            pw.print(",jar,");
14758                            pw.print(ent.path);
14759                        }
14760                    } else {
14761                        if (!checkin) {
14762                            pw.print("(apk) ");
14763                            pw.print(ent.apk);
14764                        } else {
14765                            pw.print(",apk,");
14766                            pw.print(ent.apk);
14767                        }
14768                    }
14769                    pw.println();
14770                }
14771            }
14772
14773            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14774                if (dumpState.onTitlePrinted())
14775                    pw.println();
14776                if (!checkin) {
14777                    pw.println("Features:");
14778                }
14779                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14780                while (it.hasNext()) {
14781                    String name = it.next();
14782                    if (!checkin) {
14783                        pw.print("  ");
14784                    } else {
14785                        pw.print("feat,");
14786                    }
14787                    pw.println(name);
14788                }
14789            }
14790
14791            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14792                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14793                        : "Activity Resolver Table:", "  ", packageName,
14794                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14795                    dumpState.setTitlePrinted(true);
14796                }
14797                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14798                        : "Receiver Resolver Table:", "  ", packageName,
14799                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14800                    dumpState.setTitlePrinted(true);
14801                }
14802                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14803                        : "Service Resolver Table:", "  ", packageName,
14804                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14805                    dumpState.setTitlePrinted(true);
14806                }
14807                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14808                        : "Provider Resolver Table:", "  ", packageName,
14809                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14810                    dumpState.setTitlePrinted(true);
14811                }
14812            }
14813
14814            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14815                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14816                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14817                    int user = mSettings.mPreferredActivities.keyAt(i);
14818                    if (pir.dump(pw,
14819                            dumpState.getTitlePrinted()
14820                                ? "\nPreferred Activities User " + user + ":"
14821                                : "Preferred Activities User " + user + ":", "  ",
14822                            packageName, true, false)) {
14823                        dumpState.setTitlePrinted(true);
14824                    }
14825                }
14826            }
14827
14828            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14829                pw.flush();
14830                FileOutputStream fout = new FileOutputStream(fd);
14831                BufferedOutputStream str = new BufferedOutputStream(fout);
14832                XmlSerializer serializer = new FastXmlSerializer();
14833                try {
14834                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14835                    serializer.startDocument(null, true);
14836                    serializer.setFeature(
14837                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14838                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14839                    serializer.endDocument();
14840                    serializer.flush();
14841                } catch (IllegalArgumentException e) {
14842                    pw.println("Failed writing: " + e);
14843                } catch (IllegalStateException e) {
14844                    pw.println("Failed writing: " + e);
14845                } catch (IOException e) {
14846                    pw.println("Failed writing: " + e);
14847                }
14848            }
14849
14850            if (!checkin
14851                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14852                    && packageName == null) {
14853                pw.println();
14854                int count = mSettings.mPackages.size();
14855                if (count == 0) {
14856                    pw.println("No applications!");
14857                    pw.println();
14858                } else {
14859                    final String prefix = "  ";
14860                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14861                    if (allPackageSettings.size() == 0) {
14862                        pw.println("No domain preferred apps!");
14863                        pw.println();
14864                    } else {
14865                        pw.println("App verification status:");
14866                        pw.println();
14867                        count = 0;
14868                        for (PackageSetting ps : allPackageSettings) {
14869                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14870                            if (ivi == null || ivi.getPackageName() == null) continue;
14871                            pw.println(prefix + "Package: " + ivi.getPackageName());
14872                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14873                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14874                            pw.println();
14875                            count++;
14876                        }
14877                        if (count == 0) {
14878                            pw.println(prefix + "No app verification established.");
14879                            pw.println();
14880                        }
14881                        for (int userId : sUserManager.getUserIds()) {
14882                            pw.println("App linkages for user " + userId + ":");
14883                            pw.println();
14884                            count = 0;
14885                            for (PackageSetting ps : allPackageSettings) {
14886                                final int status = ps.getDomainVerificationStatusForUser(userId);
14887                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14888                                    continue;
14889                                }
14890                                pw.println(prefix + "Package: " + ps.name);
14891                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14892                                String statusStr = IntentFilterVerificationInfo.
14893                                        getStatusStringFromValue(status);
14894                                pw.println(prefix + "Status:  " + statusStr);
14895                                pw.println();
14896                                count++;
14897                            }
14898                            if (count == 0) {
14899                                pw.println(prefix + "No configured app linkages.");
14900                                pw.println();
14901                            }
14902                        }
14903                    }
14904                }
14905            }
14906
14907            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14908                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14909                if (packageName == null && permissionNames == null) {
14910                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14911                        if (iperm == 0) {
14912                            if (dumpState.onTitlePrinted())
14913                                pw.println();
14914                            pw.println("AppOp Permissions:");
14915                        }
14916                        pw.print("  AppOp Permission ");
14917                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14918                        pw.println(":");
14919                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14920                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14921                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14922                        }
14923                    }
14924                }
14925            }
14926
14927            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14928                boolean printedSomething = false;
14929                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14930                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14931                        continue;
14932                    }
14933                    if (!printedSomething) {
14934                        if (dumpState.onTitlePrinted())
14935                            pw.println();
14936                        pw.println("Registered ContentProviders:");
14937                        printedSomething = true;
14938                    }
14939                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14940                    pw.print("    "); pw.println(p.toString());
14941                }
14942                printedSomething = false;
14943                for (Map.Entry<String, PackageParser.Provider> entry :
14944                        mProvidersByAuthority.entrySet()) {
14945                    PackageParser.Provider p = entry.getValue();
14946                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14947                        continue;
14948                    }
14949                    if (!printedSomething) {
14950                        if (dumpState.onTitlePrinted())
14951                            pw.println();
14952                        pw.println("ContentProvider Authorities:");
14953                        printedSomething = true;
14954                    }
14955                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14956                    pw.print("    "); pw.println(p.toString());
14957                    if (p.info != null && p.info.applicationInfo != null) {
14958                        final String appInfo = p.info.applicationInfo.toString();
14959                        pw.print("      applicationInfo="); pw.println(appInfo);
14960                    }
14961                }
14962            }
14963
14964            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14965                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14966            }
14967
14968            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14969                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14970            }
14971
14972            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14973                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14974            }
14975
14976            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14977                // XXX should handle packageName != null by dumping only install data that
14978                // the given package is involved with.
14979                if (dumpState.onTitlePrinted()) pw.println();
14980                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14981            }
14982
14983            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14984                if (dumpState.onTitlePrinted()) pw.println();
14985                mSettings.dumpReadMessagesLPr(pw, dumpState);
14986
14987                pw.println();
14988                pw.println("Package warning messages:");
14989                BufferedReader in = null;
14990                String line = null;
14991                try {
14992                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14993                    while ((line = in.readLine()) != null) {
14994                        if (line.contains("ignored: updated version")) continue;
14995                        pw.println(line);
14996                    }
14997                } catch (IOException ignored) {
14998                } finally {
14999                    IoUtils.closeQuietly(in);
15000                }
15001            }
15002
15003            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15004                BufferedReader in = null;
15005                String line = null;
15006                try {
15007                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15008                    while ((line = in.readLine()) != null) {
15009                        if (line.contains("ignored: updated version")) continue;
15010                        pw.print("msg,");
15011                        pw.println(line);
15012                    }
15013                } catch (IOException ignored) {
15014                } finally {
15015                    IoUtils.closeQuietly(in);
15016                }
15017            }
15018        }
15019    }
15020
15021    private String dumpDomainString(String packageName) {
15022        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15023        List<IntentFilter> filters = getAllIntentFilters(packageName);
15024
15025        ArraySet<String> result = new ArraySet<>();
15026        if (iviList.size() > 0) {
15027            for (IntentFilterVerificationInfo ivi : iviList) {
15028                for (String host : ivi.getDomains()) {
15029                    result.add(host);
15030                }
15031            }
15032        }
15033        if (filters != null && filters.size() > 0) {
15034            for (IntentFilter filter : filters) {
15035                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15036                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15037                    result.addAll(filter.getHostsList());
15038                }
15039            }
15040        }
15041
15042        StringBuilder sb = new StringBuilder(result.size() * 16);
15043        for (String domain : result) {
15044            if (sb.length() > 0) sb.append(" ");
15045            sb.append(domain);
15046        }
15047        return sb.toString();
15048    }
15049
15050    // ------- apps on sdcard specific code -------
15051    static final boolean DEBUG_SD_INSTALL = false;
15052
15053    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15054
15055    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15056
15057    private boolean mMediaMounted = false;
15058
15059    static String getEncryptKey() {
15060        try {
15061            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15062                    SD_ENCRYPTION_KEYSTORE_NAME);
15063            if (sdEncKey == null) {
15064                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15065                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15066                if (sdEncKey == null) {
15067                    Slog.e(TAG, "Failed to create encryption keys");
15068                    return null;
15069                }
15070            }
15071            return sdEncKey;
15072        } catch (NoSuchAlgorithmException nsae) {
15073            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15074            return null;
15075        } catch (IOException ioe) {
15076            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15077            return null;
15078        }
15079    }
15080
15081    /*
15082     * Update media status on PackageManager.
15083     */
15084    @Override
15085    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15086        int callingUid = Binder.getCallingUid();
15087        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15088            throw new SecurityException("Media status can only be updated by the system");
15089        }
15090        // reader; this apparently protects mMediaMounted, but should probably
15091        // be a different lock in that case.
15092        synchronized (mPackages) {
15093            Log.i(TAG, "Updating external media status from "
15094                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15095                    + (mediaStatus ? "mounted" : "unmounted"));
15096            if (DEBUG_SD_INSTALL)
15097                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15098                        + ", mMediaMounted=" + mMediaMounted);
15099            if (mediaStatus == mMediaMounted) {
15100                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15101                        : 0, -1);
15102                mHandler.sendMessage(msg);
15103                return;
15104            }
15105            mMediaMounted = mediaStatus;
15106        }
15107        // Queue up an async operation since the package installation may take a
15108        // little while.
15109        mHandler.post(new Runnable() {
15110            public void run() {
15111                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15112            }
15113        });
15114    }
15115
15116    /**
15117     * Called by MountService when the initial ASECs to scan are available.
15118     * Should block until all the ASEC containers are finished being scanned.
15119     */
15120    public void scanAvailableAsecs() {
15121        updateExternalMediaStatusInner(true, false, false);
15122        if (mShouldRestoreconData) {
15123            SELinuxMMAC.setRestoreconDone();
15124            mShouldRestoreconData = false;
15125        }
15126    }
15127
15128    /*
15129     * Collect information of applications on external media, map them against
15130     * existing containers and update information based on current mount status.
15131     * Please note that we always have to report status if reportStatus has been
15132     * set to true especially when unloading packages.
15133     */
15134    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15135            boolean externalStorage) {
15136        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15137        int[] uidArr = EmptyArray.INT;
15138
15139        final String[] list = PackageHelper.getSecureContainerList();
15140        if (ArrayUtils.isEmpty(list)) {
15141            Log.i(TAG, "No secure containers found");
15142        } else {
15143            // Process list of secure containers and categorize them
15144            // as active or stale based on their package internal state.
15145
15146            // reader
15147            synchronized (mPackages) {
15148                for (String cid : list) {
15149                    // Leave stages untouched for now; installer service owns them
15150                    if (PackageInstallerService.isStageName(cid)) continue;
15151
15152                    if (DEBUG_SD_INSTALL)
15153                        Log.i(TAG, "Processing container " + cid);
15154                    String pkgName = getAsecPackageName(cid);
15155                    if (pkgName == null) {
15156                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15157                        continue;
15158                    }
15159                    if (DEBUG_SD_INSTALL)
15160                        Log.i(TAG, "Looking for pkg : " + pkgName);
15161
15162                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15163                    if (ps == null) {
15164                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15165                        continue;
15166                    }
15167
15168                    /*
15169                     * Skip packages that are not external if we're unmounting
15170                     * external storage.
15171                     */
15172                    if (externalStorage && !isMounted && !isExternal(ps)) {
15173                        continue;
15174                    }
15175
15176                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15177                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15178                    // The package status is changed only if the code path
15179                    // matches between settings and the container id.
15180                    if (ps.codePathString != null
15181                            && ps.codePathString.startsWith(args.getCodePath())) {
15182                        if (DEBUG_SD_INSTALL) {
15183                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15184                                    + " at code path: " + ps.codePathString);
15185                        }
15186
15187                        // We do have a valid package installed on sdcard
15188                        processCids.put(args, ps.codePathString);
15189                        final int uid = ps.appId;
15190                        if (uid != -1) {
15191                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15192                        }
15193                    } else {
15194                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15195                                + ps.codePathString);
15196                    }
15197                }
15198            }
15199
15200            Arrays.sort(uidArr);
15201        }
15202
15203        // Process packages with valid entries.
15204        if (isMounted) {
15205            if (DEBUG_SD_INSTALL)
15206                Log.i(TAG, "Loading packages");
15207            loadMediaPackages(processCids, uidArr);
15208            startCleaningPackages();
15209            mInstallerService.onSecureContainersAvailable();
15210        } else {
15211            if (DEBUG_SD_INSTALL)
15212                Log.i(TAG, "Unloading packages");
15213            unloadMediaPackages(processCids, uidArr, reportStatus);
15214        }
15215    }
15216
15217    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15218            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15219        final int size = infos.size();
15220        final String[] packageNames = new String[size];
15221        final int[] packageUids = new int[size];
15222        for (int i = 0; i < size; i++) {
15223            final ApplicationInfo info = infos.get(i);
15224            packageNames[i] = info.packageName;
15225            packageUids[i] = info.uid;
15226        }
15227        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15228                finishedReceiver);
15229    }
15230
15231    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15232            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15233        sendResourcesChangedBroadcast(mediaStatus, replacing,
15234                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15235    }
15236
15237    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15238            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15239        int size = pkgList.length;
15240        if (size > 0) {
15241            // Send broadcasts here
15242            Bundle extras = new Bundle();
15243            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15244            if (uidArr != null) {
15245                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15246            }
15247            if (replacing) {
15248                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15249            }
15250            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15251                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15252            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15253        }
15254    }
15255
15256   /*
15257     * Look at potentially valid container ids from processCids If package
15258     * information doesn't match the one on record or package scanning fails,
15259     * the cid is added to list of removeCids. We currently don't delete stale
15260     * containers.
15261     */
15262    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15263        ArrayList<String> pkgList = new ArrayList<String>();
15264        Set<AsecInstallArgs> keys = processCids.keySet();
15265
15266        for (AsecInstallArgs args : keys) {
15267            String codePath = processCids.get(args);
15268            if (DEBUG_SD_INSTALL)
15269                Log.i(TAG, "Loading container : " + args.cid);
15270            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15271            try {
15272                // Make sure there are no container errors first.
15273                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15274                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15275                            + " when installing from sdcard");
15276                    continue;
15277                }
15278                // Check code path here.
15279                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15280                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15281                            + " does not match one in settings " + codePath);
15282                    continue;
15283                }
15284                // Parse package
15285                int parseFlags = mDefParseFlags;
15286                if (args.isExternalAsec()) {
15287                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15288                }
15289                if (args.isFwdLocked()) {
15290                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15291                }
15292
15293                synchronized (mInstallLock) {
15294                    PackageParser.Package pkg = null;
15295                    try {
15296                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15297                    } catch (PackageManagerException e) {
15298                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15299                    }
15300                    // Scan the package
15301                    if (pkg != null) {
15302                        /*
15303                         * TODO why is the lock being held? doPostInstall is
15304                         * called in other places without the lock. This needs
15305                         * to be straightened out.
15306                         */
15307                        // writer
15308                        synchronized (mPackages) {
15309                            retCode = PackageManager.INSTALL_SUCCEEDED;
15310                            pkgList.add(pkg.packageName);
15311                            // Post process args
15312                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15313                                    pkg.applicationInfo.uid);
15314                        }
15315                    } else {
15316                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15317                    }
15318                }
15319
15320            } finally {
15321                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15322                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15323                }
15324            }
15325        }
15326        // writer
15327        synchronized (mPackages) {
15328            // If the platform SDK has changed since the last time we booted,
15329            // we need to re-grant app permission to catch any new ones that
15330            // appear. This is really a hack, and means that apps can in some
15331            // cases get permissions that the user didn't initially explicitly
15332            // allow... it would be nice to have some better way to handle
15333            // this situation.
15334            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15335            if (regrantPermissions)
15336                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15337                        + mSdkVersion + "; regranting permissions for external storage");
15338            mSettings.mExternalSdkPlatform = mSdkVersion;
15339
15340            // Make sure group IDs have been assigned, and any permission
15341            // changes in other apps are accounted for
15342            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15343                    | (regrantPermissions
15344                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15345                            : 0));
15346
15347            mSettings.updateExternalDatabaseVersion();
15348
15349            // can downgrade to reader
15350            // Persist settings
15351            mSettings.writeLPr();
15352        }
15353        // Send a broadcast to let everyone know we are done processing
15354        if (pkgList.size() > 0) {
15355            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15356        }
15357    }
15358
15359   /*
15360     * Utility method to unload a list of specified containers
15361     */
15362    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15363        // Just unmount all valid containers.
15364        for (AsecInstallArgs arg : cidArgs) {
15365            synchronized (mInstallLock) {
15366                arg.doPostDeleteLI(false);
15367           }
15368       }
15369   }
15370
15371    /*
15372     * Unload packages mounted on external media. This involves deleting package
15373     * data from internal structures, sending broadcasts about diabled packages,
15374     * gc'ing to free up references, unmounting all secure containers
15375     * corresponding to packages on external media, and posting a
15376     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15377     * that we always have to post this message if status has been requested no
15378     * matter what.
15379     */
15380    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15381            final boolean reportStatus) {
15382        if (DEBUG_SD_INSTALL)
15383            Log.i(TAG, "unloading media packages");
15384        ArrayList<String> pkgList = new ArrayList<String>();
15385        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15386        final Set<AsecInstallArgs> keys = processCids.keySet();
15387        for (AsecInstallArgs args : keys) {
15388            String pkgName = args.getPackageName();
15389            if (DEBUG_SD_INSTALL)
15390                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15391            // Delete package internally
15392            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15393            synchronized (mInstallLock) {
15394                boolean res = deletePackageLI(pkgName, null, false, null, null,
15395                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15396                if (res) {
15397                    pkgList.add(pkgName);
15398                } else {
15399                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15400                    failedList.add(args);
15401                }
15402            }
15403        }
15404
15405        // reader
15406        synchronized (mPackages) {
15407            // We didn't update the settings after removing each package;
15408            // write them now for all packages.
15409            mSettings.writeLPr();
15410        }
15411
15412        // We have to absolutely send UPDATED_MEDIA_STATUS only
15413        // after confirming that all the receivers processed the ordered
15414        // broadcast when packages get disabled, force a gc to clean things up.
15415        // and unload all the containers.
15416        if (pkgList.size() > 0) {
15417            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15418                    new IIntentReceiver.Stub() {
15419                public void performReceive(Intent intent, int resultCode, String data,
15420                        Bundle extras, boolean ordered, boolean sticky,
15421                        int sendingUser) throws RemoteException {
15422                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15423                            reportStatus ? 1 : 0, 1, keys);
15424                    mHandler.sendMessage(msg);
15425                }
15426            });
15427        } else {
15428            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15429                    keys);
15430            mHandler.sendMessage(msg);
15431        }
15432    }
15433
15434    private void loadPrivatePackages(VolumeInfo vol) {
15435        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15436        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15437        synchronized (mInstallLock) {
15438        synchronized (mPackages) {
15439            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15440            for (PackageSetting ps : packages) {
15441                final PackageParser.Package pkg;
15442                try {
15443                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15444                    loaded.add(pkg.applicationInfo);
15445                } catch (PackageManagerException e) {
15446                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15447                }
15448            }
15449
15450            // TODO: regrant any permissions that changed based since original install
15451
15452            mSettings.writeLPr();
15453        }
15454        }
15455
15456        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15457        sendResourcesChangedBroadcast(true, false, loaded, null);
15458    }
15459
15460    private void unloadPrivatePackages(VolumeInfo vol) {
15461        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15462        synchronized (mInstallLock) {
15463        synchronized (mPackages) {
15464            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15465            for (PackageSetting ps : packages) {
15466                if (ps.pkg == null) continue;
15467
15468                final ApplicationInfo info = ps.pkg.applicationInfo;
15469                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15470                if (deletePackageLI(ps.name, null, false, null, null,
15471                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15472                    unloaded.add(info);
15473                } else {
15474                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15475                }
15476            }
15477
15478            mSettings.writeLPr();
15479        }
15480        }
15481
15482        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15483        sendResourcesChangedBroadcast(false, false, unloaded, null);
15484    }
15485
15486    /**
15487     * Examine all users present on given mounted volume, and destroy data
15488     * belonging to users that are no longer valid, or whose user ID has been
15489     * recycled.
15490     */
15491    private void reconcileUsers(String volumeUuid) {
15492        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15493        if (ArrayUtils.isEmpty(files)) {
15494            Slog.d(TAG, "No users found on " + volumeUuid);
15495            return;
15496        }
15497
15498        for (File file : files) {
15499            if (!file.isDirectory()) continue;
15500
15501            final int userId;
15502            final UserInfo info;
15503            try {
15504                userId = Integer.parseInt(file.getName());
15505                info = sUserManager.getUserInfo(userId);
15506            } catch (NumberFormatException e) {
15507                Slog.w(TAG, "Invalid user directory " + file);
15508                continue;
15509            }
15510
15511            boolean destroyUser = false;
15512            if (info == null) {
15513                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15514                        + " because no matching user was found");
15515                destroyUser = true;
15516            } else {
15517                try {
15518                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15519                } catch (IOException e) {
15520                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15521                            + " because we failed to enforce serial number: " + e);
15522                    destroyUser = true;
15523                }
15524            }
15525
15526            if (destroyUser) {
15527                synchronized (mInstallLock) {
15528                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15529                }
15530            }
15531        }
15532
15533        final UserManager um = mContext.getSystemService(UserManager.class);
15534        for (UserInfo user : um.getUsers()) {
15535            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15536            if (userDir.exists()) continue;
15537
15538            try {
15539                UserManagerService.prepareUserDirectory(userDir);
15540                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15541            } catch (IOException e) {
15542                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15543            }
15544        }
15545    }
15546
15547    /**
15548     * Examine all apps present on given mounted volume, and destroy apps that
15549     * aren't expected, either due to uninstallation or reinstallation on
15550     * another volume.
15551     */
15552    private void reconcileApps(String volumeUuid) {
15553        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15554        if (ArrayUtils.isEmpty(files)) {
15555            Slog.d(TAG, "No apps found on " + volumeUuid);
15556            return;
15557        }
15558
15559        for (File file : files) {
15560            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15561                    && !PackageInstallerService.isStageName(file.getName());
15562            if (!isPackage) {
15563                // Ignore entries which are not packages
15564                continue;
15565            }
15566
15567            boolean destroyApp = false;
15568            String packageName = null;
15569            try {
15570                final PackageLite pkg = PackageParser.parsePackageLite(file,
15571                        PackageParser.PARSE_MUST_BE_APK);
15572                packageName = pkg.packageName;
15573
15574                synchronized (mPackages) {
15575                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15576                    if (ps == null) {
15577                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15578                                + volumeUuid + " because we found no install record");
15579                        destroyApp = true;
15580                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15581                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15582                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15583                        destroyApp = true;
15584                    }
15585                }
15586
15587            } catch (PackageParserException e) {
15588                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15589                destroyApp = true;
15590            }
15591
15592            if (destroyApp) {
15593                synchronized (mInstallLock) {
15594                    if (packageName != null) {
15595                        removeDataDirsLI(volumeUuid, packageName);
15596                    }
15597                    if (file.isDirectory()) {
15598                        mInstaller.rmPackageDir(file.getAbsolutePath());
15599                    } else {
15600                        file.delete();
15601                    }
15602                }
15603            }
15604        }
15605    }
15606
15607    private void unfreezePackage(String packageName) {
15608        synchronized (mPackages) {
15609            final PackageSetting ps = mSettings.mPackages.get(packageName);
15610            if (ps != null) {
15611                ps.frozen = false;
15612            }
15613        }
15614    }
15615
15616    @Override
15617    public int movePackage(final String packageName, final String volumeUuid) {
15618        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15619
15620        final int moveId = mNextMoveId.getAndIncrement();
15621        try {
15622            movePackageInternal(packageName, volumeUuid, moveId);
15623        } catch (PackageManagerException e) {
15624            Slog.w(TAG, "Failed to move " + packageName, e);
15625            mMoveCallbacks.notifyStatusChanged(moveId,
15626                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15627        }
15628        return moveId;
15629    }
15630
15631    private void movePackageInternal(final String packageName, final String volumeUuid,
15632            final int moveId) throws PackageManagerException {
15633        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15634        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15635        final PackageManager pm = mContext.getPackageManager();
15636
15637        final boolean currentAsec;
15638        final String currentVolumeUuid;
15639        final File codeFile;
15640        final String installerPackageName;
15641        final String packageAbiOverride;
15642        final int appId;
15643        final String seinfo;
15644        final String label;
15645
15646        // reader
15647        synchronized (mPackages) {
15648            final PackageParser.Package pkg = mPackages.get(packageName);
15649            final PackageSetting ps = mSettings.mPackages.get(packageName);
15650            if (pkg == null || ps == null) {
15651                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15652            }
15653
15654            if (pkg.applicationInfo.isSystemApp()) {
15655                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15656                        "Cannot move system application");
15657            }
15658
15659            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15660                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15661                        "Package already moved to " + volumeUuid);
15662            }
15663
15664            final File probe = new File(pkg.codePath);
15665            final File probeOat = new File(probe, "oat");
15666            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15667                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15668                        "Move only supported for modern cluster style installs");
15669            }
15670
15671            if (ps.frozen) {
15672                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15673                        "Failed to move already frozen package");
15674            }
15675            ps.frozen = true;
15676
15677            currentAsec = pkg.applicationInfo.isForwardLocked()
15678                    || pkg.applicationInfo.isExternalAsec();
15679            currentVolumeUuid = ps.volumeUuid;
15680            codeFile = new File(pkg.codePath);
15681            installerPackageName = ps.installerPackageName;
15682            packageAbiOverride = ps.cpuAbiOverrideString;
15683            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15684            seinfo = pkg.applicationInfo.seinfo;
15685            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15686        }
15687
15688        // Now that we're guarded by frozen state, kill app during move
15689        killApplication(packageName, appId, "move pkg");
15690
15691        final Bundle extras = new Bundle();
15692        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15693        extras.putString(Intent.EXTRA_TITLE, label);
15694        mMoveCallbacks.notifyCreated(moveId, extras);
15695
15696        int installFlags;
15697        final boolean moveCompleteApp;
15698        final File measurePath;
15699
15700        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15701            installFlags = INSTALL_INTERNAL;
15702            moveCompleteApp = !currentAsec;
15703            measurePath = Environment.getDataAppDirectory(volumeUuid);
15704        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15705            installFlags = INSTALL_EXTERNAL;
15706            moveCompleteApp = false;
15707            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15708        } else {
15709            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15710            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15711                    || !volume.isMountedWritable()) {
15712                unfreezePackage(packageName);
15713                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15714                        "Move location not mounted private volume");
15715            }
15716
15717            Preconditions.checkState(!currentAsec);
15718
15719            installFlags = INSTALL_INTERNAL;
15720            moveCompleteApp = true;
15721            measurePath = Environment.getDataAppDirectory(volumeUuid);
15722        }
15723
15724        final PackageStats stats = new PackageStats(null, -1);
15725        synchronized (mInstaller) {
15726            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15727                unfreezePackage(packageName);
15728                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15729                        "Failed to measure package size");
15730            }
15731        }
15732
15733        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15734                + stats.dataSize);
15735
15736        final long startFreeBytes = measurePath.getFreeSpace();
15737        final long sizeBytes;
15738        if (moveCompleteApp) {
15739            sizeBytes = stats.codeSize + stats.dataSize;
15740        } else {
15741            sizeBytes = stats.codeSize;
15742        }
15743
15744        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15745            unfreezePackage(packageName);
15746            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15747                    "Not enough free space to move");
15748        }
15749
15750        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15751
15752        final CountDownLatch installedLatch = new CountDownLatch(1);
15753        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15754            @Override
15755            public void onUserActionRequired(Intent intent) throws RemoteException {
15756                throw new IllegalStateException();
15757            }
15758
15759            @Override
15760            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15761                    Bundle extras) throws RemoteException {
15762                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15763                        + PackageManager.installStatusToString(returnCode, msg));
15764
15765                installedLatch.countDown();
15766
15767                // Regardless of success or failure of the move operation,
15768                // always unfreeze the package
15769                unfreezePackage(packageName);
15770
15771                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15772                switch (status) {
15773                    case PackageInstaller.STATUS_SUCCESS:
15774                        mMoveCallbacks.notifyStatusChanged(moveId,
15775                                PackageManager.MOVE_SUCCEEDED);
15776                        break;
15777                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15778                        mMoveCallbacks.notifyStatusChanged(moveId,
15779                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15780                        break;
15781                    default:
15782                        mMoveCallbacks.notifyStatusChanged(moveId,
15783                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15784                        break;
15785                }
15786            }
15787        };
15788
15789        final MoveInfo move;
15790        if (moveCompleteApp) {
15791            // Kick off a thread to report progress estimates
15792            new Thread() {
15793                @Override
15794                public void run() {
15795                    while (true) {
15796                        try {
15797                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15798                                break;
15799                            }
15800                        } catch (InterruptedException ignored) {
15801                        }
15802
15803                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15804                        final int progress = 10 + (int) MathUtils.constrain(
15805                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15806                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15807                    }
15808                }
15809            }.start();
15810
15811            final String dataAppName = codeFile.getName();
15812            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15813                    dataAppName, appId, seinfo);
15814        } else {
15815            move = null;
15816        }
15817
15818        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15819
15820        final Message msg = mHandler.obtainMessage(INIT_COPY);
15821        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15822        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15823                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15824        mHandler.sendMessage(msg);
15825    }
15826
15827    @Override
15828    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15829        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15830
15831        final int realMoveId = mNextMoveId.getAndIncrement();
15832        final Bundle extras = new Bundle();
15833        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15834        mMoveCallbacks.notifyCreated(realMoveId, extras);
15835
15836        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15837            @Override
15838            public void onCreated(int moveId, Bundle extras) {
15839                // Ignored
15840            }
15841
15842            @Override
15843            public void onStatusChanged(int moveId, int status, long estMillis) {
15844                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15845            }
15846        };
15847
15848        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15849        storage.setPrimaryStorageUuid(volumeUuid, callback);
15850        return realMoveId;
15851    }
15852
15853    @Override
15854    public int getMoveStatus(int moveId) {
15855        mContext.enforceCallingOrSelfPermission(
15856                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15857        return mMoveCallbacks.mLastStatus.get(moveId);
15858    }
15859
15860    @Override
15861    public void registerMoveCallback(IPackageMoveObserver callback) {
15862        mContext.enforceCallingOrSelfPermission(
15863                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15864        mMoveCallbacks.register(callback);
15865    }
15866
15867    @Override
15868    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15869        mContext.enforceCallingOrSelfPermission(
15870                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15871        mMoveCallbacks.unregister(callback);
15872    }
15873
15874    @Override
15875    public boolean setInstallLocation(int loc) {
15876        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15877                null);
15878        if (getInstallLocation() == loc) {
15879            return true;
15880        }
15881        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15882                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15883            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15884                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15885            return true;
15886        }
15887        return false;
15888   }
15889
15890    @Override
15891    public int getInstallLocation() {
15892        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15893                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15894                PackageHelper.APP_INSTALL_AUTO);
15895    }
15896
15897    /** Called by UserManagerService */
15898    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15899        mDirtyUsers.remove(userHandle);
15900        mSettings.removeUserLPw(userHandle);
15901        mPendingBroadcasts.remove(userHandle);
15902        if (mInstaller != null) {
15903            // Technically, we shouldn't be doing this with the package lock
15904            // held.  However, this is very rare, and there is already so much
15905            // other disk I/O going on, that we'll let it slide for now.
15906            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15907            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15908                final String volumeUuid = vol.getFsUuid();
15909                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15910                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15911            }
15912        }
15913        mUserNeedsBadging.delete(userHandle);
15914        removeUnusedPackagesLILPw(userManager, userHandle);
15915    }
15916
15917    /**
15918     * We're removing userHandle and would like to remove any downloaded packages
15919     * that are no longer in use by any other user.
15920     * @param userHandle the user being removed
15921     */
15922    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15923        final boolean DEBUG_CLEAN_APKS = false;
15924        int [] users = userManager.getUserIdsLPr();
15925        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15926        while (psit.hasNext()) {
15927            PackageSetting ps = psit.next();
15928            if (ps.pkg == null) {
15929                continue;
15930            }
15931            final String packageName = ps.pkg.packageName;
15932            // Skip over if system app
15933            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15934                continue;
15935            }
15936            if (DEBUG_CLEAN_APKS) {
15937                Slog.i(TAG, "Checking package " + packageName);
15938            }
15939            boolean keep = false;
15940            for (int i = 0; i < users.length; i++) {
15941                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15942                    keep = true;
15943                    if (DEBUG_CLEAN_APKS) {
15944                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15945                                + users[i]);
15946                    }
15947                    break;
15948                }
15949            }
15950            if (!keep) {
15951                if (DEBUG_CLEAN_APKS) {
15952                    Slog.i(TAG, "  Removing package " + packageName);
15953                }
15954                mHandler.post(new Runnable() {
15955                    public void run() {
15956                        deletePackageX(packageName, userHandle, 0);
15957                    } //end run
15958                });
15959            }
15960        }
15961    }
15962
15963    /** Called by UserManagerService */
15964    void createNewUserLILPw(int userHandle) {
15965        if (mInstaller != null) {
15966            mInstaller.createUserConfig(userHandle);
15967            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15968            applyFactoryDefaultBrowserLPw(userHandle);
15969            primeDomainVerificationsLPw(userHandle);
15970        }
15971    }
15972
15973    void newUserCreated(final int userHandle) {
15974        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15975    }
15976
15977    @Override
15978    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15979        mContext.enforceCallingOrSelfPermission(
15980                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15981                "Only package verification agents can read the verifier device identity");
15982
15983        synchronized (mPackages) {
15984            return mSettings.getVerifierDeviceIdentityLPw();
15985        }
15986    }
15987
15988    @Override
15989    public void setPermissionEnforced(String permission, boolean enforced) {
15990        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15991        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15992            synchronized (mPackages) {
15993                if (mSettings.mReadExternalStorageEnforced == null
15994                        || mSettings.mReadExternalStorageEnforced != enforced) {
15995                    mSettings.mReadExternalStorageEnforced = enforced;
15996                    mSettings.writeLPr();
15997                }
15998            }
15999            // kill any non-foreground processes so we restart them and
16000            // grant/revoke the GID.
16001            final IActivityManager am = ActivityManagerNative.getDefault();
16002            if (am != null) {
16003                final long token = Binder.clearCallingIdentity();
16004                try {
16005                    am.killProcessesBelowForeground("setPermissionEnforcement");
16006                } catch (RemoteException e) {
16007                } finally {
16008                    Binder.restoreCallingIdentity(token);
16009                }
16010            }
16011        } else {
16012            throw new IllegalArgumentException("No selective enforcement for " + permission);
16013        }
16014    }
16015
16016    @Override
16017    @Deprecated
16018    public boolean isPermissionEnforced(String permission) {
16019        return true;
16020    }
16021
16022    @Override
16023    public boolean isStorageLow() {
16024        final long token = Binder.clearCallingIdentity();
16025        try {
16026            final DeviceStorageMonitorInternal
16027                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16028            if (dsm != null) {
16029                return dsm.isMemoryLow();
16030            } else {
16031                return false;
16032            }
16033        } finally {
16034            Binder.restoreCallingIdentity(token);
16035        }
16036    }
16037
16038    @Override
16039    public IPackageInstaller getPackageInstaller() {
16040        return mInstallerService;
16041    }
16042
16043    private boolean userNeedsBadging(int userId) {
16044        int index = mUserNeedsBadging.indexOfKey(userId);
16045        if (index < 0) {
16046            final UserInfo userInfo;
16047            final long token = Binder.clearCallingIdentity();
16048            try {
16049                userInfo = sUserManager.getUserInfo(userId);
16050            } finally {
16051                Binder.restoreCallingIdentity(token);
16052            }
16053            final boolean b;
16054            if (userInfo != null && userInfo.isManagedProfile()) {
16055                b = true;
16056            } else {
16057                b = false;
16058            }
16059            mUserNeedsBadging.put(userId, b);
16060            return b;
16061        }
16062        return mUserNeedsBadging.valueAt(index);
16063    }
16064
16065    @Override
16066    public KeySet getKeySetByAlias(String packageName, String alias) {
16067        if (packageName == null || alias == null) {
16068            return null;
16069        }
16070        synchronized(mPackages) {
16071            final PackageParser.Package pkg = mPackages.get(packageName);
16072            if (pkg == null) {
16073                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16074                throw new IllegalArgumentException("Unknown package: " + packageName);
16075            }
16076            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16077            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16078        }
16079    }
16080
16081    @Override
16082    public KeySet getSigningKeySet(String packageName) {
16083        if (packageName == null) {
16084            return null;
16085        }
16086        synchronized(mPackages) {
16087            final PackageParser.Package pkg = mPackages.get(packageName);
16088            if (pkg == null) {
16089                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16090                throw new IllegalArgumentException("Unknown package: " + packageName);
16091            }
16092            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16093                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16094                throw new SecurityException("May not access signing KeySet of other apps.");
16095            }
16096            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16097            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16098        }
16099    }
16100
16101    @Override
16102    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16103        if (packageName == null || ks == null) {
16104            return false;
16105        }
16106        synchronized(mPackages) {
16107            final PackageParser.Package pkg = mPackages.get(packageName);
16108            if (pkg == null) {
16109                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16110                throw new IllegalArgumentException("Unknown package: " + packageName);
16111            }
16112            IBinder ksh = ks.getToken();
16113            if (ksh instanceof KeySetHandle) {
16114                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16115                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16116            }
16117            return false;
16118        }
16119    }
16120
16121    @Override
16122    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16123        if (packageName == null || ks == null) {
16124            return false;
16125        }
16126        synchronized(mPackages) {
16127            final PackageParser.Package pkg = mPackages.get(packageName);
16128            if (pkg == null) {
16129                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16130                throw new IllegalArgumentException("Unknown package: " + packageName);
16131            }
16132            IBinder ksh = ks.getToken();
16133            if (ksh instanceof KeySetHandle) {
16134                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16135                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16136            }
16137            return false;
16138        }
16139    }
16140
16141    public void getUsageStatsIfNoPackageUsageInfo() {
16142        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16143            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16144            if (usm == null) {
16145                throw new IllegalStateException("UsageStatsManager must be initialized");
16146            }
16147            long now = System.currentTimeMillis();
16148            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16149            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16150                String packageName = entry.getKey();
16151                PackageParser.Package pkg = mPackages.get(packageName);
16152                if (pkg == null) {
16153                    continue;
16154                }
16155                UsageStats usage = entry.getValue();
16156                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16157                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16158            }
16159        }
16160    }
16161
16162    /**
16163     * Check and throw if the given before/after packages would be considered a
16164     * downgrade.
16165     */
16166    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16167            throws PackageManagerException {
16168        if (after.versionCode < before.mVersionCode) {
16169            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16170                    "Update version code " + after.versionCode + " is older than current "
16171                    + before.mVersionCode);
16172        } else if (after.versionCode == before.mVersionCode) {
16173            if (after.baseRevisionCode < before.baseRevisionCode) {
16174                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16175                        "Update base revision code " + after.baseRevisionCode
16176                        + " is older than current " + before.baseRevisionCode);
16177            }
16178
16179            if (!ArrayUtils.isEmpty(after.splitNames)) {
16180                for (int i = 0; i < after.splitNames.length; i++) {
16181                    final String splitName = after.splitNames[i];
16182                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16183                    if (j != -1) {
16184                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16185                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16186                                    "Update split " + splitName + " revision code "
16187                                    + after.splitRevisionCodes[i] + " is older than current "
16188                                    + before.splitRevisionCodes[j]);
16189                        }
16190                    }
16191                }
16192            }
16193        }
16194    }
16195
16196    private static class MoveCallbacks extends Handler {
16197        private static final int MSG_CREATED = 1;
16198        private static final int MSG_STATUS_CHANGED = 2;
16199
16200        private final RemoteCallbackList<IPackageMoveObserver>
16201                mCallbacks = new RemoteCallbackList<>();
16202
16203        private final SparseIntArray mLastStatus = new SparseIntArray();
16204
16205        public MoveCallbacks(Looper looper) {
16206            super(looper);
16207        }
16208
16209        public void register(IPackageMoveObserver callback) {
16210            mCallbacks.register(callback);
16211        }
16212
16213        public void unregister(IPackageMoveObserver callback) {
16214            mCallbacks.unregister(callback);
16215        }
16216
16217        @Override
16218        public void handleMessage(Message msg) {
16219            final SomeArgs args = (SomeArgs) msg.obj;
16220            final int n = mCallbacks.beginBroadcast();
16221            for (int i = 0; i < n; i++) {
16222                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16223                try {
16224                    invokeCallback(callback, msg.what, args);
16225                } catch (RemoteException ignored) {
16226                }
16227            }
16228            mCallbacks.finishBroadcast();
16229            args.recycle();
16230        }
16231
16232        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16233                throws RemoteException {
16234            switch (what) {
16235                case MSG_CREATED: {
16236                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16237                    break;
16238                }
16239                case MSG_STATUS_CHANGED: {
16240                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16241                    break;
16242                }
16243            }
16244        }
16245
16246        private void notifyCreated(int moveId, Bundle extras) {
16247            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16248
16249            final SomeArgs args = SomeArgs.obtain();
16250            args.argi1 = moveId;
16251            args.arg2 = extras;
16252            obtainMessage(MSG_CREATED, args).sendToTarget();
16253        }
16254
16255        private void notifyStatusChanged(int moveId, int status) {
16256            notifyStatusChanged(moveId, status, -1);
16257        }
16258
16259        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16260            Slog.v(TAG, "Move " + moveId + " status " + status);
16261
16262            final SomeArgs args = SomeArgs.obtain();
16263            args.argi1 = moveId;
16264            args.argi2 = status;
16265            args.arg3 = estMillis;
16266            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16267
16268            synchronized (mLastStatus) {
16269                mLastStatus.put(moveId, status);
16270            }
16271        }
16272    }
16273
16274    private final class OnPermissionChangeListeners extends Handler {
16275        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16276
16277        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16278                new RemoteCallbackList<>();
16279
16280        public OnPermissionChangeListeners(Looper looper) {
16281            super(looper);
16282        }
16283
16284        @Override
16285        public void handleMessage(Message msg) {
16286            switch (msg.what) {
16287                case MSG_ON_PERMISSIONS_CHANGED: {
16288                    final int uid = msg.arg1;
16289                    handleOnPermissionsChanged(uid);
16290                } break;
16291            }
16292        }
16293
16294        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16295            mPermissionListeners.register(listener);
16296
16297        }
16298
16299        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16300            mPermissionListeners.unregister(listener);
16301        }
16302
16303        public void onPermissionsChanged(int uid) {
16304            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16305                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16306            }
16307        }
16308
16309        private void handleOnPermissionsChanged(int uid) {
16310            final int count = mPermissionListeners.beginBroadcast();
16311            try {
16312                for (int i = 0; i < count; i++) {
16313                    IOnPermissionsChangeListener callback = mPermissionListeners
16314                            .getBroadcastItem(i);
16315                    try {
16316                        callback.onPermissionsChanged(uid);
16317                    } catch (RemoteException e) {
16318                        Log.e(TAG, "Permission listener is dead", e);
16319                    }
16320                }
16321            } finally {
16322                mPermissionListeners.finishBroadcast();
16323            }
16324        }
16325    }
16326
16327    private class PackageManagerInternalImpl extends PackageManagerInternal {
16328        @Override
16329        public void setLocationPackagesProvider(PackagesProvider provider) {
16330            synchronized (mPackages) {
16331                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16332            }
16333        }
16334
16335        @Override
16336        public void setImePackagesProvider(PackagesProvider provider) {
16337            synchronized (mPackages) {
16338                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16339            }
16340        }
16341
16342        @Override
16343        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16344            synchronized (mPackages) {
16345                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16346            }
16347        }
16348
16349        @Override
16350        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16351            synchronized (mPackages) {
16352                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16353            }
16354        }
16355
16356        @Override
16357        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16358            synchronized (mPackages) {
16359                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16360            }
16361        }
16362
16363        @Override
16364        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16365            synchronized (mPackages) {
16366                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16367            }
16368        }
16369
16370        @Override
16371        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16372            synchronized (mPackages) {
16373                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16374                        packageName, userId);
16375            }
16376        }
16377
16378        @Override
16379        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16380            synchronized (mPackages) {
16381                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16382                        packageName, userId);
16383            }
16384        }
16385    }
16386
16387    @Override
16388    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16389        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16390        synchronized (mPackages) {
16391            final long identity = Binder.clearCallingIdentity();
16392            try {
16393                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16394                        packageNames, userId);
16395            } finally {
16396                Binder.restoreCallingIdentity(identity);
16397            }
16398        }
16399    }
16400
16401    private static void enforceSystemOrPhoneCaller(String tag) {
16402        int callingUid = Binder.getCallingUid();
16403        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16404            throw new SecurityException(
16405                    "Cannot call " + tag + " from UID " + callingUid);
16406        }
16407    }
16408}
16409