PackageManagerService.java revision 12058d065e5940c4a38c22327c6e956f6b5492a3
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
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.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
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.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.pm.Settings.VersionInfo;
228import com.android.server.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277runtest -c android.content.pm.PackageManagerTests frameworks-core
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 = false;
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        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
803                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
804                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
805    }
806
807    private IntentFilterVerifier mIntentFilterVerifier;
808
809    // Set of pending broadcasts for aggregating enable/disable of components.
810    static class PendingPackageBroadcasts {
811        // for each user id, a map of <package name -> components within that package>
812        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
813
814        public PendingPackageBroadcasts() {
815            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
816        }
817
818        public ArrayList<String> get(int userId, String packageName) {
819            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
820            return packages.get(packageName);
821        }
822
823        public void put(int userId, String packageName, ArrayList<String> components) {
824            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
825            packages.put(packageName, components);
826        }
827
828        public void remove(int userId, String packageName) {
829            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
830            if (packages != null) {
831                packages.remove(packageName);
832            }
833        }
834
835        public void remove(int userId) {
836            mUidMap.remove(userId);
837        }
838
839        public int userIdCount() {
840            return mUidMap.size();
841        }
842
843        public int userIdAt(int n) {
844            return mUidMap.keyAt(n);
845        }
846
847        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
848            return mUidMap.get(userId);
849        }
850
851        public int size() {
852            // total number of pending broadcast entries across all userIds
853            int num = 0;
854            for (int i = 0; i< mUidMap.size(); i++) {
855                num += mUidMap.valueAt(i).size();
856            }
857            return num;
858        }
859
860        public void clear() {
861            mUidMap.clear();
862        }
863
864        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
865            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
866            if (map == null) {
867                map = new ArrayMap<String, ArrayList<String>>();
868                mUidMap.put(userId, map);
869            }
870            return map;
871        }
872    }
873    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
874
875    // Service Connection to remote media container service to copy
876    // package uri's from external media onto secure containers
877    // or internal storage.
878    private IMediaContainerService mContainerService = null;
879
880    static final int SEND_PENDING_BROADCAST = 1;
881    static final int MCS_BOUND = 3;
882    static final int END_COPY = 4;
883    static final int INIT_COPY = 5;
884    static final int MCS_UNBIND = 6;
885    static final int START_CLEANING_PACKAGE = 7;
886    static final int FIND_INSTALL_LOC = 8;
887    static final int POST_INSTALL = 9;
888    static final int MCS_RECONNECT = 10;
889    static final int MCS_GIVE_UP = 11;
890    static final int UPDATED_MEDIA_STATUS = 12;
891    static final int WRITE_SETTINGS = 13;
892    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
893    static final int PACKAGE_VERIFIED = 15;
894    static final int CHECK_PENDING_VERIFICATION = 16;
895    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
896    static final int INTENT_FILTER_VERIFIED = 18;
897
898    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
899
900    // Delay time in millisecs
901    static final int BROADCAST_DELAY = 10 * 1000;
902
903    static UserManagerService sUserManager;
904
905    // Stores a list of users whose package restrictions file needs to be updated
906    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
907
908    final private DefaultContainerConnection mDefContainerConn =
909            new DefaultContainerConnection();
910    class DefaultContainerConnection implements ServiceConnection {
911        public void onServiceConnected(ComponentName name, IBinder service) {
912            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
913            IMediaContainerService imcs =
914                IMediaContainerService.Stub.asInterface(service);
915            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
916        }
917
918        public void onServiceDisconnected(ComponentName name) {
919            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
920        }
921    }
922
923    // Recordkeeping of restore-after-install operations that are currently in flight
924    // between the Package Manager and the Backup Manager
925    class PostInstallData {
926        public InstallArgs args;
927        public PackageInstalledInfo res;
928
929        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
930            args = _a;
931            res = _r;
932        }
933    }
934
935    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
936    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
937
938    // XML tags for backup/restore of various bits of state
939    private static final String TAG_PREFERRED_BACKUP = "pa";
940    private static final String TAG_DEFAULT_APPS = "da";
941    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
942
943    final String mRequiredVerifierPackage;
944    final String mRequiredInstallerPackage;
945
946    private final PackageUsage mPackageUsage = new PackageUsage();
947
948    private class PackageUsage {
949        private static final int WRITE_INTERVAL
950            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
951
952        private final Object mFileLock = new Object();
953        private final AtomicLong mLastWritten = new AtomicLong(0);
954        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
955
956        private boolean mIsHistoricalPackageUsageAvailable = true;
957
958        boolean isHistoricalPackageUsageAvailable() {
959            return mIsHistoricalPackageUsageAvailable;
960        }
961
962        void write(boolean force) {
963            if (force) {
964                writeInternal();
965                return;
966            }
967            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
968                && !DEBUG_DEXOPT) {
969                return;
970            }
971            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
972                new Thread("PackageUsage_DiskWriter") {
973                    @Override
974                    public void run() {
975                        try {
976                            writeInternal();
977                        } finally {
978                            mBackgroundWriteRunning.set(false);
979                        }
980                    }
981                }.start();
982            }
983        }
984
985        private void writeInternal() {
986            synchronized (mPackages) {
987                synchronized (mFileLock) {
988                    AtomicFile file = getFile();
989                    FileOutputStream f = null;
990                    try {
991                        f = file.startWrite();
992                        BufferedOutputStream out = new BufferedOutputStream(f);
993                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
994                        StringBuilder sb = new StringBuilder();
995                        for (PackageParser.Package pkg : mPackages.values()) {
996                            if (pkg.mLastPackageUsageTimeInMills == 0) {
997                                continue;
998                            }
999                            sb.setLength(0);
1000                            sb.append(pkg.packageName);
1001                            sb.append(' ');
1002                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1003                            sb.append('\n');
1004                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1005                        }
1006                        out.flush();
1007                        file.finishWrite(f);
1008                    } catch (IOException e) {
1009                        if (f != null) {
1010                            file.failWrite(f);
1011                        }
1012                        Log.e(TAG, "Failed to write package usage times", e);
1013                    }
1014                }
1015            }
1016            mLastWritten.set(SystemClock.elapsedRealtime());
1017        }
1018
1019        void readLP() {
1020            synchronized (mFileLock) {
1021                AtomicFile file = getFile();
1022                BufferedInputStream in = null;
1023                try {
1024                    in = new BufferedInputStream(file.openRead());
1025                    StringBuffer sb = new StringBuffer();
1026                    while (true) {
1027                        String packageName = readToken(in, sb, ' ');
1028                        if (packageName == null) {
1029                            break;
1030                        }
1031                        String timeInMillisString = readToken(in, sb, '\n');
1032                        if (timeInMillisString == null) {
1033                            throw new IOException("Failed to find last usage time for package "
1034                                                  + packageName);
1035                        }
1036                        PackageParser.Package pkg = mPackages.get(packageName);
1037                        if (pkg == null) {
1038                            continue;
1039                        }
1040                        long timeInMillis;
1041                        try {
1042                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1043                        } catch (NumberFormatException e) {
1044                            throw new IOException("Failed to parse " + timeInMillisString
1045                                                  + " as a long.", e);
1046                        }
1047                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1048                    }
1049                } catch (FileNotFoundException expected) {
1050                    mIsHistoricalPackageUsageAvailable = false;
1051                } catch (IOException e) {
1052                    Log.w(TAG, "Failed to read package usage times", e);
1053                } finally {
1054                    IoUtils.closeQuietly(in);
1055                }
1056            }
1057            mLastWritten.set(SystemClock.elapsedRealtime());
1058        }
1059
1060        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1061                throws IOException {
1062            sb.setLength(0);
1063            while (true) {
1064                int ch = in.read();
1065                if (ch == -1) {
1066                    if (sb.length() == 0) {
1067                        return null;
1068                    }
1069                    throw new IOException("Unexpected EOF");
1070                }
1071                if (ch == endOfToken) {
1072                    return sb.toString();
1073                }
1074                sb.append((char)ch);
1075            }
1076        }
1077
1078        private AtomicFile getFile() {
1079            File dataDir = Environment.getDataDirectory();
1080            File systemDir = new File(dataDir, "system");
1081            File fname = new File(systemDir, "package-usage.list");
1082            return new AtomicFile(fname);
1083        }
1084    }
1085
1086    class PackageHandler extends Handler {
1087        private boolean mBound = false;
1088        final ArrayList<HandlerParams> mPendingInstalls =
1089            new ArrayList<HandlerParams>();
1090
1091        private boolean connectToService() {
1092            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1093                    " DefaultContainerService");
1094            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1095            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1096            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1097                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1098                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1099                mBound = true;
1100                return true;
1101            }
1102            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1103            return false;
1104        }
1105
1106        private void disconnectService() {
1107            mContainerService = null;
1108            mBound = false;
1109            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110            mContext.unbindService(mDefContainerConn);
1111            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112        }
1113
1114        PackageHandler(Looper looper) {
1115            super(looper);
1116        }
1117
1118        public void handleMessage(Message msg) {
1119            try {
1120                doHandleMessage(msg);
1121            } finally {
1122                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1123            }
1124        }
1125
1126        void doHandleMessage(Message msg) {
1127            switch (msg.what) {
1128                case INIT_COPY: {
1129                    HandlerParams params = (HandlerParams) msg.obj;
1130                    int idx = mPendingInstalls.size();
1131                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1132                    // If a bind was already initiated we dont really
1133                    // need to do anything. The pending install
1134                    // will be processed later on.
1135                    if (!mBound) {
1136                        // If this is the only one pending we might
1137                        // have to bind to the service again.
1138                        if (!connectToService()) {
1139                            Slog.e(TAG, "Failed to bind to media container service");
1140                            params.serviceError();
1141                            return;
1142                        } else {
1143                            // Once we bind to the service, the first
1144                            // pending request will be processed.
1145                            mPendingInstalls.add(idx, params);
1146                        }
1147                    } else {
1148                        mPendingInstalls.add(idx, params);
1149                        // Already bound to the service. Just make
1150                        // sure we trigger off processing the first request.
1151                        if (idx == 0) {
1152                            mHandler.sendEmptyMessage(MCS_BOUND);
1153                        }
1154                    }
1155                    break;
1156                }
1157                case MCS_BOUND: {
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1159                    if (msg.obj != null) {
1160                        mContainerService = (IMediaContainerService) msg.obj;
1161                    }
1162                    if (mContainerService == null) {
1163                        if (!mBound) {
1164                            // Something seriously wrong since we are not bound and we are not
1165                            // waiting for connection. Bail out.
1166                            Slog.e(TAG, "Cannot bind to media container service");
1167                            for (HandlerParams params : mPendingInstalls) {
1168                                // Indicate service bind error
1169                                params.serviceError();
1170                            }
1171                            mPendingInstalls.clear();
1172                        } else {
1173                            Slog.w(TAG, "Waiting to connect to media container service");
1174                        }
1175                    } else if (mPendingInstalls.size() > 0) {
1176                        HandlerParams params = mPendingInstalls.get(0);
1177                        if (params != null) {
1178                            if (params.startCopy()) {
1179                                // We are done...  look for more work or to
1180                                // go idle.
1181                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1182                                        "Checking for more work or unbind...");
1183                                // Delete pending install
1184                                if (mPendingInstalls.size() > 0) {
1185                                    mPendingInstalls.remove(0);
1186                                }
1187                                if (mPendingInstalls.size() == 0) {
1188                                    if (mBound) {
1189                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1190                                                "Posting delayed MCS_UNBIND");
1191                                        removeMessages(MCS_UNBIND);
1192                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1193                                        // Unbind after a little delay, to avoid
1194                                        // continual thrashing.
1195                                        sendMessageDelayed(ubmsg, 10000);
1196                                    }
1197                                } else {
1198                                    // There are more pending requests in queue.
1199                                    // Just post MCS_BOUND message to trigger processing
1200                                    // of next pending install.
1201                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1202                                            "Posting MCS_BOUND for next work");
1203                                    mHandler.sendEmptyMessage(MCS_BOUND);
1204                                }
1205                            }
1206                        }
1207                    } else {
1208                        // Should never happen ideally.
1209                        Slog.w(TAG, "Empty queue");
1210                    }
1211                    break;
1212                }
1213                case MCS_RECONNECT: {
1214                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1215                    if (mPendingInstalls.size() > 0) {
1216                        if (mBound) {
1217                            disconnectService();
1218                        }
1219                        if (!connectToService()) {
1220                            Slog.e(TAG, "Failed to bind to media container service");
1221                            for (HandlerParams params : mPendingInstalls) {
1222                                // Indicate service bind error
1223                                params.serviceError();
1224                            }
1225                            mPendingInstalls.clear();
1226                        }
1227                    }
1228                    break;
1229                }
1230                case MCS_UNBIND: {
1231                    // If there is no actual work left, then time to unbind.
1232                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1233
1234                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1235                        if (mBound) {
1236                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1237
1238                            disconnectService();
1239                        }
1240                    } else if (mPendingInstalls.size() > 0) {
1241                        // There are more pending requests in queue.
1242                        // Just post MCS_BOUND message to trigger processing
1243                        // of next pending install.
1244                        mHandler.sendEmptyMessage(MCS_BOUND);
1245                    }
1246
1247                    break;
1248                }
1249                case MCS_GIVE_UP: {
1250                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1251                    mPendingInstalls.remove(0);
1252                    break;
1253                }
1254                case SEND_PENDING_BROADCAST: {
1255                    String packages[];
1256                    ArrayList<String> components[];
1257                    int size = 0;
1258                    int uids[];
1259                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1260                    synchronized (mPackages) {
1261                        if (mPendingBroadcasts == null) {
1262                            return;
1263                        }
1264                        size = mPendingBroadcasts.size();
1265                        if (size <= 0) {
1266                            // Nothing to be done. Just return
1267                            return;
1268                        }
1269                        packages = new String[size];
1270                        components = new ArrayList[size];
1271                        uids = new int[size];
1272                        int i = 0;  // filling out the above arrays
1273
1274                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1275                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1276                            Iterator<Map.Entry<String, ArrayList<String>>> it
1277                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1278                                            .entrySet().iterator();
1279                            while (it.hasNext() && i < size) {
1280                                Map.Entry<String, ArrayList<String>> ent = it.next();
1281                                packages[i] = ent.getKey();
1282                                components[i] = ent.getValue();
1283                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1284                                uids[i] = (ps != null)
1285                                        ? UserHandle.getUid(packageUserId, ps.appId)
1286                                        : -1;
1287                                i++;
1288                            }
1289                        }
1290                        size = i;
1291                        mPendingBroadcasts.clear();
1292                    }
1293                    // Send broadcasts
1294                    for (int i = 0; i < size; i++) {
1295                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1296                    }
1297                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1298                    break;
1299                }
1300                case START_CLEANING_PACKAGE: {
1301                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1302                    final String packageName = (String)msg.obj;
1303                    final int userId = msg.arg1;
1304                    final boolean andCode = msg.arg2 != 0;
1305                    synchronized (mPackages) {
1306                        if (userId == UserHandle.USER_ALL) {
1307                            int[] users = sUserManager.getUserIds();
1308                            for (int user : users) {
1309                                mSettings.addPackageToCleanLPw(
1310                                        new PackageCleanItem(user, packageName, andCode));
1311                            }
1312                        } else {
1313                            mSettings.addPackageToCleanLPw(
1314                                    new PackageCleanItem(userId, packageName, andCode));
1315                        }
1316                    }
1317                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1318                    startCleaningPackages();
1319                } break;
1320                case POST_INSTALL: {
1321                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1322                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1323                    mRunningInstalls.delete(msg.arg1);
1324                    boolean deleteOld = false;
1325
1326                    if (data != null) {
1327                        InstallArgs args = data.args;
1328                        PackageInstalledInfo res = data.res;
1329
1330                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1331                            final String packageName = res.pkg.applicationInfo.packageName;
1332                            res.removedInfo.sendBroadcast(false, true, false);
1333                            Bundle extras = new Bundle(1);
1334                            extras.putInt(Intent.EXTRA_UID, res.uid);
1335
1336                            // Now that we successfully installed the package, grant runtime
1337                            // permissions if requested before broadcasting the install.
1338                            if ((args.installFlags
1339                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1340                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1341                                        args.installGrantPermissions);
1342                            }
1343
1344                            // Determine the set of users who are adding this
1345                            // package for the first time vs. those who are seeing
1346                            // an update.
1347                            int[] firstUsers;
1348                            int[] updateUsers = new int[0];
1349                            if (res.origUsers == null || res.origUsers.length == 0) {
1350                                firstUsers = res.newUsers;
1351                            } else {
1352                                firstUsers = new int[0];
1353                                for (int i=0; i<res.newUsers.length; i++) {
1354                                    int user = res.newUsers[i];
1355                                    boolean isNew = true;
1356                                    for (int j=0; j<res.origUsers.length; j++) {
1357                                        if (res.origUsers[j] == user) {
1358                                            isNew = false;
1359                                            break;
1360                                        }
1361                                    }
1362                                    if (isNew) {
1363                                        int[] newFirst = new int[firstUsers.length+1];
1364                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1365                                                firstUsers.length);
1366                                        newFirst[firstUsers.length] = user;
1367                                        firstUsers = newFirst;
1368                                    } else {
1369                                        int[] newUpdate = new int[updateUsers.length+1];
1370                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1371                                                updateUsers.length);
1372                                        newUpdate[updateUsers.length] = user;
1373                                        updateUsers = newUpdate;
1374                                    }
1375                                }
1376                            }
1377                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1378                                    packageName, extras, null, null, firstUsers);
1379                            final boolean update = res.removedInfo.removedPackage != null;
1380                            if (update) {
1381                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1382                            }
1383                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1384                                    packageName, extras, null, null, updateUsers);
1385                            if (update) {
1386                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1387                                        packageName, extras, null, null, updateUsers);
1388                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1389                                        null, null, packageName, null, updateUsers);
1390
1391                                // treat asec-hosted packages like removable media on upgrade
1392                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1393                                    if (DEBUG_INSTALL) {
1394                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1395                                                + " is ASEC-hosted -> AVAILABLE");
1396                                    }
1397                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1398                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1399                                    pkgList.add(packageName);
1400                                    sendResourcesChangedBroadcast(true, true,
1401                                            pkgList,uidArray, null);
1402                                }
1403                            }
1404                            if (res.removedInfo.args != null) {
1405                                // Remove the replaced package's older resources safely now
1406                                deleteOld = true;
1407                            }
1408
1409                            // If this app is a browser and it's newly-installed for some
1410                            // users, clear any default-browser state in those users
1411                            if (firstUsers.length > 0) {
1412                                // the app's nature doesn't depend on the user, so we can just
1413                                // check its browser nature in any user and generalize.
1414                                if (packageIsBrowser(packageName, firstUsers[0])) {
1415                                    synchronized (mPackages) {
1416                                        for (int userId : firstUsers) {
1417                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1418                                        }
1419                                    }
1420                                }
1421                            }
1422                            // Log current value of "unknown sources" setting
1423                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1424                                getUnknownSourcesSettings());
1425                        }
1426                        // Force a gc to clear up things
1427                        Runtime.getRuntime().gc();
1428                        // We delete after a gc for applications  on sdcard.
1429                        if (deleteOld) {
1430                            synchronized (mInstallLock) {
1431                                res.removedInfo.args.doPostDeleteLI(true);
1432                            }
1433                        }
1434                        if (args.observer != null) {
1435                            try {
1436                                Bundle extras = extrasForInstallResult(res);
1437                                args.observer.onPackageInstalled(res.name, res.returnCode,
1438                                        res.returnMsg, extras);
1439                            } catch (RemoteException e) {
1440                                Slog.i(TAG, "Observer no longer exists.");
1441                            }
1442                        }
1443                    } else {
1444                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1445                    }
1446                } break;
1447                case UPDATED_MEDIA_STATUS: {
1448                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1449                    boolean reportStatus = msg.arg1 == 1;
1450                    boolean doGc = msg.arg2 == 1;
1451                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1452                    if (doGc) {
1453                        // Force a gc to clear up stale containers.
1454                        Runtime.getRuntime().gc();
1455                    }
1456                    if (msg.obj != null) {
1457                        @SuppressWarnings("unchecked")
1458                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1459                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1460                        // Unload containers
1461                        unloadAllContainers(args);
1462                    }
1463                    if (reportStatus) {
1464                        try {
1465                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1466                            PackageHelper.getMountService().finishMediaUpdate();
1467                        } catch (RemoteException e) {
1468                            Log.e(TAG, "MountService not running?");
1469                        }
1470                    }
1471                } break;
1472                case WRITE_SETTINGS: {
1473                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1474                    synchronized (mPackages) {
1475                        removeMessages(WRITE_SETTINGS);
1476                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1477                        mSettings.writeLPr();
1478                        mDirtyUsers.clear();
1479                    }
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1481                } break;
1482                case WRITE_PACKAGE_RESTRICTIONS: {
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1484                    synchronized (mPackages) {
1485                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1486                        for (int userId : mDirtyUsers) {
1487                            mSettings.writePackageRestrictionsLPr(userId);
1488                        }
1489                        mDirtyUsers.clear();
1490                    }
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1492                } break;
1493                case CHECK_PENDING_VERIFICATION: {
1494                    final int verificationId = msg.arg1;
1495                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1496
1497                    if ((state != null) && !state.timeoutExtended()) {
1498                        final InstallArgs args = state.getInstallArgs();
1499                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1500
1501                        Slog.i(TAG, "Verification timed out for " + originUri);
1502                        mPendingVerification.remove(verificationId);
1503
1504                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1505
1506                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1507                            Slog.i(TAG, "Continuing with installation of " + originUri);
1508                            state.setVerifierResponse(Binder.getCallingUid(),
1509                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1510                            broadcastPackageVerified(verificationId, originUri,
1511                                    PackageManager.VERIFICATION_ALLOW,
1512                                    state.getInstallArgs().getUser());
1513                            try {
1514                                ret = args.copyApk(mContainerService, true);
1515                            } catch (RemoteException e) {
1516                                Slog.e(TAG, "Could not contact the ContainerService");
1517                            }
1518                        } else {
1519                            broadcastPackageVerified(verificationId, originUri,
1520                                    PackageManager.VERIFICATION_REJECT,
1521                                    state.getInstallArgs().getUser());
1522                        }
1523
1524                        processPendingInstall(args, ret);
1525                        mHandler.sendEmptyMessage(MCS_UNBIND);
1526                    }
1527                    break;
1528                }
1529                case PACKAGE_VERIFIED: {
1530                    final int verificationId = msg.arg1;
1531
1532                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1533                    if (state == null) {
1534                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1535                        break;
1536                    }
1537
1538                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1539
1540                    state.setVerifierResponse(response.callerUid, response.code);
1541
1542                    if (state.isVerificationComplete()) {
1543                        mPendingVerification.remove(verificationId);
1544
1545                        final InstallArgs args = state.getInstallArgs();
1546                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1547
1548                        int ret;
1549                        if (state.isInstallAllowed()) {
1550                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1551                            broadcastPackageVerified(verificationId, originUri,
1552                                    response.code, state.getInstallArgs().getUser());
1553                            try {
1554                                ret = args.copyApk(mContainerService, true);
1555                            } catch (RemoteException e) {
1556                                Slog.e(TAG, "Could not contact the ContainerService");
1557                            }
1558                        } else {
1559                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1560                        }
1561
1562                        processPendingInstall(args, ret);
1563
1564                        mHandler.sendEmptyMessage(MCS_UNBIND);
1565                    }
1566
1567                    break;
1568                }
1569                case START_INTENT_FILTER_VERIFICATIONS: {
1570                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1571                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1572                            params.replacing, params.pkg);
1573                    break;
1574                }
1575                case INTENT_FILTER_VERIFIED: {
1576                    final int verificationId = msg.arg1;
1577
1578                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1579                            verificationId);
1580                    if (state == null) {
1581                        Slog.w(TAG, "Invalid IntentFilter verification token "
1582                                + verificationId + " received");
1583                        break;
1584                    }
1585
1586                    final int userId = state.getUserId();
1587
1588                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1589                            "Processing IntentFilter verification with token:"
1590                            + verificationId + " and userId:" + userId);
1591
1592                    final IntentFilterVerificationResponse response =
1593                            (IntentFilterVerificationResponse) msg.obj;
1594
1595                    state.setVerifierResponse(response.callerUid, response.code);
1596
1597                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598                            "IntentFilter verification with token:" + verificationId
1599                            + " and userId:" + userId
1600                            + " is settings verifier response with response code:"
1601                            + response.code);
1602
1603                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1604                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1605                                + response.getFailedDomainsString());
1606                    }
1607
1608                    if (state.isVerificationComplete()) {
1609                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1610                    } else {
1611                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                                "IntentFilter verification with token:" + verificationId
1613                                + " was not said to be complete");
1614                    }
1615
1616                    break;
1617                }
1618            }
1619        }
1620    }
1621
1622    private StorageEventListener mStorageListener = new StorageEventListener() {
1623        @Override
1624        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1625            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1626                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1627                    final String volumeUuid = vol.getFsUuid();
1628
1629                    // Clean up any users or apps that were removed or recreated
1630                    // while this volume was missing
1631                    reconcileUsers(volumeUuid);
1632                    reconcileApps(volumeUuid);
1633
1634                    // Clean up any install sessions that expired or were
1635                    // cancelled while this volume was missing
1636                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1637
1638                    loadPrivatePackages(vol);
1639
1640                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1641                    unloadPrivatePackages(vol);
1642                }
1643            }
1644
1645            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1646                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1647                    updateExternalMediaStatus(true, false);
1648                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1649                    updateExternalMediaStatus(false, false);
1650                }
1651            }
1652        }
1653
1654        @Override
1655        public void onVolumeForgotten(String fsUuid) {
1656            if (TextUtils.isEmpty(fsUuid)) {
1657                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1658                return;
1659            }
1660
1661            // Remove any apps installed on the forgotten volume
1662            synchronized (mPackages) {
1663                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1664                for (PackageSetting ps : packages) {
1665                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1666                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1667                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1668                }
1669
1670                mSettings.onVolumeForgotten(fsUuid);
1671                mSettings.writeLPr();
1672            }
1673        }
1674    };
1675
1676    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1677            String[] grantedPermissions) {
1678        if (userId >= UserHandle.USER_OWNER) {
1679            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1680        } else if (userId == UserHandle.USER_ALL) {
1681            final int[] userIds;
1682            synchronized (mPackages) {
1683                userIds = UserManagerService.getInstance().getUserIds();
1684            }
1685            for (int someUserId : userIds) {
1686                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1687            }
1688        }
1689
1690        // We could have touched GID membership, so flush out packages.list
1691        synchronized (mPackages) {
1692            mSettings.writePackageListLPr();
1693        }
1694    }
1695
1696    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1697            String[] grantedPermissions) {
1698        SettingBase sb = (SettingBase) pkg.mExtras;
1699        if (sb == null) {
1700            return;
1701        }
1702
1703        PermissionsState permissionsState = sb.getPermissionsState();
1704
1705        for (String permission : pkg.requestedPermissions) {
1706            BasePermission bp = mSettings.mPermissions.get(permission);
1707            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1708                    || ArrayUtils.contains(grantedPermissions, permission))) {
1709                permissionsState.grantRuntimePermission(bp, userId);
1710            }
1711        }
1712    }
1713
1714    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1715        Bundle extras = null;
1716        switch (res.returnCode) {
1717            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1718                extras = new Bundle();
1719                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1720                        res.origPermission);
1721                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1722                        res.origPackage);
1723                break;
1724            }
1725            case PackageManager.INSTALL_SUCCEEDED: {
1726                extras = new Bundle();
1727                extras.putBoolean(Intent.EXTRA_REPLACING,
1728                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1729                break;
1730            }
1731        }
1732        return extras;
1733    }
1734
1735    void scheduleWriteSettingsLocked() {
1736        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1737            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1738        }
1739    }
1740
1741    void scheduleWritePackageRestrictionsLocked(int userId) {
1742        if (!sUserManager.exists(userId)) return;
1743        mDirtyUsers.add(userId);
1744        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1745            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1746        }
1747    }
1748
1749    public static PackageManagerService main(Context context, Installer installer,
1750            boolean factoryTest, boolean onlyCore) {
1751        PackageManagerService m = new PackageManagerService(context, installer,
1752                factoryTest, onlyCore);
1753        ServiceManager.addService("package", m);
1754        return m;
1755    }
1756
1757    static String[] splitString(String str, char sep) {
1758        int count = 1;
1759        int i = 0;
1760        while ((i=str.indexOf(sep, i)) >= 0) {
1761            count++;
1762            i++;
1763        }
1764
1765        String[] res = new String[count];
1766        i=0;
1767        count = 0;
1768        int lastI=0;
1769        while ((i=str.indexOf(sep, i)) >= 0) {
1770            res[count] = str.substring(lastI, i);
1771            count++;
1772            i++;
1773            lastI = i;
1774        }
1775        res[count] = str.substring(lastI, str.length());
1776        return res;
1777    }
1778
1779    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1780        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1781                Context.DISPLAY_SERVICE);
1782        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1783    }
1784
1785    public PackageManagerService(Context context, Installer installer,
1786            boolean factoryTest, boolean onlyCore) {
1787        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1788                SystemClock.uptimeMillis());
1789
1790        if (mSdkVersion <= 0) {
1791            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1792        }
1793
1794        mContext = context;
1795        mFactoryTest = factoryTest;
1796        mOnlyCore = onlyCore;
1797        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1798        mMetrics = new DisplayMetrics();
1799        mSettings = new Settings(mPackages);
1800        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1801                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1802        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1803                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1804        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1805                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1806        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1807                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1808        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1809                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1810        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1811                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1812
1813        // TODO: add a property to control this?
1814        long dexOptLRUThresholdInMinutes;
1815        if (mLazyDexOpt) {
1816            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1817        } else {
1818            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1819        }
1820        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1821
1822        String separateProcesses = SystemProperties.get("debug.separate_processes");
1823        if (separateProcesses != null && separateProcesses.length() > 0) {
1824            if ("*".equals(separateProcesses)) {
1825                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1826                mSeparateProcesses = null;
1827                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1828            } else {
1829                mDefParseFlags = 0;
1830                mSeparateProcesses = separateProcesses.split(",");
1831                Slog.w(TAG, "Running with debug.separate_processes: "
1832                        + separateProcesses);
1833            }
1834        } else {
1835            mDefParseFlags = 0;
1836            mSeparateProcesses = null;
1837        }
1838
1839        mInstaller = installer;
1840        mPackageDexOptimizer = new PackageDexOptimizer(this);
1841        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1842
1843        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1844                FgThread.get().getLooper());
1845
1846        getDefaultDisplayMetrics(context, mMetrics);
1847
1848        SystemConfig systemConfig = SystemConfig.getInstance();
1849        mGlobalGids = systemConfig.getGlobalGids();
1850        mSystemPermissions = systemConfig.getSystemPermissions();
1851        mAvailableFeatures = systemConfig.getAvailableFeatures();
1852
1853        synchronized (mInstallLock) {
1854        // writer
1855        synchronized (mPackages) {
1856            mHandlerThread = new ServiceThread(TAG,
1857                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1858            mHandlerThread.start();
1859            mHandler = new PackageHandler(mHandlerThread.getLooper());
1860            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1861
1862            File dataDir = Environment.getDataDirectory();
1863            mAppDataDir = new File(dataDir, "data");
1864            mAppInstallDir = new File(dataDir, "app");
1865            mAppLib32InstallDir = new File(dataDir, "app-lib");
1866            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1867            mUserAppDataDir = new File(dataDir, "user");
1868            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1869
1870            sUserManager = new UserManagerService(context, this,
1871                    mInstallLock, mPackages);
1872
1873            // Propagate permission configuration in to package manager.
1874            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1875                    = systemConfig.getPermissions();
1876            for (int i=0; i<permConfig.size(); i++) {
1877                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1878                BasePermission bp = mSettings.mPermissions.get(perm.name);
1879                if (bp == null) {
1880                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1881                    mSettings.mPermissions.put(perm.name, bp);
1882                }
1883                if (perm.gids != null) {
1884                    bp.setGids(perm.gids, perm.perUser);
1885                }
1886            }
1887
1888            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1889            for (int i=0; i<libConfig.size(); i++) {
1890                mSharedLibraries.put(libConfig.keyAt(i),
1891                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1892            }
1893
1894            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1895
1896            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1897                    mSdkVersion, mOnlyCore);
1898
1899            String customResolverActivity = Resources.getSystem().getString(
1900                    R.string.config_customResolverActivity);
1901            if (TextUtils.isEmpty(customResolverActivity)) {
1902                customResolverActivity = null;
1903            } else {
1904                mCustomResolverComponentName = ComponentName.unflattenFromString(
1905                        customResolverActivity);
1906            }
1907
1908            long startTime = SystemClock.uptimeMillis();
1909
1910            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1911                    startTime);
1912
1913            // Set flag to monitor and not change apk file paths when
1914            // scanning install directories.
1915            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1916
1917            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1918
1919            /**
1920             * Add everything in the in the boot class path to the
1921             * list of process files because dexopt will have been run
1922             * if necessary during zygote startup.
1923             */
1924            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1925            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1926
1927            if (bootClassPath != null) {
1928                String[] bootClassPathElements = splitString(bootClassPath, ':');
1929                for (String element : bootClassPathElements) {
1930                    alreadyDexOpted.add(element);
1931                }
1932            } else {
1933                Slog.w(TAG, "No BOOTCLASSPATH found!");
1934            }
1935
1936            if (systemServerClassPath != null) {
1937                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1938                for (String element : systemServerClassPathElements) {
1939                    alreadyDexOpted.add(element);
1940                }
1941            } else {
1942                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1943            }
1944
1945            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1946            final String[] dexCodeInstructionSets =
1947                    getDexCodeInstructionSets(
1948                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1949
1950            /**
1951             * Ensure all external libraries have had dexopt run on them.
1952             */
1953            if (mSharedLibraries.size() > 0) {
1954                // NOTE: For now, we're compiling these system "shared libraries"
1955                // (and framework jars) into all available architectures. It's possible
1956                // to compile them only when we come across an app that uses them (there's
1957                // already logic for that in scanPackageLI) but that adds some complexity.
1958                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1959                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1960                        final String lib = libEntry.path;
1961                        if (lib == null) {
1962                            continue;
1963                        }
1964
1965                        try {
1966                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1967                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1968                                alreadyDexOpted.add(lib);
1969                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1970                            }
1971                        } catch (FileNotFoundException e) {
1972                            Slog.w(TAG, "Library not found: " + lib);
1973                        } catch (IOException e) {
1974                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1975                                    + e.getMessage());
1976                        }
1977                    }
1978                }
1979            }
1980
1981            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1982
1983            // Gross hack for now: we know this file doesn't contain any
1984            // code, so don't dexopt it to avoid the resulting log spew.
1985            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1986
1987            // Gross hack for now: we know this file is only part of
1988            // the boot class path for art, so don't dexopt it to
1989            // avoid the resulting log spew.
1990            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1991
1992            /**
1993             * There are a number of commands implemented in Java, which
1994             * we currently need to do the dexopt on so that they can be
1995             * run from a non-root shell.
1996             */
1997            String[] frameworkFiles = frameworkDir.list();
1998            if (frameworkFiles != null) {
1999                // TODO: We could compile these only for the most preferred ABI. We should
2000                // first double check that the dex files for these commands are not referenced
2001                // by other system apps.
2002                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2003                    for (int i=0; i<frameworkFiles.length; i++) {
2004                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2005                        String path = libPath.getPath();
2006                        // Skip the file if we already did it.
2007                        if (alreadyDexOpted.contains(path)) {
2008                            continue;
2009                        }
2010                        // Skip the file if it is not a type we want to dexopt.
2011                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2012                            continue;
2013                        }
2014                        try {
2015                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2016                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2017                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2018                            }
2019                        } catch (FileNotFoundException e) {
2020                            Slog.w(TAG, "Jar not found: " + path);
2021                        } catch (IOException e) {
2022                            Slog.w(TAG, "Exception reading jar: " + path, e);
2023                        }
2024                    }
2025                }
2026            }
2027
2028            // Collect vendor overlay packages.
2029            // (Do this before scanning any apps.)
2030            // For security and version matching reason, only consider
2031            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2032            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2033            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2034                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2035
2036            // Find base frameworks (resource packages without code).
2037            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2038                    | PackageParser.PARSE_IS_SYSTEM_DIR
2039                    | PackageParser.PARSE_IS_PRIVILEGED,
2040                    scanFlags | SCAN_NO_DEX, 0);
2041
2042            // Collected privileged system packages.
2043            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2044            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2045                    | PackageParser.PARSE_IS_SYSTEM_DIR
2046                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2047
2048            // Collect ordinary system packages.
2049            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2050            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2051                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2052
2053            // Collect all vendor packages.
2054            File vendorAppDir = new File("/vendor/app");
2055            try {
2056                vendorAppDir = vendorAppDir.getCanonicalFile();
2057            } catch (IOException e) {
2058                // failed to look up canonical path, continue with original one
2059            }
2060            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2061                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2062
2063            // Collect all OEM packages.
2064            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2065            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2066                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2067
2068            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2069            mInstaller.moveFiles();
2070
2071            // Prune any system packages that no longer exist.
2072            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2073            if (!mOnlyCore) {
2074                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2075                while (psit.hasNext()) {
2076                    PackageSetting ps = psit.next();
2077
2078                    /*
2079                     * If this is not a system app, it can't be a
2080                     * disable system app.
2081                     */
2082                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2083                        continue;
2084                    }
2085
2086                    /*
2087                     * If the package is scanned, it's not erased.
2088                     */
2089                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2090                    if (scannedPkg != null) {
2091                        /*
2092                         * If the system app is both scanned and in the
2093                         * disabled packages list, then it must have been
2094                         * added via OTA. Remove it from the currently
2095                         * scanned package so the previously user-installed
2096                         * application can be scanned.
2097                         */
2098                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2099                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2100                                    + ps.name + "; removing system app.  Last known codePath="
2101                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2102                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2103                                    + scannedPkg.mVersionCode);
2104                            removePackageLI(ps, true);
2105                            mExpectingBetter.put(ps.name, ps.codePath);
2106                        }
2107
2108                        continue;
2109                    }
2110
2111                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2112                        psit.remove();
2113                        logCriticalInfo(Log.WARN, "System package " + ps.name
2114                                + " no longer exists; wiping its data");
2115                        removeDataDirsLI(null, ps.name);
2116                    } else {
2117                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2118                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2119                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2120                        }
2121                    }
2122                }
2123            }
2124
2125            //look for any incomplete package installations
2126            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2127            //clean up list
2128            for(int i = 0; i < deletePkgsList.size(); i++) {
2129                //clean up here
2130                cleanupInstallFailedPackage(deletePkgsList.get(i));
2131            }
2132            //delete tmp files
2133            deleteTempPackageFiles();
2134
2135            // Remove any shared userIDs that have no associated packages
2136            mSettings.pruneSharedUsersLPw();
2137
2138            if (!mOnlyCore) {
2139                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2140                        SystemClock.uptimeMillis());
2141                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2142
2143                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2144                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2145
2146                /**
2147                 * Remove disable package settings for any updated system
2148                 * apps that were removed via an OTA. If they're not a
2149                 * previously-updated app, remove them completely.
2150                 * Otherwise, just revoke their system-level permissions.
2151                 */
2152                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2153                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2154                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2155
2156                    String msg;
2157                    if (deletedPkg == null) {
2158                        msg = "Updated system package " + deletedAppName
2159                                + " no longer exists; wiping its data";
2160                        removeDataDirsLI(null, deletedAppName);
2161                    } else {
2162                        msg = "Updated system app + " + deletedAppName
2163                                + " no longer present; removing system privileges for "
2164                                + deletedAppName;
2165
2166                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2167
2168                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2169                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2170                    }
2171                    logCriticalInfo(Log.WARN, msg);
2172                }
2173
2174                /**
2175                 * Make sure all system apps that we expected to appear on
2176                 * the userdata partition actually showed up. If they never
2177                 * appeared, crawl back and revive the system version.
2178                 */
2179                for (int i = 0; i < mExpectingBetter.size(); i++) {
2180                    final String packageName = mExpectingBetter.keyAt(i);
2181                    if (!mPackages.containsKey(packageName)) {
2182                        final File scanFile = mExpectingBetter.valueAt(i);
2183
2184                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2185                                + " but never showed up; reverting to system");
2186
2187                        final int reparseFlags;
2188                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2189                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2190                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2191                                    | PackageParser.PARSE_IS_PRIVILEGED;
2192                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2193                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2194                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2195                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2196                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2197                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2198                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2199                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2200                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2201                        } else {
2202                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2203                            continue;
2204                        }
2205
2206                        mSettings.enableSystemPackageLPw(packageName);
2207
2208                        try {
2209                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2210                        } catch (PackageManagerException e) {
2211                            Slog.e(TAG, "Failed to parse original system package: "
2212                                    + e.getMessage());
2213                        }
2214                    }
2215                }
2216            }
2217            mExpectingBetter.clear();
2218
2219            // Now that we know all of the shared libraries, update all clients to have
2220            // the correct library paths.
2221            updateAllSharedLibrariesLPw();
2222
2223            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2224                // NOTE: We ignore potential failures here during a system scan (like
2225                // the rest of the commands above) because there's precious little we
2226                // can do about it. A settings error is reported, though.
2227                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2228                        false /* force dexopt */, false /* defer dexopt */);
2229            }
2230
2231            // Now that we know all the packages we are keeping,
2232            // read and update their last usage times.
2233            mPackageUsage.readLP();
2234
2235            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2236                    SystemClock.uptimeMillis());
2237            Slog.i(TAG, "Time to scan packages: "
2238                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2239                    + " seconds");
2240
2241            // If the platform SDK has changed since the last time we booted,
2242            // we need to re-grant app permission to catch any new ones that
2243            // appear.  This is really a hack, and means that apps can in some
2244            // cases get permissions that the user didn't initially explicitly
2245            // allow...  it would be nice to have some better way to handle
2246            // this situation.
2247            final VersionInfo ver = mSettings.getInternalVersion();
2248
2249            int updateFlags = UPDATE_PERMISSIONS_ALL;
2250            if (ver.sdkVersion != mSdkVersion) {
2251                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2252                        + mSdkVersion + "; regranting permissions for internal storage");
2253                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2254            }
2255            updatePermissionsLPw(null, null, updateFlags);
2256            ver.sdkVersion = mSdkVersion;
2257
2258            // If this is the first boot, and it is a normal boot, then
2259            // we need to initialize the default preferred apps.
2260            if (!mRestoredSettings && !onlyCore) {
2261                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2262                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2263                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2264            }
2265
2266            // If this is first boot after an OTA, and a normal boot, then
2267            // we need to clear code cache directories.
2268            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2269            if (mIsUpgrade && !onlyCore) {
2270                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2271                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2272                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2273                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2274                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2275                    }
2276                }
2277                ver.fingerprint = Build.FINGERPRINT;
2278            }
2279
2280            checkDefaultBrowser();
2281
2282            // All the changes are done during package scanning.
2283            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2284
2285            // can downgrade to reader
2286            mSettings.writeLPr();
2287
2288            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2289                    SystemClock.uptimeMillis());
2290
2291            mRequiredVerifierPackage = getRequiredVerifierLPr();
2292            mRequiredInstallerPackage = getRequiredInstallerLPr();
2293
2294            mInstallerService = new PackageInstallerService(context, this);
2295
2296            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2297            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2298                    mIntentFilterVerifierComponent);
2299
2300        } // synchronized (mPackages)
2301        } // synchronized (mInstallLock)
2302
2303        // Now after opening every single application zip, make sure they
2304        // are all flushed.  Not really needed, but keeps things nice and
2305        // tidy.
2306        Runtime.getRuntime().gc();
2307
2308        // Expose private service for system components to use.
2309        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2310    }
2311
2312    @Override
2313    public boolean isFirstBoot() {
2314        return !mRestoredSettings;
2315    }
2316
2317    @Override
2318    public boolean isOnlyCoreApps() {
2319        return mOnlyCore;
2320    }
2321
2322    @Override
2323    public boolean isUpgrade() {
2324        return mIsUpgrade;
2325    }
2326
2327    private String getRequiredVerifierLPr() {
2328        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2329        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2330                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2331
2332        String requiredVerifier = null;
2333
2334        final int N = receivers.size();
2335        for (int i = 0; i < N; i++) {
2336            final ResolveInfo info = receivers.get(i);
2337
2338            if (info.activityInfo == null) {
2339                continue;
2340            }
2341
2342            final String packageName = info.activityInfo.packageName;
2343
2344            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2345                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2346                continue;
2347            }
2348
2349            if (requiredVerifier != null) {
2350                throw new RuntimeException("There can be only one required verifier");
2351            }
2352
2353            requiredVerifier = packageName;
2354        }
2355
2356        return requiredVerifier;
2357    }
2358
2359    private String getRequiredInstallerLPr() {
2360        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2361        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2362        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2363
2364        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2365                PACKAGE_MIME_TYPE, 0, 0);
2366
2367        String requiredInstaller = null;
2368
2369        final int N = installers.size();
2370        for (int i = 0; i < N; i++) {
2371            final ResolveInfo info = installers.get(i);
2372            final String packageName = info.activityInfo.packageName;
2373
2374            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2375                continue;
2376            }
2377
2378            if (requiredInstaller != null) {
2379                throw new RuntimeException("There must be one required installer");
2380            }
2381
2382            requiredInstaller = packageName;
2383        }
2384
2385        if (requiredInstaller == null) {
2386            throw new RuntimeException("There must be one required installer");
2387        }
2388
2389        return requiredInstaller;
2390    }
2391
2392    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2393        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2394        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2395                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2396
2397        ComponentName verifierComponentName = null;
2398
2399        int priority = -1000;
2400        final int N = receivers.size();
2401        for (int i = 0; i < N; i++) {
2402            final ResolveInfo info = receivers.get(i);
2403
2404            if (info.activityInfo == null) {
2405                continue;
2406            }
2407
2408            final String packageName = info.activityInfo.packageName;
2409
2410            final PackageSetting ps = mSettings.mPackages.get(packageName);
2411            if (ps == null) {
2412                continue;
2413            }
2414
2415            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2416                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2417                continue;
2418            }
2419
2420            // Select the IntentFilterVerifier with the highest priority
2421            if (priority < info.priority) {
2422                priority = info.priority;
2423                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2424                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2425                        + verifierComponentName + " with priority: " + info.priority);
2426            }
2427        }
2428
2429        return verifierComponentName;
2430    }
2431
2432    private void primeDomainVerificationsLPw(int userId) {
2433        if (DEBUG_DOMAIN_VERIFICATION) {
2434            Slog.d(TAG, "Priming domain verifications in user " + userId);
2435        }
2436
2437        SystemConfig systemConfig = SystemConfig.getInstance();
2438        ArraySet<String> packages = systemConfig.getLinkedApps();
2439        ArraySet<String> domains = new ArraySet<String>();
2440
2441        for (String packageName : packages) {
2442            PackageParser.Package pkg = mPackages.get(packageName);
2443            if (pkg != null) {
2444                if (!pkg.isSystemApp()) {
2445                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2446                    continue;
2447                }
2448
2449                domains.clear();
2450                for (PackageParser.Activity a : pkg.activities) {
2451                    for (ActivityIntentInfo filter : a.intents) {
2452                        if (hasValidDomains(filter)) {
2453                            domains.addAll(filter.getHostsList());
2454                        }
2455                    }
2456                }
2457
2458                if (domains.size() > 0) {
2459                    if (DEBUG_DOMAIN_VERIFICATION) {
2460                        Slog.v(TAG, "      + " + packageName);
2461                    }
2462                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2463                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2464                    // and then 'always' in the per-user state actually used for intent resolution.
2465                    final IntentFilterVerificationInfo ivi;
2466                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2467                            new ArrayList<String>(domains));
2468                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2469                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2470                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2471                } else {
2472                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2473                            + "' does not handle web links");
2474                }
2475            } else {
2476                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2477            }
2478        }
2479
2480        scheduleWritePackageRestrictionsLocked(userId);
2481        scheduleWriteSettingsLocked();
2482    }
2483
2484    private void applyFactoryDefaultBrowserLPw(int userId) {
2485        // The default browser app's package name is stored in a string resource,
2486        // with a product-specific overlay used for vendor customization.
2487        String browserPkg = mContext.getResources().getString(
2488                com.android.internal.R.string.default_browser);
2489        if (!TextUtils.isEmpty(browserPkg)) {
2490            // non-empty string => required to be a known package
2491            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2492            if (ps == null) {
2493                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2494                browserPkg = null;
2495            } else {
2496                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2497            }
2498        }
2499
2500        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2501        // default.  If there's more than one, just leave everything alone.
2502        if (browserPkg == null) {
2503            calculateDefaultBrowserLPw(userId);
2504        }
2505    }
2506
2507    private void calculateDefaultBrowserLPw(int userId) {
2508        List<String> allBrowsers = resolveAllBrowserApps(userId);
2509        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2510        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2511    }
2512
2513    private List<String> resolveAllBrowserApps(int userId) {
2514        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2515        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2516                PackageManager.MATCH_ALL, userId);
2517
2518        final int count = list.size();
2519        List<String> result = new ArrayList<String>(count);
2520        for (int i=0; i<count; i++) {
2521            ResolveInfo info = list.get(i);
2522            if (info.activityInfo == null
2523                    || !info.handleAllWebDataURI
2524                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2525                    || result.contains(info.activityInfo.packageName)) {
2526                continue;
2527            }
2528            result.add(info.activityInfo.packageName);
2529        }
2530
2531        return result;
2532    }
2533
2534    private boolean packageIsBrowser(String packageName, int userId) {
2535        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2536                PackageManager.MATCH_ALL, userId);
2537        final int N = list.size();
2538        for (int i = 0; i < N; i++) {
2539            ResolveInfo info = list.get(i);
2540            if (packageName.equals(info.activityInfo.packageName)) {
2541                return true;
2542            }
2543        }
2544        return false;
2545    }
2546
2547    private void checkDefaultBrowser() {
2548        final int myUserId = UserHandle.myUserId();
2549        final String packageName = getDefaultBrowserPackageName(myUserId);
2550        if (packageName != null) {
2551            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2552            if (info == null) {
2553                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2554                synchronized (mPackages) {
2555                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2556                }
2557            }
2558        }
2559    }
2560
2561    @Override
2562    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2563            throws RemoteException {
2564        try {
2565            return super.onTransact(code, data, reply, flags);
2566        } catch (RuntimeException e) {
2567            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2568                Slog.wtf(TAG, "Package Manager Crash", e);
2569            }
2570            throw e;
2571        }
2572    }
2573
2574    void cleanupInstallFailedPackage(PackageSetting ps) {
2575        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2576
2577        removeDataDirsLI(ps.volumeUuid, ps.name);
2578        if (ps.codePath != null) {
2579            if (ps.codePath.isDirectory()) {
2580                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2581            } else {
2582                ps.codePath.delete();
2583            }
2584        }
2585        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2586            if (ps.resourcePath.isDirectory()) {
2587                FileUtils.deleteContents(ps.resourcePath);
2588            }
2589            ps.resourcePath.delete();
2590        }
2591        mSettings.removePackageLPw(ps.name);
2592    }
2593
2594    static int[] appendInts(int[] cur, int[] add) {
2595        if (add == null) return cur;
2596        if (cur == null) return add;
2597        final int N = add.length;
2598        for (int i=0; i<N; i++) {
2599            cur = appendInt(cur, add[i]);
2600        }
2601        return cur;
2602    }
2603
2604    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2605        if (!sUserManager.exists(userId)) return null;
2606        final PackageSetting ps = (PackageSetting) p.mExtras;
2607        if (ps == null) {
2608            return null;
2609        }
2610
2611        final PermissionsState permissionsState = ps.getPermissionsState();
2612
2613        final int[] gids = permissionsState.computeGids(userId);
2614        final Set<String> permissions = permissionsState.getPermissions(userId);
2615        final PackageUserState state = ps.readUserState(userId);
2616
2617        return PackageParser.generatePackageInfo(p, gids, flags,
2618                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2619    }
2620
2621    @Override
2622    public boolean isPackageFrozen(String packageName) {
2623        synchronized (mPackages) {
2624            final PackageSetting ps = mSettings.mPackages.get(packageName);
2625            if (ps != null) {
2626                return ps.frozen;
2627            }
2628        }
2629        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2630        return true;
2631    }
2632
2633    @Override
2634    public boolean isPackageAvailable(String packageName, int userId) {
2635        if (!sUserManager.exists(userId)) return false;
2636        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2637        synchronized (mPackages) {
2638            PackageParser.Package p = mPackages.get(packageName);
2639            if (p != null) {
2640                final PackageSetting ps = (PackageSetting) p.mExtras;
2641                if (ps != null) {
2642                    final PackageUserState state = ps.readUserState(userId);
2643                    if (state != null) {
2644                        return PackageParser.isAvailable(state);
2645                    }
2646                }
2647            }
2648        }
2649        return false;
2650    }
2651
2652    @Override
2653    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2654        if (!sUserManager.exists(userId)) return null;
2655        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2656        // reader
2657        synchronized (mPackages) {
2658            PackageParser.Package p = mPackages.get(packageName);
2659            if (DEBUG_PACKAGE_INFO)
2660                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2661            if (p != null) {
2662                return generatePackageInfo(p, flags, userId);
2663            }
2664            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2665                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2666            }
2667        }
2668        return null;
2669    }
2670
2671    @Override
2672    public String[] currentToCanonicalPackageNames(String[] names) {
2673        String[] out = new String[names.length];
2674        // reader
2675        synchronized (mPackages) {
2676            for (int i=names.length-1; i>=0; i--) {
2677                PackageSetting ps = mSettings.mPackages.get(names[i]);
2678                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2679            }
2680        }
2681        return out;
2682    }
2683
2684    @Override
2685    public String[] canonicalToCurrentPackageNames(String[] names) {
2686        String[] out = new String[names.length];
2687        // reader
2688        synchronized (mPackages) {
2689            for (int i=names.length-1; i>=0; i--) {
2690                String cur = mSettings.mRenamedPackages.get(names[i]);
2691                out[i] = cur != null ? cur : names[i];
2692            }
2693        }
2694        return out;
2695    }
2696
2697    @Override
2698    public int getPackageUid(String packageName, int userId) {
2699        if (!sUserManager.exists(userId)) return -1;
2700        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2701
2702        // reader
2703        synchronized (mPackages) {
2704            PackageParser.Package p = mPackages.get(packageName);
2705            if(p != null) {
2706                return UserHandle.getUid(userId, p.applicationInfo.uid);
2707            }
2708            PackageSetting ps = mSettings.mPackages.get(packageName);
2709            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2710                return -1;
2711            }
2712            p = ps.pkg;
2713            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2714        }
2715    }
2716
2717    @Override
2718    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2719        if (!sUserManager.exists(userId)) {
2720            return null;
2721        }
2722
2723        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2724                "getPackageGids");
2725
2726        // reader
2727        synchronized (mPackages) {
2728            PackageParser.Package p = mPackages.get(packageName);
2729            if (DEBUG_PACKAGE_INFO) {
2730                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2731            }
2732            if (p != null) {
2733                PackageSetting ps = (PackageSetting) p.mExtras;
2734                return ps.getPermissionsState().computeGids(userId);
2735            }
2736        }
2737
2738        return null;
2739    }
2740
2741    static PermissionInfo generatePermissionInfo(
2742            BasePermission bp, int flags) {
2743        if (bp.perm != null) {
2744            return PackageParser.generatePermissionInfo(bp.perm, flags);
2745        }
2746        PermissionInfo pi = new PermissionInfo();
2747        pi.name = bp.name;
2748        pi.packageName = bp.sourcePackage;
2749        pi.nonLocalizedLabel = bp.name;
2750        pi.protectionLevel = bp.protectionLevel;
2751        return pi;
2752    }
2753
2754    @Override
2755    public PermissionInfo getPermissionInfo(String name, int flags) {
2756        // reader
2757        synchronized (mPackages) {
2758            final BasePermission p = mSettings.mPermissions.get(name);
2759            if (p != null) {
2760                return generatePermissionInfo(p, flags);
2761            }
2762            return null;
2763        }
2764    }
2765
2766    @Override
2767    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2768        // reader
2769        synchronized (mPackages) {
2770            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2771            for (BasePermission p : mSettings.mPermissions.values()) {
2772                if (group == null) {
2773                    if (p.perm == null || p.perm.info.group == null) {
2774                        out.add(generatePermissionInfo(p, flags));
2775                    }
2776                } else {
2777                    if (p.perm != null && group.equals(p.perm.info.group)) {
2778                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2779                    }
2780                }
2781            }
2782
2783            if (out.size() > 0) {
2784                return out;
2785            }
2786            return mPermissionGroups.containsKey(group) ? out : null;
2787        }
2788    }
2789
2790    @Override
2791    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2792        // reader
2793        synchronized (mPackages) {
2794            return PackageParser.generatePermissionGroupInfo(
2795                    mPermissionGroups.get(name), flags);
2796        }
2797    }
2798
2799    @Override
2800    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2801        // reader
2802        synchronized (mPackages) {
2803            final int N = mPermissionGroups.size();
2804            ArrayList<PermissionGroupInfo> out
2805                    = new ArrayList<PermissionGroupInfo>(N);
2806            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2807                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2808            }
2809            return out;
2810        }
2811    }
2812
2813    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2814            int userId) {
2815        if (!sUserManager.exists(userId)) return null;
2816        PackageSetting ps = mSettings.mPackages.get(packageName);
2817        if (ps != null) {
2818            if (ps.pkg == null) {
2819                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2820                        flags, userId);
2821                if (pInfo != null) {
2822                    return pInfo.applicationInfo;
2823                }
2824                return null;
2825            }
2826            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2827                    ps.readUserState(userId), userId);
2828        }
2829        return null;
2830    }
2831
2832    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2833            int userId) {
2834        if (!sUserManager.exists(userId)) return null;
2835        PackageSetting ps = mSettings.mPackages.get(packageName);
2836        if (ps != null) {
2837            PackageParser.Package pkg = ps.pkg;
2838            if (pkg == null) {
2839                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2840                    return null;
2841                }
2842                // Only data remains, so we aren't worried about code paths
2843                pkg = new PackageParser.Package(packageName);
2844                pkg.applicationInfo.packageName = packageName;
2845                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2846                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2847                pkg.applicationInfo.dataDir = Environment
2848                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2849                        .getAbsolutePath();
2850                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2851                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2852            }
2853            return generatePackageInfo(pkg, flags, userId);
2854        }
2855        return null;
2856    }
2857
2858    @Override
2859    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2860        if (!sUserManager.exists(userId)) return null;
2861        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2862        // writer
2863        synchronized (mPackages) {
2864            PackageParser.Package p = mPackages.get(packageName);
2865            if (DEBUG_PACKAGE_INFO) Log.v(
2866                    TAG, "getApplicationInfo " + packageName
2867                    + ": " + p);
2868            if (p != null) {
2869                PackageSetting ps = mSettings.mPackages.get(packageName);
2870                if (ps == null) return null;
2871                // Note: isEnabledLP() does not apply here - always return info
2872                return PackageParser.generateApplicationInfo(
2873                        p, flags, ps.readUserState(userId), userId);
2874            }
2875            if ("android".equals(packageName)||"system".equals(packageName)) {
2876                return mAndroidApplication;
2877            }
2878            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2879                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2880            }
2881        }
2882        return null;
2883    }
2884
2885    @Override
2886    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2887            final IPackageDataObserver observer) {
2888        mContext.enforceCallingOrSelfPermission(
2889                android.Manifest.permission.CLEAR_APP_CACHE, null);
2890        // Queue up an async operation since clearing cache may take a little while.
2891        mHandler.post(new Runnable() {
2892            public void run() {
2893                mHandler.removeCallbacks(this);
2894                int retCode = -1;
2895                synchronized (mInstallLock) {
2896                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2897                    if (retCode < 0) {
2898                        Slog.w(TAG, "Couldn't clear application caches");
2899                    }
2900                }
2901                if (observer != null) {
2902                    try {
2903                        observer.onRemoveCompleted(null, (retCode >= 0));
2904                    } catch (RemoteException e) {
2905                        Slog.w(TAG, "RemoveException when invoking call back");
2906                    }
2907                }
2908            }
2909        });
2910    }
2911
2912    @Override
2913    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2914            final IntentSender pi) {
2915        mContext.enforceCallingOrSelfPermission(
2916                android.Manifest.permission.CLEAR_APP_CACHE, null);
2917        // Queue up an async operation since clearing cache may take a little while.
2918        mHandler.post(new Runnable() {
2919            public void run() {
2920                mHandler.removeCallbacks(this);
2921                int retCode = -1;
2922                synchronized (mInstallLock) {
2923                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2924                    if (retCode < 0) {
2925                        Slog.w(TAG, "Couldn't clear application caches");
2926                    }
2927                }
2928                if(pi != null) {
2929                    try {
2930                        // Callback via pending intent
2931                        int code = (retCode >= 0) ? 1 : 0;
2932                        pi.sendIntent(null, code, null,
2933                                null, null);
2934                    } catch (SendIntentException e1) {
2935                        Slog.i(TAG, "Failed to send pending intent");
2936                    }
2937                }
2938            }
2939        });
2940    }
2941
2942    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2943        synchronized (mInstallLock) {
2944            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2945                throw new IOException("Failed to free enough space");
2946            }
2947        }
2948    }
2949
2950    @Override
2951    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2952        if (!sUserManager.exists(userId)) return null;
2953        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2954        synchronized (mPackages) {
2955            PackageParser.Activity a = mActivities.mActivities.get(component);
2956
2957            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2958            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2959                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2960                if (ps == null) return null;
2961                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2962                        userId);
2963            }
2964            if (mResolveComponentName.equals(component)) {
2965                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2966                        new PackageUserState(), userId);
2967            }
2968        }
2969        return null;
2970    }
2971
2972    @Override
2973    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2974            String resolvedType) {
2975        synchronized (mPackages) {
2976            if (component.equals(mResolveComponentName)) {
2977                // The resolver supports EVERYTHING!
2978                return true;
2979            }
2980            PackageParser.Activity a = mActivities.mActivities.get(component);
2981            if (a == null) {
2982                return false;
2983            }
2984            for (int i=0; i<a.intents.size(); i++) {
2985                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2986                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2987                    return true;
2988                }
2989            }
2990            return false;
2991        }
2992    }
2993
2994    @Override
2995    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2996        if (!sUserManager.exists(userId)) return null;
2997        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2998        synchronized (mPackages) {
2999            PackageParser.Activity a = mReceivers.mActivities.get(component);
3000            if (DEBUG_PACKAGE_INFO) Log.v(
3001                TAG, "getReceiverInfo " + component + ": " + a);
3002            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3003                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3004                if (ps == null) return null;
3005                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3006                        userId);
3007            }
3008        }
3009        return null;
3010    }
3011
3012    @Override
3013    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3014        if (!sUserManager.exists(userId)) return null;
3015        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3016        synchronized (mPackages) {
3017            PackageParser.Service s = mServices.mServices.get(component);
3018            if (DEBUG_PACKAGE_INFO) Log.v(
3019                TAG, "getServiceInfo " + component + ": " + s);
3020            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3021                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3022                if (ps == null) return null;
3023                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3024                        userId);
3025            }
3026        }
3027        return null;
3028    }
3029
3030    @Override
3031    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3032        if (!sUserManager.exists(userId)) return null;
3033        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3034        synchronized (mPackages) {
3035            PackageParser.Provider p = mProviders.mProviders.get(component);
3036            if (DEBUG_PACKAGE_INFO) Log.v(
3037                TAG, "getProviderInfo " + component + ": " + p);
3038            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3039                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3040                if (ps == null) return null;
3041                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3042                        userId);
3043            }
3044        }
3045        return null;
3046    }
3047
3048    @Override
3049    public String[] getSystemSharedLibraryNames() {
3050        Set<String> libSet;
3051        synchronized (mPackages) {
3052            libSet = mSharedLibraries.keySet();
3053            int size = libSet.size();
3054            if (size > 0) {
3055                String[] libs = new String[size];
3056                libSet.toArray(libs);
3057                return libs;
3058            }
3059        }
3060        return null;
3061    }
3062
3063    /**
3064     * @hide
3065     */
3066    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3067        synchronized (mPackages) {
3068            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3069            if (lib != null && lib.apk != null) {
3070                return mPackages.get(lib.apk);
3071            }
3072        }
3073        return null;
3074    }
3075
3076    @Override
3077    public FeatureInfo[] getSystemAvailableFeatures() {
3078        Collection<FeatureInfo> featSet;
3079        synchronized (mPackages) {
3080            featSet = mAvailableFeatures.values();
3081            int size = featSet.size();
3082            if (size > 0) {
3083                FeatureInfo[] features = new FeatureInfo[size+1];
3084                featSet.toArray(features);
3085                FeatureInfo fi = new FeatureInfo();
3086                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3087                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3088                features[size] = fi;
3089                return features;
3090            }
3091        }
3092        return null;
3093    }
3094
3095    @Override
3096    public boolean hasSystemFeature(String name) {
3097        synchronized (mPackages) {
3098            return mAvailableFeatures.containsKey(name);
3099        }
3100    }
3101
3102    private void checkValidCaller(int uid, int userId) {
3103        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3104            return;
3105
3106        throw new SecurityException("Caller uid=" + uid
3107                + " is not privileged to communicate with user=" + userId);
3108    }
3109
3110    @Override
3111    public int checkPermission(String permName, String pkgName, int userId) {
3112        if (!sUserManager.exists(userId)) {
3113            return PackageManager.PERMISSION_DENIED;
3114        }
3115
3116        synchronized (mPackages) {
3117            final PackageParser.Package p = mPackages.get(pkgName);
3118            if (p != null && p.mExtras != null) {
3119                final PackageSetting ps = (PackageSetting) p.mExtras;
3120                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3121                    return PackageManager.PERMISSION_GRANTED;
3122                }
3123            }
3124        }
3125
3126        return PackageManager.PERMISSION_DENIED;
3127    }
3128
3129    @Override
3130    public int checkUidPermission(String permName, int uid) {
3131        final int userId = UserHandle.getUserId(uid);
3132
3133        if (!sUserManager.exists(userId)) {
3134            return PackageManager.PERMISSION_DENIED;
3135        }
3136
3137        synchronized (mPackages) {
3138            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3139            if (obj != null) {
3140                final SettingBase ps = (SettingBase) obj;
3141                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3142                    return PackageManager.PERMISSION_GRANTED;
3143                }
3144            } else {
3145                ArraySet<String> perms = mSystemPermissions.get(uid);
3146                if (perms != null && perms.contains(permName)) {
3147                    return PackageManager.PERMISSION_GRANTED;
3148                }
3149            }
3150        }
3151
3152        return PackageManager.PERMISSION_DENIED;
3153    }
3154
3155    @Override
3156    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3157        if (UserHandle.getCallingUserId() != userId) {
3158            mContext.enforceCallingPermission(
3159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3160                    "isPermissionRevokedByPolicy for user " + userId);
3161        }
3162
3163        if (checkPermission(permission, packageName, userId)
3164                == PackageManager.PERMISSION_GRANTED) {
3165            return false;
3166        }
3167
3168        final long identity = Binder.clearCallingIdentity();
3169        try {
3170            final int flags = getPermissionFlags(permission, packageName, userId);
3171            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3172        } finally {
3173            Binder.restoreCallingIdentity(identity);
3174        }
3175    }
3176
3177    /**
3178     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3179     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3180     * @param checkShell TODO(yamasani):
3181     * @param message the message to log on security exception
3182     */
3183    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3184            boolean checkShell, String message) {
3185        if (userId < 0) {
3186            throw new IllegalArgumentException("Invalid userId " + userId);
3187        }
3188        if (checkShell) {
3189            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3190        }
3191        if (userId == UserHandle.getUserId(callingUid)) return;
3192        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3193            if (requireFullPermission) {
3194                mContext.enforceCallingOrSelfPermission(
3195                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3196            } else {
3197                try {
3198                    mContext.enforceCallingOrSelfPermission(
3199                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3200                } catch (SecurityException se) {
3201                    mContext.enforceCallingOrSelfPermission(
3202                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3203                }
3204            }
3205        }
3206    }
3207
3208    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3209        if (callingUid == Process.SHELL_UID) {
3210            if (userHandle >= 0
3211                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3212                throw new SecurityException("Shell does not have permission to access user "
3213                        + userHandle);
3214            } else if (userHandle < 0) {
3215                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3216                        + Debug.getCallers(3));
3217            }
3218        }
3219    }
3220
3221    private BasePermission findPermissionTreeLP(String permName) {
3222        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3223            if (permName.startsWith(bp.name) &&
3224                    permName.length() > bp.name.length() &&
3225                    permName.charAt(bp.name.length()) == '.') {
3226                return bp;
3227            }
3228        }
3229        return null;
3230    }
3231
3232    private BasePermission checkPermissionTreeLP(String permName) {
3233        if (permName != null) {
3234            BasePermission bp = findPermissionTreeLP(permName);
3235            if (bp != null) {
3236                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3237                    return bp;
3238                }
3239                throw new SecurityException("Calling uid "
3240                        + Binder.getCallingUid()
3241                        + " is not allowed to add to permission tree "
3242                        + bp.name + " owned by uid " + bp.uid);
3243            }
3244        }
3245        throw new SecurityException("No permission tree found for " + permName);
3246    }
3247
3248    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3249        if (s1 == null) {
3250            return s2 == null;
3251        }
3252        if (s2 == null) {
3253            return false;
3254        }
3255        if (s1.getClass() != s2.getClass()) {
3256            return false;
3257        }
3258        return s1.equals(s2);
3259    }
3260
3261    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3262        if (pi1.icon != pi2.icon) return false;
3263        if (pi1.logo != pi2.logo) return false;
3264        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3265        if (!compareStrings(pi1.name, pi2.name)) return false;
3266        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3267        // We'll take care of setting this one.
3268        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3269        // These are not currently stored in settings.
3270        //if (!compareStrings(pi1.group, pi2.group)) return false;
3271        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3272        //if (pi1.labelRes != pi2.labelRes) return false;
3273        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3274        return true;
3275    }
3276
3277    int permissionInfoFootprint(PermissionInfo info) {
3278        int size = info.name.length();
3279        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3280        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3281        return size;
3282    }
3283
3284    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3285        int size = 0;
3286        for (BasePermission perm : mSettings.mPermissions.values()) {
3287            if (perm.uid == tree.uid) {
3288                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3289            }
3290        }
3291        return size;
3292    }
3293
3294    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3295        // We calculate the max size of permissions defined by this uid and throw
3296        // if that plus the size of 'info' would exceed our stated maximum.
3297        if (tree.uid != Process.SYSTEM_UID) {
3298            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3299            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3300                throw new SecurityException("Permission tree size cap exceeded");
3301            }
3302        }
3303    }
3304
3305    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3306        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3307            throw new SecurityException("Label must be specified in permission");
3308        }
3309        BasePermission tree = checkPermissionTreeLP(info.name);
3310        BasePermission bp = mSettings.mPermissions.get(info.name);
3311        boolean added = bp == null;
3312        boolean changed = true;
3313        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3314        if (added) {
3315            enforcePermissionCapLocked(info, tree);
3316            bp = new BasePermission(info.name, tree.sourcePackage,
3317                    BasePermission.TYPE_DYNAMIC);
3318        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3319            throw new SecurityException(
3320                    "Not allowed to modify non-dynamic permission "
3321                    + info.name);
3322        } else {
3323            if (bp.protectionLevel == fixedLevel
3324                    && bp.perm.owner.equals(tree.perm.owner)
3325                    && bp.uid == tree.uid
3326                    && comparePermissionInfos(bp.perm.info, info)) {
3327                changed = false;
3328            }
3329        }
3330        bp.protectionLevel = fixedLevel;
3331        info = new PermissionInfo(info);
3332        info.protectionLevel = fixedLevel;
3333        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3334        bp.perm.info.packageName = tree.perm.info.packageName;
3335        bp.uid = tree.uid;
3336        if (added) {
3337            mSettings.mPermissions.put(info.name, bp);
3338        }
3339        if (changed) {
3340            if (!async) {
3341                mSettings.writeLPr();
3342            } else {
3343                scheduleWriteSettingsLocked();
3344            }
3345        }
3346        return added;
3347    }
3348
3349    @Override
3350    public boolean addPermission(PermissionInfo info) {
3351        synchronized (mPackages) {
3352            return addPermissionLocked(info, false);
3353        }
3354    }
3355
3356    @Override
3357    public boolean addPermissionAsync(PermissionInfo info) {
3358        synchronized (mPackages) {
3359            return addPermissionLocked(info, true);
3360        }
3361    }
3362
3363    @Override
3364    public void removePermission(String name) {
3365        synchronized (mPackages) {
3366            checkPermissionTreeLP(name);
3367            BasePermission bp = mSettings.mPermissions.get(name);
3368            if (bp != null) {
3369                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3370                    throw new SecurityException(
3371                            "Not allowed to modify non-dynamic permission "
3372                            + name);
3373                }
3374                mSettings.mPermissions.remove(name);
3375                mSettings.writeLPr();
3376            }
3377        }
3378    }
3379
3380    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3381            BasePermission bp) {
3382        int index = pkg.requestedPermissions.indexOf(bp.name);
3383        if (index == -1) {
3384            throw new SecurityException("Package " + pkg.packageName
3385                    + " has not requested permission " + bp.name);
3386        }
3387        if (!bp.isRuntime()) {
3388            throw new SecurityException("Permission " + bp.name
3389                    + " is not a changeable permission type");
3390        }
3391    }
3392
3393    @Override
3394    public void grantRuntimePermission(String packageName, String name, final int userId) {
3395        if (!sUserManager.exists(userId)) {
3396            Log.e(TAG, "No such user:" + userId);
3397            return;
3398        }
3399
3400        mContext.enforceCallingOrSelfPermission(
3401                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3402                "grantRuntimePermission");
3403
3404        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3405                "grantRuntimePermission");
3406
3407        final int uid;
3408        final SettingBase sb;
3409
3410        synchronized (mPackages) {
3411            final PackageParser.Package pkg = mPackages.get(packageName);
3412            if (pkg == null) {
3413                throw new IllegalArgumentException("Unknown package: " + packageName);
3414            }
3415
3416            final BasePermission bp = mSettings.mPermissions.get(name);
3417            if (bp == null) {
3418                throw new IllegalArgumentException("Unknown permission: " + name);
3419            }
3420
3421            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3422
3423            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3424            sb = (SettingBase) pkg.mExtras;
3425            if (sb == null) {
3426                throw new IllegalArgumentException("Unknown package: " + packageName);
3427            }
3428
3429            final PermissionsState permissionsState = sb.getPermissionsState();
3430
3431            final int flags = permissionsState.getPermissionFlags(name, userId);
3432            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3433                throw new SecurityException("Cannot grant system fixed permission: "
3434                        + name + " for package: " + packageName);
3435            }
3436
3437            final int result = permissionsState.grantRuntimePermission(bp, userId);
3438            switch (result) {
3439                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3440                    return;
3441                }
3442
3443                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3444                    mHandler.post(new Runnable() {
3445                        @Override
3446                        public void run() {
3447                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3448                        }
3449                    });
3450                } break;
3451            }
3452
3453            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3454
3455            // Not critical if that is lost - app has to request again.
3456            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3457        }
3458
3459        // Only need to do this if user is initialized. Otherwise it's a new user
3460        // and there are no processes running as the user yet and there's no need
3461        // to make an expensive call to remount processes for the changed permissions.
3462        if (READ_EXTERNAL_STORAGE.equals(name)
3463                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3464            final long token = Binder.clearCallingIdentity();
3465            try {
3466                if (sUserManager.isInitialized(userId)) {
3467                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3468                            MountServiceInternal.class);
3469                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3470                }
3471            } finally {
3472                Binder.restoreCallingIdentity(token);
3473            }
3474        }
3475    }
3476
3477    @Override
3478    public void revokeRuntimePermission(String packageName, String name, int userId) {
3479        if (!sUserManager.exists(userId)) {
3480            Log.e(TAG, "No such user:" + userId);
3481            return;
3482        }
3483
3484        mContext.enforceCallingOrSelfPermission(
3485                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3486                "revokeRuntimePermission");
3487
3488        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3489                "revokeRuntimePermission");
3490
3491        final SettingBase sb;
3492
3493        synchronized (mPackages) {
3494            final PackageParser.Package pkg = mPackages.get(packageName);
3495            if (pkg == null) {
3496                throw new IllegalArgumentException("Unknown package: " + packageName);
3497            }
3498
3499            final BasePermission bp = mSettings.mPermissions.get(name);
3500            if (bp == null) {
3501                throw new IllegalArgumentException("Unknown permission: " + name);
3502            }
3503
3504            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3505
3506            sb = (SettingBase) pkg.mExtras;
3507            if (sb == null) {
3508                throw new IllegalArgumentException("Unknown package: " + packageName);
3509            }
3510
3511            final PermissionsState permissionsState = sb.getPermissionsState();
3512
3513            final int flags = permissionsState.getPermissionFlags(name, userId);
3514            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3515                throw new SecurityException("Cannot revoke system fixed permission: "
3516                        + name + " for package: " + packageName);
3517            }
3518
3519            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3520                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3521                return;
3522            }
3523
3524            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3525
3526            // Critical, after this call app should never have the permission.
3527            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3528        }
3529
3530        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3531    }
3532
3533    @Override
3534    public void resetRuntimePermissions() {
3535        mContext.enforceCallingOrSelfPermission(
3536                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3537                "revokeRuntimePermission");
3538
3539        int callingUid = Binder.getCallingUid();
3540        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3541            mContext.enforceCallingOrSelfPermission(
3542                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3543                    "resetRuntimePermissions");
3544        }
3545
3546        synchronized (mPackages) {
3547            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3548            for (int userId : UserManagerService.getInstance().getUserIds()) {
3549                final int packageCount = mPackages.size();
3550                for (int i = 0; i < packageCount; i++) {
3551                    PackageParser.Package pkg = mPackages.valueAt(i);
3552                    if (!(pkg.mExtras instanceof PackageSetting)) {
3553                        continue;
3554                    }
3555                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3556                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3557                }
3558            }
3559        }
3560    }
3561
3562    @Override
3563    public int getPermissionFlags(String name, String packageName, int userId) {
3564        if (!sUserManager.exists(userId)) {
3565            return 0;
3566        }
3567
3568        enforceGrantRevokeRuntimePermissionPermissions("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        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3602
3603        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3604                "updatePermissionFlags");
3605
3606        // Only the system can change these flags and nothing else.
3607        if (getCallingUid() != Process.SYSTEM_UID) {
3608            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3609            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3610            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3611            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3612            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3613            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3614        }
3615
3616        synchronized (mPackages) {
3617            final PackageParser.Package pkg = mPackages.get(packageName);
3618            if (pkg == null) {
3619                throw new IllegalArgumentException("Unknown package: " + packageName);
3620            }
3621
3622            final BasePermission bp = mSettings.mPermissions.get(name);
3623            if (bp == null) {
3624                throw new IllegalArgumentException("Unknown permission: " + name);
3625            }
3626
3627            SettingBase sb = (SettingBase) pkg.mExtras;
3628            if (sb == null) {
3629                throw new IllegalArgumentException("Unknown package: " + packageName);
3630            }
3631
3632            PermissionsState permissionsState = sb.getPermissionsState();
3633
3634            // Only the package manager can change flags for system component permissions.
3635            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3636            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3637                return;
3638            }
3639
3640            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3641
3642            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3643                // Install and runtime permissions are stored in different places,
3644                // so figure out what permission changed and persist the change.
3645                if (permissionsState.getInstallPermissionState(name) != null) {
3646                    scheduleWriteSettingsLocked();
3647                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3648                        || hadState) {
3649                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3650                }
3651            }
3652        }
3653    }
3654
3655    /**
3656     * Update the permission flags for all packages and runtime permissions of a user in order
3657     * to allow device or profile owner to remove POLICY_FIXED.
3658     */
3659    @Override
3660    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3661        if (!sUserManager.exists(userId)) {
3662            return;
3663        }
3664
3665        enforceGrantRevokeRuntimePermissionPermissions("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    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3696        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3697                != PackageManager.PERMISSION_GRANTED
3698            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3699                != PackageManager.PERMISSION_GRANTED) {
3700            throw new SecurityException(message + " requires "
3701                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3702                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3703        }
3704    }
3705
3706    @Override
3707    public boolean shouldShowRequestPermissionRationale(String permissionName,
3708            String packageName, int userId) {
3709        if (UserHandle.getCallingUserId() != userId) {
3710            mContext.enforceCallingPermission(
3711                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3712                    "canShowRequestPermissionRationale for user " + userId);
3713        }
3714
3715        final int uid = getPackageUid(packageName, userId);
3716        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3717            return false;
3718        }
3719
3720        if (checkPermission(permissionName, packageName, userId)
3721                == PackageManager.PERMISSION_GRANTED) {
3722            return false;
3723        }
3724
3725        final int flags;
3726
3727        final long identity = Binder.clearCallingIdentity();
3728        try {
3729            flags = getPermissionFlags(permissionName,
3730                    packageName, userId);
3731        } finally {
3732            Binder.restoreCallingIdentity(identity);
3733        }
3734
3735        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3736                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3737                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3738
3739        if ((flags & fixedFlags) != 0) {
3740            return false;
3741        }
3742
3743        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3744    }
3745
3746    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3747        BasePermission bp = mSettings.mPermissions.get(permission);
3748        if (bp == null) {
3749            throw new SecurityException("Missing " + permission + " permission");
3750        }
3751
3752        SettingBase sb = (SettingBase) pkg.mExtras;
3753        PermissionsState permissionsState = sb.getPermissionsState();
3754
3755        if (permissionsState.grantInstallPermission(bp) !=
3756                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3757            scheduleWriteSettingsLocked();
3758        }
3759    }
3760
3761    @Override
3762    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3763        mContext.enforceCallingOrSelfPermission(
3764                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3765                "addOnPermissionsChangeListener");
3766
3767        synchronized (mPackages) {
3768            mOnPermissionChangeListeners.addListenerLocked(listener);
3769        }
3770    }
3771
3772    @Override
3773    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3774        synchronized (mPackages) {
3775            mOnPermissionChangeListeners.removeListenerLocked(listener);
3776        }
3777    }
3778
3779    @Override
3780    public boolean isProtectedBroadcast(String actionName) {
3781        synchronized (mPackages) {
3782            return mProtectedBroadcasts.contains(actionName);
3783        }
3784    }
3785
3786    @Override
3787    public int checkSignatures(String pkg1, String pkg2) {
3788        synchronized (mPackages) {
3789            final PackageParser.Package p1 = mPackages.get(pkg1);
3790            final PackageParser.Package p2 = mPackages.get(pkg2);
3791            if (p1 == null || p1.mExtras == null
3792                    || p2 == null || p2.mExtras == null) {
3793                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3794            }
3795            return compareSignatures(p1.mSignatures, p2.mSignatures);
3796        }
3797    }
3798
3799    @Override
3800    public int checkUidSignatures(int uid1, int uid2) {
3801        // Map to base uids.
3802        uid1 = UserHandle.getAppId(uid1);
3803        uid2 = UserHandle.getAppId(uid2);
3804        // reader
3805        synchronized (mPackages) {
3806            Signature[] s1;
3807            Signature[] s2;
3808            Object obj = mSettings.getUserIdLPr(uid1);
3809            if (obj != null) {
3810                if (obj instanceof SharedUserSetting) {
3811                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3812                } else if (obj instanceof PackageSetting) {
3813                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3814                } else {
3815                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3816                }
3817            } else {
3818                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3819            }
3820            obj = mSettings.getUserIdLPr(uid2);
3821            if (obj != null) {
3822                if (obj instanceof SharedUserSetting) {
3823                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3824                } else if (obj instanceof PackageSetting) {
3825                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3826                } else {
3827                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3828                }
3829            } else {
3830                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3831            }
3832            return compareSignatures(s1, s2);
3833        }
3834    }
3835
3836    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3837        final long identity = Binder.clearCallingIdentity();
3838        try {
3839            if (sb instanceof SharedUserSetting) {
3840                SharedUserSetting sus = (SharedUserSetting) sb;
3841                final int packageCount = sus.packages.size();
3842                for (int i = 0; i < packageCount; i++) {
3843                    PackageSetting susPs = sus.packages.valueAt(i);
3844                    if (userId == UserHandle.USER_ALL) {
3845                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3846                    } else {
3847                        final int uid = UserHandle.getUid(userId, susPs.appId);
3848                        killUid(uid, reason);
3849                    }
3850                }
3851            } else if (sb instanceof PackageSetting) {
3852                PackageSetting ps = (PackageSetting) sb;
3853                if (userId == UserHandle.USER_ALL) {
3854                    killApplication(ps.pkg.packageName, ps.appId, reason);
3855                } else {
3856                    final int uid = UserHandle.getUid(userId, ps.appId);
3857                    killUid(uid, reason);
3858                }
3859            }
3860        } finally {
3861            Binder.restoreCallingIdentity(identity);
3862        }
3863    }
3864
3865    private static void killUid(int uid, String reason) {
3866        IActivityManager am = ActivityManagerNative.getDefault();
3867        if (am != null) {
3868            try {
3869                am.killUid(uid, reason);
3870            } catch (RemoteException e) {
3871                /* ignore - same process */
3872            }
3873        }
3874    }
3875
3876    /**
3877     * Compares two sets of signatures. Returns:
3878     * <br />
3879     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3880     * <br />
3881     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3882     * <br />
3883     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3884     * <br />
3885     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3886     * <br />
3887     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3888     */
3889    static int compareSignatures(Signature[] s1, Signature[] s2) {
3890        if (s1 == null) {
3891            return s2 == null
3892                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3893                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3894        }
3895
3896        if (s2 == null) {
3897            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3898        }
3899
3900        if (s1.length != s2.length) {
3901            return PackageManager.SIGNATURE_NO_MATCH;
3902        }
3903
3904        // Since both signature sets are of size 1, we can compare without HashSets.
3905        if (s1.length == 1) {
3906            return s1[0].equals(s2[0]) ?
3907                    PackageManager.SIGNATURE_MATCH :
3908                    PackageManager.SIGNATURE_NO_MATCH;
3909        }
3910
3911        ArraySet<Signature> set1 = new ArraySet<Signature>();
3912        for (Signature sig : s1) {
3913            set1.add(sig);
3914        }
3915        ArraySet<Signature> set2 = new ArraySet<Signature>();
3916        for (Signature sig : s2) {
3917            set2.add(sig);
3918        }
3919        // Make sure s2 contains all signatures in s1.
3920        if (set1.equals(set2)) {
3921            return PackageManager.SIGNATURE_MATCH;
3922        }
3923        return PackageManager.SIGNATURE_NO_MATCH;
3924    }
3925
3926    /**
3927     * If the database version for this type of package (internal storage or
3928     * external storage) is less than the version where package signatures
3929     * were updated, return true.
3930     */
3931    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3932        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3933        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3934    }
3935
3936    /**
3937     * Used for backward compatibility to make sure any packages with
3938     * certificate chains get upgraded to the new style. {@code existingSigs}
3939     * will be in the old format (since they were stored on disk from before the
3940     * system upgrade) and {@code scannedSigs} will be in the newer format.
3941     */
3942    private int compareSignaturesCompat(PackageSignatures existingSigs,
3943            PackageParser.Package scannedPkg) {
3944        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3945            return PackageManager.SIGNATURE_NO_MATCH;
3946        }
3947
3948        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3949        for (Signature sig : existingSigs.mSignatures) {
3950            existingSet.add(sig);
3951        }
3952        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3953        for (Signature sig : scannedPkg.mSignatures) {
3954            try {
3955                Signature[] chainSignatures = sig.getChainSignatures();
3956                for (Signature chainSig : chainSignatures) {
3957                    scannedCompatSet.add(chainSig);
3958                }
3959            } catch (CertificateEncodingException e) {
3960                scannedCompatSet.add(sig);
3961            }
3962        }
3963        /*
3964         * Make sure the expanded scanned set contains all signatures in the
3965         * existing one.
3966         */
3967        if (scannedCompatSet.equals(existingSet)) {
3968            // Migrate the old signatures to the new scheme.
3969            existingSigs.assignSignatures(scannedPkg.mSignatures);
3970            // The new KeySets will be re-added later in the scanning process.
3971            synchronized (mPackages) {
3972                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3973            }
3974            return PackageManager.SIGNATURE_MATCH;
3975        }
3976        return PackageManager.SIGNATURE_NO_MATCH;
3977    }
3978
3979    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3980        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3981        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
3982    }
3983
3984    private int compareSignaturesRecover(PackageSignatures existingSigs,
3985            PackageParser.Package scannedPkg) {
3986        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3987            return PackageManager.SIGNATURE_NO_MATCH;
3988        }
3989
3990        String msg = null;
3991        try {
3992            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3993                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3994                        + scannedPkg.packageName);
3995                return PackageManager.SIGNATURE_MATCH;
3996            }
3997        } catch (CertificateException e) {
3998            msg = e.getMessage();
3999        }
4000
4001        logCriticalInfo(Log.INFO,
4002                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4003        return PackageManager.SIGNATURE_NO_MATCH;
4004    }
4005
4006    @Override
4007    public String[] getPackagesForUid(int uid) {
4008        uid = UserHandle.getAppId(uid);
4009        // reader
4010        synchronized (mPackages) {
4011            Object obj = mSettings.getUserIdLPr(uid);
4012            if (obj instanceof SharedUserSetting) {
4013                final SharedUserSetting sus = (SharedUserSetting) obj;
4014                final int N = sus.packages.size();
4015                final String[] res = new String[N];
4016                final Iterator<PackageSetting> it = sus.packages.iterator();
4017                int i = 0;
4018                while (it.hasNext()) {
4019                    res[i++] = it.next().name;
4020                }
4021                return res;
4022            } else if (obj instanceof PackageSetting) {
4023                final PackageSetting ps = (PackageSetting) obj;
4024                return new String[] { ps.name };
4025            }
4026        }
4027        return null;
4028    }
4029
4030    @Override
4031    public String getNameForUid(int uid) {
4032        // reader
4033        synchronized (mPackages) {
4034            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4035            if (obj instanceof SharedUserSetting) {
4036                final SharedUserSetting sus = (SharedUserSetting) obj;
4037                return sus.name + ":" + sus.userId;
4038            } else if (obj instanceof PackageSetting) {
4039                final PackageSetting ps = (PackageSetting) obj;
4040                return ps.name;
4041            }
4042        }
4043        return null;
4044    }
4045
4046    @Override
4047    public int getUidForSharedUser(String sharedUserName) {
4048        if(sharedUserName == null) {
4049            return -1;
4050        }
4051        // reader
4052        synchronized (mPackages) {
4053            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4054            if (suid == null) {
4055                return -1;
4056            }
4057            return suid.userId;
4058        }
4059    }
4060
4061    @Override
4062    public int getFlagsForUid(int uid) {
4063        synchronized (mPackages) {
4064            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4065            if (obj instanceof SharedUserSetting) {
4066                final SharedUserSetting sus = (SharedUserSetting) obj;
4067                return sus.pkgFlags;
4068            } else if (obj instanceof PackageSetting) {
4069                final PackageSetting ps = (PackageSetting) obj;
4070                return ps.pkgFlags;
4071            }
4072        }
4073        return 0;
4074    }
4075
4076    @Override
4077    public int getPrivateFlagsForUid(int uid) {
4078        synchronized (mPackages) {
4079            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4080            if (obj instanceof SharedUserSetting) {
4081                final SharedUserSetting sus = (SharedUserSetting) obj;
4082                return sus.pkgPrivateFlags;
4083            } else if (obj instanceof PackageSetting) {
4084                final PackageSetting ps = (PackageSetting) obj;
4085                return ps.pkgPrivateFlags;
4086            }
4087        }
4088        return 0;
4089    }
4090
4091    @Override
4092    public boolean isUidPrivileged(int uid) {
4093        uid = UserHandle.getAppId(uid);
4094        // reader
4095        synchronized (mPackages) {
4096            Object obj = mSettings.getUserIdLPr(uid);
4097            if (obj instanceof SharedUserSetting) {
4098                final SharedUserSetting sus = (SharedUserSetting) obj;
4099                final Iterator<PackageSetting> it = sus.packages.iterator();
4100                while (it.hasNext()) {
4101                    if (it.next().isPrivileged()) {
4102                        return true;
4103                    }
4104                }
4105            } else if (obj instanceof PackageSetting) {
4106                final PackageSetting ps = (PackageSetting) obj;
4107                return ps.isPrivileged();
4108            }
4109        }
4110        return false;
4111    }
4112
4113    @Override
4114    public String[] getAppOpPermissionPackages(String permissionName) {
4115        synchronized (mPackages) {
4116            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4117            if (pkgs == null) {
4118                return null;
4119            }
4120            return pkgs.toArray(new String[pkgs.size()]);
4121        }
4122    }
4123
4124    @Override
4125    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4126            int flags, int userId) {
4127        if (!sUserManager.exists(userId)) return null;
4128        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4129        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4130        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4131    }
4132
4133    @Override
4134    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4135            IntentFilter filter, int match, ComponentName activity) {
4136        final int userId = UserHandle.getCallingUserId();
4137        if (DEBUG_PREFERRED) {
4138            Log.v(TAG, "setLastChosenActivity intent=" + intent
4139                + " resolvedType=" + resolvedType
4140                + " flags=" + flags
4141                + " filter=" + filter
4142                + " match=" + match
4143                + " activity=" + activity);
4144            filter.dump(new PrintStreamPrinter(System.out), "    ");
4145        }
4146        intent.setComponent(null);
4147        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4148        // Find any earlier preferred or last chosen entries and nuke them
4149        findPreferredActivity(intent, resolvedType,
4150                flags, query, 0, false, true, false, userId);
4151        // Add the new activity as the last chosen for this filter
4152        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4153                "Setting last chosen");
4154    }
4155
4156    @Override
4157    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4158        final int userId = UserHandle.getCallingUserId();
4159        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4160        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4161        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4162                false, false, false, userId);
4163    }
4164
4165    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4166            int flags, List<ResolveInfo> query, int userId) {
4167        if (query != null) {
4168            final int N = query.size();
4169            if (N == 1) {
4170                return query.get(0);
4171            } else if (N > 1) {
4172                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4173                // If there is more than one activity with the same priority,
4174                // then let the user decide between them.
4175                ResolveInfo r0 = query.get(0);
4176                ResolveInfo r1 = query.get(1);
4177                if (DEBUG_INTENT_MATCHING || debug) {
4178                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4179                            + r1.activityInfo.name + "=" + r1.priority);
4180                }
4181                // If the first activity has a higher priority, or a different
4182                // default, then it is always desireable to pick it.
4183                if (r0.priority != r1.priority
4184                        || r0.preferredOrder != r1.preferredOrder
4185                        || r0.isDefault != r1.isDefault) {
4186                    return query.get(0);
4187                }
4188                // If we have saved a preference for a preferred activity for
4189                // this Intent, use that.
4190                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4191                        flags, query, r0.priority, true, false, debug, userId);
4192                if (ri != null) {
4193                    return ri;
4194                }
4195                if (userId != 0) {
4196                    ri = new ResolveInfo(mResolveInfo);
4197                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4198                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4199                            ri.activityInfo.applicationInfo);
4200                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4201                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4202                    return ri;
4203                }
4204                return mResolveInfo;
4205            }
4206        }
4207        return null;
4208    }
4209
4210    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4211            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4212        final int N = query.size();
4213        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4214                .get(userId);
4215        // Get the list of persistent preferred activities that handle the intent
4216        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4217        List<PersistentPreferredActivity> pprefs = ppir != null
4218                ? ppir.queryIntent(intent, resolvedType,
4219                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4220                : null;
4221        if (pprefs != null && pprefs.size() > 0) {
4222            final int M = pprefs.size();
4223            for (int i=0; i<M; i++) {
4224                final PersistentPreferredActivity ppa = pprefs.get(i);
4225                if (DEBUG_PREFERRED || debug) {
4226                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4227                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4228                            + "\n  component=" + ppa.mComponent);
4229                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4230                }
4231                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4232                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4233                if (DEBUG_PREFERRED || debug) {
4234                    Slog.v(TAG, "Found persistent preferred activity:");
4235                    if (ai != null) {
4236                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4237                    } else {
4238                        Slog.v(TAG, "  null");
4239                    }
4240                }
4241                if (ai == null) {
4242                    // This previously registered persistent preferred activity
4243                    // component is no longer known. Ignore it and do NOT remove it.
4244                    continue;
4245                }
4246                for (int j=0; j<N; j++) {
4247                    final ResolveInfo ri = query.get(j);
4248                    if (!ri.activityInfo.applicationInfo.packageName
4249                            .equals(ai.applicationInfo.packageName)) {
4250                        continue;
4251                    }
4252                    if (!ri.activityInfo.name.equals(ai.name)) {
4253                        continue;
4254                    }
4255                    //  Found a persistent preference that can handle the intent.
4256                    if (DEBUG_PREFERRED || debug) {
4257                        Slog.v(TAG, "Returning persistent preferred activity: " +
4258                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4259                    }
4260                    return ri;
4261                }
4262            }
4263        }
4264        return null;
4265    }
4266
4267    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4268            List<ResolveInfo> query, int priority, boolean always,
4269            boolean removeMatches, boolean debug, int userId) {
4270        if (!sUserManager.exists(userId)) return null;
4271        // writer
4272        synchronized (mPackages) {
4273            if (intent.getSelector() != null) {
4274                intent = intent.getSelector();
4275            }
4276            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4277
4278            // Try to find a matching persistent preferred activity.
4279            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4280                    debug, userId);
4281
4282            // If a persistent preferred activity matched, use it.
4283            if (pri != null) {
4284                return pri;
4285            }
4286
4287            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4288            // Get the list of preferred activities that handle the intent
4289            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4290            List<PreferredActivity> prefs = pir != null
4291                    ? pir.queryIntent(intent, resolvedType,
4292                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4293                    : null;
4294            if (prefs != null && prefs.size() > 0) {
4295                boolean changed = false;
4296                try {
4297                    // First figure out how good the original match set is.
4298                    // We will only allow preferred activities that came
4299                    // from the same match quality.
4300                    int match = 0;
4301
4302                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4303
4304                    final int N = query.size();
4305                    for (int j=0; j<N; j++) {
4306                        final ResolveInfo ri = query.get(j);
4307                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4308                                + ": 0x" + Integer.toHexString(match));
4309                        if (ri.match > match) {
4310                            match = ri.match;
4311                        }
4312                    }
4313
4314                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4315                            + Integer.toHexString(match));
4316
4317                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4318                    final int M = prefs.size();
4319                    for (int i=0; i<M; i++) {
4320                        final PreferredActivity pa = prefs.get(i);
4321                        if (DEBUG_PREFERRED || debug) {
4322                            Slog.v(TAG, "Checking PreferredActivity ds="
4323                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4324                                    + "\n  component=" + pa.mPref.mComponent);
4325                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4326                        }
4327                        if (pa.mPref.mMatch != match) {
4328                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4329                                    + Integer.toHexString(pa.mPref.mMatch));
4330                            continue;
4331                        }
4332                        // If it's not an "always" type preferred activity and that's what we're
4333                        // looking for, skip it.
4334                        if (always && !pa.mPref.mAlways) {
4335                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4336                            continue;
4337                        }
4338                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4339                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4340                        if (DEBUG_PREFERRED || debug) {
4341                            Slog.v(TAG, "Found preferred activity:");
4342                            if (ai != null) {
4343                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4344                            } else {
4345                                Slog.v(TAG, "  null");
4346                            }
4347                        }
4348                        if (ai == null) {
4349                            // This previously registered preferred activity
4350                            // component is no longer known.  Most likely an update
4351                            // to the app was installed and in the new version this
4352                            // component no longer exists.  Clean it up by removing
4353                            // it from the preferred activities list, and skip it.
4354                            Slog.w(TAG, "Removing dangling preferred activity: "
4355                                    + pa.mPref.mComponent);
4356                            pir.removeFilter(pa);
4357                            changed = true;
4358                            continue;
4359                        }
4360                        for (int j=0; j<N; j++) {
4361                            final ResolveInfo ri = query.get(j);
4362                            if (!ri.activityInfo.applicationInfo.packageName
4363                                    .equals(ai.applicationInfo.packageName)) {
4364                                continue;
4365                            }
4366                            if (!ri.activityInfo.name.equals(ai.name)) {
4367                                continue;
4368                            }
4369
4370                            if (removeMatches) {
4371                                pir.removeFilter(pa);
4372                                changed = true;
4373                                if (DEBUG_PREFERRED) {
4374                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4375                                }
4376                                break;
4377                            }
4378
4379                            // Okay we found a previously set preferred or last chosen app.
4380                            // If the result set is different from when this
4381                            // was created, we need to clear it and re-ask the
4382                            // user their preference, if we're looking for an "always" type entry.
4383                            if (always && !pa.mPref.sameSet(query)) {
4384                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4385                                        + intent + " type " + resolvedType);
4386                                if (DEBUG_PREFERRED) {
4387                                    Slog.v(TAG, "Removing preferred activity since set changed "
4388                                            + pa.mPref.mComponent);
4389                                }
4390                                pir.removeFilter(pa);
4391                                // Re-add the filter as a "last chosen" entry (!always)
4392                                PreferredActivity lastChosen = new PreferredActivity(
4393                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4394                                pir.addFilter(lastChosen);
4395                                changed = true;
4396                                return null;
4397                            }
4398
4399                            // Yay! Either the set matched or we're looking for the last chosen
4400                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4401                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4402                            return ri;
4403                        }
4404                    }
4405                } finally {
4406                    if (changed) {
4407                        if (DEBUG_PREFERRED) {
4408                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4409                        }
4410                        scheduleWritePackageRestrictionsLocked(userId);
4411                    }
4412                }
4413            }
4414        }
4415        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4416        return null;
4417    }
4418
4419    /*
4420     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4421     */
4422    @Override
4423    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4424            int targetUserId) {
4425        mContext.enforceCallingOrSelfPermission(
4426                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4427        List<CrossProfileIntentFilter> matches =
4428                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4429        if (matches != null) {
4430            int size = matches.size();
4431            for (int i = 0; i < size; i++) {
4432                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4433            }
4434        }
4435        if (hasWebURI(intent)) {
4436            // cross-profile app linking works only towards the parent.
4437            final UserInfo parent = getProfileParent(sourceUserId);
4438            synchronized(mPackages) {
4439                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4440                        intent, resolvedType, 0, sourceUserId, parent.id);
4441                return xpDomainInfo != null;
4442            }
4443        }
4444        return false;
4445    }
4446
4447    private UserInfo getProfileParent(int userId) {
4448        final long identity = Binder.clearCallingIdentity();
4449        try {
4450            return sUserManager.getProfileParent(userId);
4451        } finally {
4452            Binder.restoreCallingIdentity(identity);
4453        }
4454    }
4455
4456    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4457            String resolvedType, int userId) {
4458        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4459        if (resolver != null) {
4460            return resolver.queryIntent(intent, resolvedType, false, userId);
4461        }
4462        return null;
4463    }
4464
4465    @Override
4466    public List<ResolveInfo> queryIntentActivities(Intent intent,
4467            String resolvedType, int flags, int userId) {
4468        if (!sUserManager.exists(userId)) return Collections.emptyList();
4469        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4470        ComponentName comp = intent.getComponent();
4471        if (comp == null) {
4472            if (intent.getSelector() != null) {
4473                intent = intent.getSelector();
4474                comp = intent.getComponent();
4475            }
4476        }
4477
4478        if (comp != null) {
4479            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4480            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4481            if (ai != null) {
4482                final ResolveInfo ri = new ResolveInfo();
4483                ri.activityInfo = ai;
4484                list.add(ri);
4485            }
4486            return list;
4487        }
4488
4489        // reader
4490        synchronized (mPackages) {
4491            final String pkgName = intent.getPackage();
4492            if (pkgName == null) {
4493                List<CrossProfileIntentFilter> matchingFilters =
4494                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4495                // Check for results that need to skip the current profile.
4496                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4497                        resolvedType, flags, userId);
4498                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4499                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4500                    result.add(xpResolveInfo);
4501                    return filterIfNotPrimaryUser(result, userId);
4502                }
4503
4504                // Check for results in the current profile.
4505                List<ResolveInfo> result = mActivities.queryIntent(
4506                        intent, resolvedType, flags, userId);
4507
4508                // Check for cross profile results.
4509                xpResolveInfo = queryCrossProfileIntents(
4510                        matchingFilters, intent, resolvedType, flags, userId);
4511                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4512                    result.add(xpResolveInfo);
4513                    Collections.sort(result, mResolvePrioritySorter);
4514                }
4515                result = filterIfNotPrimaryUser(result, userId);
4516                if (hasWebURI(intent)) {
4517                    CrossProfileDomainInfo xpDomainInfo = null;
4518                    final UserInfo parent = getProfileParent(userId);
4519                    if (parent != null) {
4520                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4521                                flags, userId, parent.id);
4522                    }
4523                    if (xpDomainInfo != null) {
4524                        if (xpResolveInfo != null) {
4525                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4526                            // in the result.
4527                            result.remove(xpResolveInfo);
4528                        }
4529                        if (result.size() == 0) {
4530                            result.add(xpDomainInfo.resolveInfo);
4531                            return result;
4532                        }
4533                    } else if (result.size() <= 1) {
4534                        return result;
4535                    }
4536                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4537                            xpDomainInfo, userId);
4538                    Collections.sort(result, mResolvePrioritySorter);
4539                }
4540                return result;
4541            }
4542            final PackageParser.Package pkg = mPackages.get(pkgName);
4543            if (pkg != null) {
4544                return filterIfNotPrimaryUser(
4545                        mActivities.queryIntentForPackage(
4546                                intent, resolvedType, flags, pkg.activities, userId),
4547                        userId);
4548            }
4549            return new ArrayList<ResolveInfo>();
4550        }
4551    }
4552
4553    private static class CrossProfileDomainInfo {
4554        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4555        ResolveInfo resolveInfo;
4556        /* Best domain verification status of the activities found in the other profile */
4557        int bestDomainVerificationStatus;
4558    }
4559
4560    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4561            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4562        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4563                sourceUserId)) {
4564            return null;
4565        }
4566        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4567                resolvedType, flags, parentUserId);
4568
4569        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4570            return null;
4571        }
4572        CrossProfileDomainInfo result = null;
4573        int size = resultTargetUser.size();
4574        for (int i = 0; i < size; i++) {
4575            ResolveInfo riTargetUser = resultTargetUser.get(i);
4576            // Intent filter verification is only for filters that specify a host. So don't return
4577            // those that handle all web uris.
4578            if (riTargetUser.handleAllWebDataURI) {
4579                continue;
4580            }
4581            String packageName = riTargetUser.activityInfo.packageName;
4582            PackageSetting ps = mSettings.mPackages.get(packageName);
4583            if (ps == null) {
4584                continue;
4585            }
4586            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4587            int status = (int)(verificationState >> 32);
4588            if (result == null) {
4589                result = new CrossProfileDomainInfo();
4590                result.resolveInfo =
4591                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4592                result.bestDomainVerificationStatus = status;
4593            } else {
4594                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4595                        result.bestDomainVerificationStatus);
4596            }
4597        }
4598        // Don't consider matches with status NEVER across profiles.
4599        if (result != null && result.bestDomainVerificationStatus
4600                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4601            return null;
4602        }
4603        return result;
4604    }
4605
4606    /**
4607     * Verification statuses are ordered from the worse to the best, except for
4608     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4609     */
4610    private int bestDomainVerificationStatus(int status1, int status2) {
4611        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4612            return status2;
4613        }
4614        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4615            return status1;
4616        }
4617        return (int) MathUtils.max(status1, status2);
4618    }
4619
4620    private boolean isUserEnabled(int userId) {
4621        long callingId = Binder.clearCallingIdentity();
4622        try {
4623            UserInfo userInfo = sUserManager.getUserInfo(userId);
4624            return userInfo != null && userInfo.isEnabled();
4625        } finally {
4626            Binder.restoreCallingIdentity(callingId);
4627        }
4628    }
4629
4630    /**
4631     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4632     *
4633     * @return filtered list
4634     */
4635    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4636        if (userId == UserHandle.USER_OWNER) {
4637            return resolveInfos;
4638        }
4639        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4640            ResolveInfo info = resolveInfos.get(i);
4641            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4642                resolveInfos.remove(i);
4643            }
4644        }
4645        return resolveInfos;
4646    }
4647
4648    private static boolean hasWebURI(Intent intent) {
4649        if (intent.getData() == null) {
4650            return false;
4651        }
4652        final String scheme = intent.getScheme();
4653        if (TextUtils.isEmpty(scheme)) {
4654            return false;
4655        }
4656        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4657    }
4658
4659    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4660            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4661            int userId) {
4662        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4663
4664        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4665            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4666                    candidates.size());
4667        }
4668
4669        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4670        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4671        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4672        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4673        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4674
4675        synchronized (mPackages) {
4676            final int count = candidates.size();
4677            // First, try to use linked apps. Partition the candidates into four lists:
4678            // one for the final results, one for the "do not use ever", one for "undefined status"
4679            // and finally one for "browser app type".
4680            for (int n=0; n<count; n++) {
4681                ResolveInfo info = candidates.get(n);
4682                String packageName = info.activityInfo.packageName;
4683                PackageSetting ps = mSettings.mPackages.get(packageName);
4684                if (ps != null) {
4685                    // Add to the special match all list (Browser use case)
4686                    if (info.handleAllWebDataURI) {
4687                        matchAllList.add(info);
4688                        continue;
4689                    }
4690                    // Try to get the status from User settings first
4691                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4692                    int status = (int)(packedStatus >> 32);
4693                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4694                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4695                        if (DEBUG_DOMAIN_VERIFICATION) {
4696                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4697                                    + " : linkgen=" + linkGeneration);
4698                        }
4699                        // Use link-enabled generation as preferredOrder, i.e.
4700                        // prefer newly-enabled over earlier-enabled.
4701                        info.preferredOrder = linkGeneration;
4702                        alwaysList.add(info);
4703                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4704                        if (DEBUG_DOMAIN_VERIFICATION) {
4705                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4706                        }
4707                        neverList.add(info);
4708                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4709                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4710                        if (DEBUG_DOMAIN_VERIFICATION) {
4711                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4712                        }
4713                        undefinedList.add(info);
4714                    }
4715                }
4716            }
4717            // First try to add the "always" resolution(s) for the current user, if any
4718            if (alwaysList.size() > 0) {
4719                result.addAll(alwaysList);
4720            // if there is an "always" for the parent user, add it.
4721            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4722                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4723                result.add(xpDomainInfo.resolveInfo);
4724            } else {
4725                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4726                result.addAll(undefinedList);
4727                if (xpDomainInfo != null && (
4728                        xpDomainInfo.bestDomainVerificationStatus
4729                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4730                        || xpDomainInfo.bestDomainVerificationStatus
4731                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4732                    result.add(xpDomainInfo.resolveInfo);
4733                }
4734                // Also add Browsers (all of them or only the default one)
4735                if ((matchFlags & MATCH_ALL) != 0) {
4736                    result.addAll(matchAllList);
4737                } else {
4738                    // Browser/generic handling case.  If there's a default browser, go straight
4739                    // to that (but only if there is no other higher-priority match).
4740                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4741                    int maxMatchPrio = 0;
4742                    ResolveInfo defaultBrowserMatch = null;
4743                    final int numCandidates = matchAllList.size();
4744                    for (int n = 0; n < numCandidates; n++) {
4745                        ResolveInfo info = matchAllList.get(n);
4746                        // track the highest overall match priority...
4747                        if (info.priority > maxMatchPrio) {
4748                            maxMatchPrio = info.priority;
4749                        }
4750                        // ...and the highest-priority default browser match
4751                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4752                            if (defaultBrowserMatch == null
4753                                    || (defaultBrowserMatch.priority < info.priority)) {
4754                                if (debug) {
4755                                    Slog.v(TAG, "Considering default browser match " + info);
4756                                }
4757                                defaultBrowserMatch = info;
4758                            }
4759                        }
4760                    }
4761                    if (defaultBrowserMatch != null
4762                            && defaultBrowserMatch.priority >= maxMatchPrio
4763                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4764                    {
4765                        if (debug) {
4766                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4767                        }
4768                        result.add(defaultBrowserMatch);
4769                    } else {
4770                        result.addAll(matchAllList);
4771                    }
4772                }
4773
4774                // If there is nothing selected, add all candidates and remove the ones that the user
4775                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4776                if (result.size() == 0) {
4777                    result.addAll(candidates);
4778                    result.removeAll(neverList);
4779                }
4780            }
4781        }
4782        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4783            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4784                    result.size());
4785            for (ResolveInfo info : result) {
4786                Slog.v(TAG, "  + " + info.activityInfo);
4787            }
4788        }
4789        return result;
4790    }
4791
4792    // Returns a packed value as a long:
4793    //
4794    // high 'int'-sized word: link status: undefined/ask/never/always.
4795    // low 'int'-sized word: relative priority among 'always' results.
4796    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4797        long result = ps.getDomainVerificationStatusForUser(userId);
4798        // if none available, get the master status
4799        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4800            if (ps.getIntentFilterVerificationInfo() != null) {
4801                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4802            }
4803        }
4804        return result;
4805    }
4806
4807    private ResolveInfo querySkipCurrentProfileIntents(
4808            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4809            int flags, int sourceUserId) {
4810        if (matchingFilters != null) {
4811            int size = matchingFilters.size();
4812            for (int i = 0; i < size; i ++) {
4813                CrossProfileIntentFilter filter = matchingFilters.get(i);
4814                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4815                    // Checking if there are activities in the target user that can handle the
4816                    // intent.
4817                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4818                            flags, sourceUserId);
4819                    if (resolveInfo != null) {
4820                        return resolveInfo;
4821                    }
4822                }
4823            }
4824        }
4825        return null;
4826    }
4827
4828    // Return matching ResolveInfo if any for skip current profile intent filters.
4829    private ResolveInfo queryCrossProfileIntents(
4830            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4831            int flags, int sourceUserId) {
4832        if (matchingFilters != null) {
4833            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4834            // match the same intent. For performance reasons, it is better not to
4835            // run queryIntent twice for the same userId
4836            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4837            int size = matchingFilters.size();
4838            for (int i = 0; i < size; i++) {
4839                CrossProfileIntentFilter filter = matchingFilters.get(i);
4840                int targetUserId = filter.getTargetUserId();
4841                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4842                        && !alreadyTriedUserIds.get(targetUserId)) {
4843                    // Checking if there are activities in the target user that can handle the
4844                    // intent.
4845                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4846                            flags, sourceUserId);
4847                    if (resolveInfo != null) return resolveInfo;
4848                    alreadyTriedUserIds.put(targetUserId, true);
4849                }
4850            }
4851        }
4852        return null;
4853    }
4854
4855    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4856            String resolvedType, int flags, int sourceUserId) {
4857        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4858                resolvedType, flags, filter.getTargetUserId());
4859        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4860            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4861        }
4862        return null;
4863    }
4864
4865    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4866            int sourceUserId, int targetUserId) {
4867        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4868        String className;
4869        if (targetUserId == UserHandle.USER_OWNER) {
4870            className = FORWARD_INTENT_TO_USER_OWNER;
4871        } else {
4872            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4873        }
4874        ComponentName forwardingActivityComponentName = new ComponentName(
4875                mAndroidApplication.packageName, className);
4876        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4877                sourceUserId);
4878        if (targetUserId == UserHandle.USER_OWNER) {
4879            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4880            forwardingResolveInfo.noResourceId = true;
4881        }
4882        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4883        forwardingResolveInfo.priority = 0;
4884        forwardingResolveInfo.preferredOrder = 0;
4885        forwardingResolveInfo.match = 0;
4886        forwardingResolveInfo.isDefault = true;
4887        forwardingResolveInfo.filter = filter;
4888        forwardingResolveInfo.targetUserId = targetUserId;
4889        return forwardingResolveInfo;
4890    }
4891
4892    @Override
4893    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4894            Intent[] specifics, String[] specificTypes, Intent intent,
4895            String resolvedType, int flags, int userId) {
4896        if (!sUserManager.exists(userId)) return Collections.emptyList();
4897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4898                false, "query intent activity options");
4899        final String resultsAction = intent.getAction();
4900
4901        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4902                | PackageManager.GET_RESOLVED_FILTER, userId);
4903
4904        if (DEBUG_INTENT_MATCHING) {
4905            Log.v(TAG, "Query " + intent + ": " + results);
4906        }
4907
4908        int specificsPos = 0;
4909        int N;
4910
4911        // todo: note that the algorithm used here is O(N^2).  This
4912        // isn't a problem in our current environment, but if we start running
4913        // into situations where we have more than 5 or 10 matches then this
4914        // should probably be changed to something smarter...
4915
4916        // First we go through and resolve each of the specific items
4917        // that were supplied, taking care of removing any corresponding
4918        // duplicate items in the generic resolve list.
4919        if (specifics != null) {
4920            for (int i=0; i<specifics.length; i++) {
4921                final Intent sintent = specifics[i];
4922                if (sintent == null) {
4923                    continue;
4924                }
4925
4926                if (DEBUG_INTENT_MATCHING) {
4927                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4928                }
4929
4930                String action = sintent.getAction();
4931                if (resultsAction != null && resultsAction.equals(action)) {
4932                    // If this action was explicitly requested, then don't
4933                    // remove things that have it.
4934                    action = null;
4935                }
4936
4937                ResolveInfo ri = null;
4938                ActivityInfo ai = null;
4939
4940                ComponentName comp = sintent.getComponent();
4941                if (comp == null) {
4942                    ri = resolveIntent(
4943                        sintent,
4944                        specificTypes != null ? specificTypes[i] : null,
4945                            flags, userId);
4946                    if (ri == null) {
4947                        continue;
4948                    }
4949                    if (ri == mResolveInfo) {
4950                        // ACK!  Must do something better with this.
4951                    }
4952                    ai = ri.activityInfo;
4953                    comp = new ComponentName(ai.applicationInfo.packageName,
4954                            ai.name);
4955                } else {
4956                    ai = getActivityInfo(comp, flags, userId);
4957                    if (ai == null) {
4958                        continue;
4959                    }
4960                }
4961
4962                // Look for any generic query activities that are duplicates
4963                // of this specific one, and remove them from the results.
4964                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4965                N = results.size();
4966                int j;
4967                for (j=specificsPos; j<N; j++) {
4968                    ResolveInfo sri = results.get(j);
4969                    if ((sri.activityInfo.name.equals(comp.getClassName())
4970                            && sri.activityInfo.applicationInfo.packageName.equals(
4971                                    comp.getPackageName()))
4972                        || (action != null && sri.filter.matchAction(action))) {
4973                        results.remove(j);
4974                        if (DEBUG_INTENT_MATCHING) Log.v(
4975                            TAG, "Removing duplicate item from " + j
4976                            + " due to specific " + specificsPos);
4977                        if (ri == null) {
4978                            ri = sri;
4979                        }
4980                        j--;
4981                        N--;
4982                    }
4983                }
4984
4985                // Add this specific item to its proper place.
4986                if (ri == null) {
4987                    ri = new ResolveInfo();
4988                    ri.activityInfo = ai;
4989                }
4990                results.add(specificsPos, ri);
4991                ri.specificIndex = i;
4992                specificsPos++;
4993            }
4994        }
4995
4996        // Now we go through the remaining generic results and remove any
4997        // duplicate actions that are found here.
4998        N = results.size();
4999        for (int i=specificsPos; i<N-1; i++) {
5000            final ResolveInfo rii = results.get(i);
5001            if (rii.filter == null) {
5002                continue;
5003            }
5004
5005            // Iterate over all of the actions of this result's intent
5006            // filter...  typically this should be just one.
5007            final Iterator<String> it = rii.filter.actionsIterator();
5008            if (it == null) {
5009                continue;
5010            }
5011            while (it.hasNext()) {
5012                final String action = it.next();
5013                if (resultsAction != null && resultsAction.equals(action)) {
5014                    // If this action was explicitly requested, then don't
5015                    // remove things that have it.
5016                    continue;
5017                }
5018                for (int j=i+1; j<N; j++) {
5019                    final ResolveInfo rij = results.get(j);
5020                    if (rij.filter != null && rij.filter.hasAction(action)) {
5021                        results.remove(j);
5022                        if (DEBUG_INTENT_MATCHING) Log.v(
5023                            TAG, "Removing duplicate item from " + j
5024                            + " due to action " + action + " at " + i);
5025                        j--;
5026                        N--;
5027                    }
5028                }
5029            }
5030
5031            // If the caller didn't request filter information, drop it now
5032            // so we don't have to marshall/unmarshall it.
5033            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5034                rii.filter = null;
5035            }
5036        }
5037
5038        // Filter out the caller activity if so requested.
5039        if (caller != null) {
5040            N = results.size();
5041            for (int i=0; i<N; i++) {
5042                ActivityInfo ainfo = results.get(i).activityInfo;
5043                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5044                        && caller.getClassName().equals(ainfo.name)) {
5045                    results.remove(i);
5046                    break;
5047                }
5048            }
5049        }
5050
5051        // If the caller didn't request filter information,
5052        // drop them now so we don't have to
5053        // marshall/unmarshall it.
5054        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5055            N = results.size();
5056            for (int i=0; i<N; i++) {
5057                results.get(i).filter = null;
5058            }
5059        }
5060
5061        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5062        return results;
5063    }
5064
5065    @Override
5066    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5067            int userId) {
5068        if (!sUserManager.exists(userId)) return Collections.emptyList();
5069        ComponentName comp = intent.getComponent();
5070        if (comp == null) {
5071            if (intent.getSelector() != null) {
5072                intent = intent.getSelector();
5073                comp = intent.getComponent();
5074            }
5075        }
5076        if (comp != null) {
5077            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5078            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5079            if (ai != null) {
5080                ResolveInfo ri = new ResolveInfo();
5081                ri.activityInfo = ai;
5082                list.add(ri);
5083            }
5084            return list;
5085        }
5086
5087        // reader
5088        synchronized (mPackages) {
5089            String pkgName = intent.getPackage();
5090            if (pkgName == null) {
5091                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5092            }
5093            final PackageParser.Package pkg = mPackages.get(pkgName);
5094            if (pkg != null) {
5095                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5096                        userId);
5097            }
5098            return null;
5099        }
5100    }
5101
5102    @Override
5103    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5104        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5105        if (!sUserManager.exists(userId)) return null;
5106        if (query != null) {
5107            if (query.size() >= 1) {
5108                // If there is more than one service with the same priority,
5109                // just arbitrarily pick the first one.
5110                return query.get(0);
5111            }
5112        }
5113        return null;
5114    }
5115
5116    @Override
5117    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5118            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 ServiceInfo si = getServiceInfo(comp, flags, userId);
5130            if (si != null) {
5131                final ResolveInfo ri = new ResolveInfo();
5132                ri.serviceInfo = si;
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 mServices.queryIntent(intent, resolvedType, flags, userId);
5143            }
5144            final PackageParser.Package pkg = mPackages.get(pkgName);
5145            if (pkg != null) {
5146                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5147                        userId);
5148            }
5149            return null;
5150        }
5151    }
5152
5153    @Override
5154    public List<ResolveInfo> queryIntentContentProviders(
5155            Intent intent, String resolvedType, int flags, int userId) {
5156        if (!sUserManager.exists(userId)) return Collections.emptyList();
5157        ComponentName comp = intent.getComponent();
5158        if (comp == null) {
5159            if (intent.getSelector() != null) {
5160                intent = intent.getSelector();
5161                comp = intent.getComponent();
5162            }
5163        }
5164        if (comp != null) {
5165            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5166            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5167            if (pi != null) {
5168                final ResolveInfo ri = new ResolveInfo();
5169                ri.providerInfo = pi;
5170                list.add(ri);
5171            }
5172            return list;
5173        }
5174
5175        // reader
5176        synchronized (mPackages) {
5177            String pkgName = intent.getPackage();
5178            if (pkgName == null) {
5179                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5180            }
5181            final PackageParser.Package pkg = mPackages.get(pkgName);
5182            if (pkg != null) {
5183                return mProviders.queryIntentForPackage(
5184                        intent, resolvedType, flags, pkg.providers, userId);
5185            }
5186            return null;
5187        }
5188    }
5189
5190    @Override
5191    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5192        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5193
5194        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5195
5196        // writer
5197        synchronized (mPackages) {
5198            ArrayList<PackageInfo> list;
5199            if (listUninstalled) {
5200                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5201                for (PackageSetting ps : mSettings.mPackages.values()) {
5202                    PackageInfo pi;
5203                    if (ps.pkg != null) {
5204                        pi = generatePackageInfo(ps.pkg, flags, userId);
5205                    } else {
5206                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5207                    }
5208                    if (pi != null) {
5209                        list.add(pi);
5210                    }
5211                }
5212            } else {
5213                list = new ArrayList<PackageInfo>(mPackages.size());
5214                for (PackageParser.Package p : mPackages.values()) {
5215                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5216                    if (pi != null) {
5217                        list.add(pi);
5218                    }
5219                }
5220            }
5221
5222            return new ParceledListSlice<PackageInfo>(list);
5223        }
5224    }
5225
5226    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5227            String[] permissions, boolean[] tmp, int flags, int userId) {
5228        int numMatch = 0;
5229        final PermissionsState permissionsState = ps.getPermissionsState();
5230        for (int i=0; i<permissions.length; i++) {
5231            final String permission = permissions[i];
5232            if (permissionsState.hasPermission(permission, userId)) {
5233                tmp[i] = true;
5234                numMatch++;
5235            } else {
5236                tmp[i] = false;
5237            }
5238        }
5239        if (numMatch == 0) {
5240            return;
5241        }
5242        PackageInfo pi;
5243        if (ps.pkg != null) {
5244            pi = generatePackageInfo(ps.pkg, flags, userId);
5245        } else {
5246            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5247        }
5248        // The above might return null in cases of uninstalled apps or install-state
5249        // skew across users/profiles.
5250        if (pi != null) {
5251            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5252                if (numMatch == permissions.length) {
5253                    pi.requestedPermissions = permissions;
5254                } else {
5255                    pi.requestedPermissions = new String[numMatch];
5256                    numMatch = 0;
5257                    for (int i=0; i<permissions.length; i++) {
5258                        if (tmp[i]) {
5259                            pi.requestedPermissions[numMatch] = permissions[i];
5260                            numMatch++;
5261                        }
5262                    }
5263                }
5264            }
5265            list.add(pi);
5266        }
5267    }
5268
5269    @Override
5270    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5271            String[] permissions, int flags, int userId) {
5272        if (!sUserManager.exists(userId)) return null;
5273        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5274
5275        // writer
5276        synchronized (mPackages) {
5277            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5278            boolean[] tmpBools = new boolean[permissions.length];
5279            if (listUninstalled) {
5280                for (PackageSetting ps : mSettings.mPackages.values()) {
5281                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5282                }
5283            } else {
5284                for (PackageParser.Package pkg : mPackages.values()) {
5285                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5286                    if (ps != null) {
5287                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5288                                userId);
5289                    }
5290                }
5291            }
5292
5293            return new ParceledListSlice<PackageInfo>(list);
5294        }
5295    }
5296
5297    @Override
5298    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5299        if (!sUserManager.exists(userId)) return null;
5300        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5301
5302        // writer
5303        synchronized (mPackages) {
5304            ArrayList<ApplicationInfo> list;
5305            if (listUninstalled) {
5306                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5307                for (PackageSetting ps : mSettings.mPackages.values()) {
5308                    ApplicationInfo ai;
5309                    if (ps.pkg != null) {
5310                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5311                                ps.readUserState(userId), userId);
5312                    } else {
5313                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5314                    }
5315                    if (ai != null) {
5316                        list.add(ai);
5317                    }
5318                }
5319            } else {
5320                list = new ArrayList<ApplicationInfo>(mPackages.size());
5321                for (PackageParser.Package p : mPackages.values()) {
5322                    if (p.mExtras != null) {
5323                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5324                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5325                        if (ai != null) {
5326                            list.add(ai);
5327                        }
5328                    }
5329                }
5330            }
5331
5332            return new ParceledListSlice<ApplicationInfo>(list);
5333        }
5334    }
5335
5336    public List<ApplicationInfo> getPersistentApplications(int flags) {
5337        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5338
5339        // reader
5340        synchronized (mPackages) {
5341            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5342            final int userId = UserHandle.getCallingUserId();
5343            while (i.hasNext()) {
5344                final PackageParser.Package p = i.next();
5345                if (p.applicationInfo != null
5346                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5347                        && (!mSafeMode || isSystemApp(p))) {
5348                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5349                    if (ps != null) {
5350                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5351                                ps.readUserState(userId), userId);
5352                        if (ai != null) {
5353                            finalList.add(ai);
5354                        }
5355                    }
5356                }
5357            }
5358        }
5359
5360        return finalList;
5361    }
5362
5363    @Override
5364    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5365        if (!sUserManager.exists(userId)) return null;
5366        // reader
5367        synchronized (mPackages) {
5368            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5369            PackageSetting ps = provider != null
5370                    ? mSettings.mPackages.get(provider.owner.packageName)
5371                    : null;
5372            return ps != null
5373                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5374                    && (!mSafeMode || (provider.info.applicationInfo.flags
5375                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5376                    ? PackageParser.generateProviderInfo(provider, flags,
5377                            ps.readUserState(userId), userId)
5378                    : null;
5379        }
5380    }
5381
5382    /**
5383     * @deprecated
5384     */
5385    @Deprecated
5386    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5387        // reader
5388        synchronized (mPackages) {
5389            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5390                    .entrySet().iterator();
5391            final int userId = UserHandle.getCallingUserId();
5392            while (i.hasNext()) {
5393                Map.Entry<String, PackageParser.Provider> entry = i.next();
5394                PackageParser.Provider p = entry.getValue();
5395                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5396
5397                if (ps != null && p.syncable
5398                        && (!mSafeMode || (p.info.applicationInfo.flags
5399                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5400                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5401                            ps.readUserState(userId), userId);
5402                    if (info != null) {
5403                        outNames.add(entry.getKey());
5404                        outInfo.add(info);
5405                    }
5406                }
5407            }
5408        }
5409    }
5410
5411    @Override
5412    public List<ProviderInfo> queryContentProviders(String processName,
5413            int uid, int flags) {
5414        ArrayList<ProviderInfo> finalList = null;
5415        // reader
5416        synchronized (mPackages) {
5417            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5418            final int userId = processName != null ?
5419                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5420            while (i.hasNext()) {
5421                final PackageParser.Provider p = i.next();
5422                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5423                if (ps != null && p.info.authority != null
5424                        && (processName == null
5425                                || (p.info.processName.equals(processName)
5426                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5427                        && mSettings.isEnabledLPr(p.info, flags, userId)
5428                        && (!mSafeMode
5429                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5430                    if (finalList == null) {
5431                        finalList = new ArrayList<ProviderInfo>(3);
5432                    }
5433                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5434                            ps.readUserState(userId), userId);
5435                    if (info != null) {
5436                        finalList.add(info);
5437                    }
5438                }
5439            }
5440        }
5441
5442        if (finalList != null) {
5443            Collections.sort(finalList, mProviderInitOrderSorter);
5444        }
5445
5446        return finalList;
5447    }
5448
5449    @Override
5450    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5451            int flags) {
5452        // reader
5453        synchronized (mPackages) {
5454            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5455            return PackageParser.generateInstrumentationInfo(i, flags);
5456        }
5457    }
5458
5459    @Override
5460    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5461            int flags) {
5462        ArrayList<InstrumentationInfo> finalList =
5463            new ArrayList<InstrumentationInfo>();
5464
5465        // reader
5466        synchronized (mPackages) {
5467            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5468            while (i.hasNext()) {
5469                final PackageParser.Instrumentation p = i.next();
5470                if (targetPackage == null
5471                        || targetPackage.equals(p.info.targetPackage)) {
5472                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5473                            flags);
5474                    if (ii != null) {
5475                        finalList.add(ii);
5476                    }
5477                }
5478            }
5479        }
5480
5481        return finalList;
5482    }
5483
5484    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5485        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5486        if (overlays == null) {
5487            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5488            return;
5489        }
5490        for (PackageParser.Package opkg : overlays.values()) {
5491            // Not much to do if idmap fails: we already logged the error
5492            // and we certainly don't want to abort installation of pkg simply
5493            // because an overlay didn't fit properly. For these reasons,
5494            // ignore the return value of createIdmapForPackagePairLI.
5495            createIdmapForPackagePairLI(pkg, opkg);
5496        }
5497    }
5498
5499    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5500            PackageParser.Package opkg) {
5501        if (!opkg.mTrustedOverlay) {
5502            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5503                    opkg.baseCodePath + ": overlay not trusted");
5504            return false;
5505        }
5506        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5507        if (overlaySet == null) {
5508            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5509                    opkg.baseCodePath + " but target package has no known overlays");
5510            return false;
5511        }
5512        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5513        // TODO: generate idmap for split APKs
5514        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5515            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5516                    + opkg.baseCodePath);
5517            return false;
5518        }
5519        PackageParser.Package[] overlayArray =
5520            overlaySet.values().toArray(new PackageParser.Package[0]);
5521        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5522            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5523                return p1.mOverlayPriority - p2.mOverlayPriority;
5524            }
5525        };
5526        Arrays.sort(overlayArray, cmp);
5527
5528        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5529        int i = 0;
5530        for (PackageParser.Package p : overlayArray) {
5531            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5532        }
5533        return true;
5534    }
5535
5536    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5537        final File[] files = dir.listFiles();
5538        if (ArrayUtils.isEmpty(files)) {
5539            Log.d(TAG, "No files in app dir " + dir);
5540            return;
5541        }
5542
5543        if (DEBUG_PACKAGE_SCANNING) {
5544            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5545                    + " flags=0x" + Integer.toHexString(parseFlags));
5546        }
5547
5548        for (File file : files) {
5549            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5550                    && !PackageInstallerService.isStageName(file.getName());
5551            if (!isPackage) {
5552                // Ignore entries which are not packages
5553                continue;
5554            }
5555            try {
5556                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5557                        scanFlags, currentTime, null);
5558            } catch (PackageManagerException e) {
5559                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5560
5561                // Delete invalid userdata apps
5562                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5563                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5564                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5565                    if (file.isDirectory()) {
5566                        mInstaller.rmPackageDir(file.getAbsolutePath());
5567                    } else {
5568                        file.delete();
5569                    }
5570                }
5571            }
5572        }
5573    }
5574
5575    private static File getSettingsProblemFile() {
5576        File dataDir = Environment.getDataDirectory();
5577        File systemDir = new File(dataDir, "system");
5578        File fname = new File(systemDir, "uiderrors.txt");
5579        return fname;
5580    }
5581
5582    static void reportSettingsProblem(int priority, String msg) {
5583        logCriticalInfo(priority, msg);
5584    }
5585
5586    static void logCriticalInfo(int priority, String msg) {
5587        Slog.println(priority, TAG, msg);
5588        EventLogTags.writePmCriticalInfo(msg);
5589        try {
5590            File fname = getSettingsProblemFile();
5591            FileOutputStream out = new FileOutputStream(fname, true);
5592            PrintWriter pw = new FastPrintWriter(out);
5593            SimpleDateFormat formatter = new SimpleDateFormat();
5594            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5595            pw.println(dateString + ": " + msg);
5596            pw.close();
5597            FileUtils.setPermissions(
5598                    fname.toString(),
5599                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5600                    -1, -1);
5601        } catch (java.io.IOException e) {
5602        }
5603    }
5604
5605    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5606            PackageParser.Package pkg, File srcFile, int parseFlags)
5607            throws PackageManagerException {
5608        if (ps != null
5609                && ps.codePath.equals(srcFile)
5610                && ps.timeStamp == srcFile.lastModified()
5611                && !isCompatSignatureUpdateNeeded(pkg)
5612                && !isRecoverSignatureUpdateNeeded(pkg)) {
5613            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5614            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5615            ArraySet<PublicKey> signingKs;
5616            synchronized (mPackages) {
5617                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5618            }
5619            if (ps.signatures.mSignatures != null
5620                    && ps.signatures.mSignatures.length != 0
5621                    && signingKs != null) {
5622                // Optimization: reuse the existing cached certificates
5623                // if the package appears to be unchanged.
5624                pkg.mSignatures = ps.signatures.mSignatures;
5625                pkg.mSigningKeys = signingKs;
5626                return;
5627            }
5628
5629            Slog.w(TAG, "PackageSetting for " + ps.name
5630                    + " is missing signatures.  Collecting certs again to recover them.");
5631        } else {
5632            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5633        }
5634
5635        try {
5636            pp.collectCertificates(pkg, parseFlags);
5637            pp.collectManifestDigest(pkg);
5638        } catch (PackageParserException e) {
5639            throw PackageManagerException.from(e);
5640        }
5641    }
5642
5643    /*
5644     *  Scan a package and return the newly parsed package.
5645     *  Returns null in case of errors and the error code is stored in mLastScanError
5646     */
5647    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5648            long currentTime, UserHandle user) throws PackageManagerException {
5649        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5650        parseFlags |= mDefParseFlags;
5651        PackageParser pp = new PackageParser();
5652        pp.setSeparateProcesses(mSeparateProcesses);
5653        pp.setOnlyCoreApps(mOnlyCore);
5654        pp.setDisplayMetrics(mMetrics);
5655
5656        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5657            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5658        }
5659
5660        final PackageParser.Package pkg;
5661        try {
5662            pkg = pp.parsePackage(scanFile, parseFlags);
5663        } catch (PackageParserException e) {
5664            throw PackageManagerException.from(e);
5665        }
5666
5667        PackageSetting ps = null;
5668        PackageSetting updatedPkg;
5669        // reader
5670        synchronized (mPackages) {
5671            // Look to see if we already know about this package.
5672            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5673            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5674                // This package has been renamed to its original name.  Let's
5675                // use that.
5676                ps = mSettings.peekPackageLPr(oldName);
5677            }
5678            // If there was no original package, see one for the real package name.
5679            if (ps == null) {
5680                ps = mSettings.peekPackageLPr(pkg.packageName);
5681            }
5682            // Check to see if this package could be hiding/updating a system
5683            // package.  Must look for it either under the original or real
5684            // package name depending on our state.
5685            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5686            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5687        }
5688        boolean updatedPkgBetter = false;
5689        // First check if this is a system package that may involve an update
5690        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5691            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5692            // it needs to drop FLAG_PRIVILEGED.
5693            if (locationIsPrivileged(scanFile)) {
5694                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5695            } else {
5696                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5697            }
5698
5699            if (ps != null && !ps.codePath.equals(scanFile)) {
5700                // The path has changed from what was last scanned...  check the
5701                // version of the new path against what we have stored to determine
5702                // what to do.
5703                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5704                if (pkg.mVersionCode <= ps.versionCode) {
5705                    // The system package has been updated and the code path does not match
5706                    // Ignore entry. Skip it.
5707                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5708                            + " ignored: updated version " + ps.versionCode
5709                            + " better than this " + pkg.mVersionCode);
5710                    if (!updatedPkg.codePath.equals(scanFile)) {
5711                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5712                                + ps.name + " changing from " + updatedPkg.codePathString
5713                                + " to " + scanFile);
5714                        updatedPkg.codePath = scanFile;
5715                        updatedPkg.codePathString = scanFile.toString();
5716                        updatedPkg.resourcePath = scanFile;
5717                        updatedPkg.resourcePathString = scanFile.toString();
5718                    }
5719                    updatedPkg.pkg = pkg;
5720                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5721                            "Package " + ps.name + " at " + scanFile
5722                                    + " ignored: updated version " + ps.versionCode
5723                                    + " better than this " + pkg.mVersionCode);
5724                } else {
5725                    // The current app on the system partition is better than
5726                    // what we have updated to on the data partition; switch
5727                    // back to the system partition version.
5728                    // At this point, its safely assumed that package installation for
5729                    // apps in system partition will go through. If not there won't be a working
5730                    // version of the app
5731                    // writer
5732                    synchronized (mPackages) {
5733                        // Just remove the loaded entries from package lists.
5734                        mPackages.remove(ps.name);
5735                    }
5736
5737                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5738                            + " reverting from " + ps.codePathString
5739                            + ": new version " + pkg.mVersionCode
5740                            + " better than installed " + ps.versionCode);
5741
5742                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5743                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5744                    synchronized (mInstallLock) {
5745                        args.cleanUpResourcesLI();
5746                    }
5747                    synchronized (mPackages) {
5748                        mSettings.enableSystemPackageLPw(ps.name);
5749                    }
5750                    updatedPkgBetter = true;
5751                }
5752            }
5753        }
5754
5755        if (updatedPkg != null) {
5756            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5757            // initially
5758            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5759
5760            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5761            // flag set initially
5762            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5763                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5764            }
5765        }
5766
5767        // Verify certificates against what was last scanned
5768        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5769
5770        /*
5771         * A new system app appeared, but we already had a non-system one of the
5772         * same name installed earlier.
5773         */
5774        boolean shouldHideSystemApp = false;
5775        if (updatedPkg == null && ps != null
5776                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5777            /*
5778             * Check to make sure the signatures match first. If they don't,
5779             * wipe the installed application and its data.
5780             */
5781            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5782                    != PackageManager.SIGNATURE_MATCH) {
5783                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5784                        + " signatures don't match existing userdata copy; removing");
5785                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5786                ps = null;
5787            } else {
5788                /*
5789                 * If the newly-added system app is an older version than the
5790                 * already installed version, hide it. It will be scanned later
5791                 * and re-added like an update.
5792                 */
5793                if (pkg.mVersionCode <= ps.versionCode) {
5794                    shouldHideSystemApp = true;
5795                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5796                            + " but new version " + pkg.mVersionCode + " better than installed "
5797                            + ps.versionCode + "; hiding system");
5798                } else {
5799                    /*
5800                     * The newly found system app is a newer version that the
5801                     * one previously installed. Simply remove the
5802                     * already-installed application and replace it with our own
5803                     * while keeping the application data.
5804                     */
5805                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5806                            + " reverting from " + ps.codePathString + ": new version "
5807                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5808                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5809                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5810                    synchronized (mInstallLock) {
5811                        args.cleanUpResourcesLI();
5812                    }
5813                }
5814            }
5815        }
5816
5817        // The apk is forward locked (not public) if its code and resources
5818        // are kept in different files. (except for app in either system or
5819        // vendor path).
5820        // TODO grab this value from PackageSettings
5821        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5822            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5823                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5824            }
5825        }
5826
5827        // TODO: extend to support forward-locked splits
5828        String resourcePath = null;
5829        String baseResourcePath = null;
5830        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5831            if (ps != null && ps.resourcePathString != null) {
5832                resourcePath = ps.resourcePathString;
5833                baseResourcePath = ps.resourcePathString;
5834            } else {
5835                // Should not happen at all. Just log an error.
5836                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5837            }
5838        } else {
5839            resourcePath = pkg.codePath;
5840            baseResourcePath = pkg.baseCodePath;
5841        }
5842
5843        // Set application objects path explicitly.
5844        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5845        pkg.applicationInfo.setCodePath(pkg.codePath);
5846        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5847        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5848        pkg.applicationInfo.setResourcePath(resourcePath);
5849        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5850        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5851
5852        // Note that we invoke the following method only if we are about to unpack an application
5853        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5854                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5855
5856        /*
5857         * If the system app should be overridden by a previously installed
5858         * data, hide the system app now and let the /data/app scan pick it up
5859         * again.
5860         */
5861        if (shouldHideSystemApp) {
5862            synchronized (mPackages) {
5863                /*
5864                 * We have to grant systems permissions before we hide, because
5865                 * grantPermissions will assume the package update is trying to
5866                 * expand its permissions.
5867                 */
5868                grantPermissionsLPw(pkg, true, pkg.packageName);
5869                mSettings.disableSystemPackageLPw(pkg.packageName);
5870            }
5871        }
5872
5873        return scannedPkg;
5874    }
5875
5876    private static String fixProcessName(String defProcessName,
5877            String processName, int uid) {
5878        if (processName == null) {
5879            return defProcessName;
5880        }
5881        return processName;
5882    }
5883
5884    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5885            throws PackageManagerException {
5886        if (pkgSetting.signatures.mSignatures != null) {
5887            // Already existing package. Make sure signatures match
5888            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5889                    == PackageManager.SIGNATURE_MATCH;
5890            if (!match) {
5891                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5892                        == PackageManager.SIGNATURE_MATCH;
5893            }
5894            if (!match) {
5895                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5896                        == PackageManager.SIGNATURE_MATCH;
5897            }
5898            if (!match) {
5899                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5900                        + pkg.packageName + " signatures do not match the "
5901                        + "previously installed version; ignoring!");
5902            }
5903        }
5904
5905        // Check for shared user signatures
5906        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5907            // Already existing package. Make sure signatures match
5908            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5909                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5910            if (!match) {
5911                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5912                        == PackageManager.SIGNATURE_MATCH;
5913            }
5914            if (!match) {
5915                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5916                        == PackageManager.SIGNATURE_MATCH;
5917            }
5918            if (!match) {
5919                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5920                        "Package " + pkg.packageName
5921                        + " has no signatures that match those in shared user "
5922                        + pkgSetting.sharedUser.name + "; ignoring!");
5923            }
5924        }
5925    }
5926
5927    /**
5928     * Enforces that only the system UID or root's UID can call a method exposed
5929     * via Binder.
5930     *
5931     * @param message used as message if SecurityException is thrown
5932     * @throws SecurityException if the caller is not system or root
5933     */
5934    private static final void enforceSystemOrRoot(String message) {
5935        final int uid = Binder.getCallingUid();
5936        if (uid != Process.SYSTEM_UID && uid != 0) {
5937            throw new SecurityException(message);
5938        }
5939    }
5940
5941    @Override
5942    public void performBootDexOpt() {
5943        enforceSystemOrRoot("Only the system can request dexopt be performed");
5944
5945        // Before everything else, see whether we need to fstrim.
5946        try {
5947            IMountService ms = PackageHelper.getMountService();
5948            if (ms != null) {
5949                final boolean isUpgrade = isUpgrade();
5950                boolean doTrim = isUpgrade;
5951                if (doTrim) {
5952                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5953                } else {
5954                    final long interval = android.provider.Settings.Global.getLong(
5955                            mContext.getContentResolver(),
5956                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5957                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5958                    if (interval > 0) {
5959                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5960                        if (timeSinceLast > interval) {
5961                            doTrim = true;
5962                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5963                                    + "; running immediately");
5964                        }
5965                    }
5966                }
5967                if (doTrim) {
5968                    if (!isFirstBoot()) {
5969                        try {
5970                            ActivityManagerNative.getDefault().showBootMessage(
5971                                    mContext.getResources().getString(
5972                                            R.string.android_upgrading_fstrim), true);
5973                        } catch (RemoteException e) {
5974                        }
5975                    }
5976                    ms.runMaintenance();
5977                }
5978            } else {
5979                Slog.e(TAG, "Mount service unavailable!");
5980            }
5981        } catch (RemoteException e) {
5982            // Can't happen; MountService is local
5983        }
5984
5985        final ArraySet<PackageParser.Package> pkgs;
5986        synchronized (mPackages) {
5987            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5988        }
5989
5990        if (pkgs != null) {
5991            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5992            // in case the device runs out of space.
5993            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5994            // Give priority to core apps.
5995            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5996                PackageParser.Package pkg = it.next();
5997                if (pkg.coreApp) {
5998                    if (DEBUG_DEXOPT) {
5999                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6000                    }
6001                    sortedPkgs.add(pkg);
6002                    it.remove();
6003                }
6004            }
6005            // Give priority to system apps that listen for pre boot complete.
6006            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6007            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6008            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6009                PackageParser.Package pkg = it.next();
6010                if (pkgNames.contains(pkg.packageName)) {
6011                    if (DEBUG_DEXOPT) {
6012                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6013                    }
6014                    sortedPkgs.add(pkg);
6015                    it.remove();
6016                }
6017            }
6018            // Give priority to system apps.
6019            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6020                PackageParser.Package pkg = it.next();
6021                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6022                    if (DEBUG_DEXOPT) {
6023                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6024                    }
6025                    sortedPkgs.add(pkg);
6026                    it.remove();
6027                }
6028            }
6029            // Give priority to updated system apps.
6030            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6031                PackageParser.Package pkg = it.next();
6032                if (pkg.isUpdatedSystemApp()) {
6033                    if (DEBUG_DEXOPT) {
6034                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6035                    }
6036                    sortedPkgs.add(pkg);
6037                    it.remove();
6038                }
6039            }
6040            // Give priority to apps that listen for boot complete.
6041            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6042            pkgNames = getPackageNamesForIntent(intent);
6043            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6044                PackageParser.Package pkg = it.next();
6045                if (pkgNames.contains(pkg.packageName)) {
6046                    if (DEBUG_DEXOPT) {
6047                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6048                    }
6049                    sortedPkgs.add(pkg);
6050                    it.remove();
6051                }
6052            }
6053            // Filter out packages that aren't recently used.
6054            filterRecentlyUsedApps(pkgs);
6055            // Add all remaining apps.
6056            for (PackageParser.Package pkg : pkgs) {
6057                if (DEBUG_DEXOPT) {
6058                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6059                }
6060                sortedPkgs.add(pkg);
6061            }
6062
6063            // If we want to be lazy, filter everything that wasn't recently used.
6064            if (mLazyDexOpt) {
6065                filterRecentlyUsedApps(sortedPkgs);
6066            }
6067
6068            int i = 0;
6069            int total = sortedPkgs.size();
6070            File dataDir = Environment.getDataDirectory();
6071            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6072            if (lowThreshold == 0) {
6073                throw new IllegalStateException("Invalid low memory threshold");
6074            }
6075            for (PackageParser.Package pkg : sortedPkgs) {
6076                long usableSpace = dataDir.getUsableSpace();
6077                if (usableSpace < lowThreshold) {
6078                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6079                    break;
6080                }
6081                performBootDexOpt(pkg, ++i, total);
6082            }
6083        }
6084    }
6085
6086    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6087        // Filter out packages that aren't recently used.
6088        //
6089        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6090        // should do a full dexopt.
6091        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6092            int total = pkgs.size();
6093            int skipped = 0;
6094            long now = System.currentTimeMillis();
6095            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6096                PackageParser.Package pkg = i.next();
6097                long then = pkg.mLastPackageUsageTimeInMills;
6098                if (then + mDexOptLRUThresholdInMills < now) {
6099                    if (DEBUG_DEXOPT) {
6100                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6101                              ((then == 0) ? "never" : new Date(then)));
6102                    }
6103                    i.remove();
6104                    skipped++;
6105                }
6106            }
6107            if (DEBUG_DEXOPT) {
6108                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6109            }
6110        }
6111    }
6112
6113    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6114        List<ResolveInfo> ris = null;
6115        try {
6116            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6117                    intent, null, 0, UserHandle.USER_OWNER);
6118        } catch (RemoteException e) {
6119        }
6120        ArraySet<String> pkgNames = new ArraySet<String>();
6121        if (ris != null) {
6122            for (ResolveInfo ri : ris) {
6123                pkgNames.add(ri.activityInfo.packageName);
6124            }
6125        }
6126        return pkgNames;
6127    }
6128
6129    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6130        if (DEBUG_DEXOPT) {
6131            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6132        }
6133        if (!isFirstBoot()) {
6134            try {
6135                ActivityManagerNative.getDefault().showBootMessage(
6136                        mContext.getResources().getString(R.string.android_upgrading_apk,
6137                                curr, total), true);
6138            } catch (RemoteException e) {
6139            }
6140        }
6141        PackageParser.Package p = pkg;
6142        synchronized (mInstallLock) {
6143            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6144                    false /* force dex */, false /* defer */, true /* include dependencies */);
6145        }
6146    }
6147
6148    @Override
6149    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6150        return performDexOpt(packageName, instructionSet, false);
6151    }
6152
6153    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6154        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6155        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6156        if (!dexopt && !updateUsage) {
6157            // We aren't going to dexopt or update usage, so bail early.
6158            return false;
6159        }
6160        PackageParser.Package p;
6161        final String targetInstructionSet;
6162        synchronized (mPackages) {
6163            p = mPackages.get(packageName);
6164            if (p == null) {
6165                return false;
6166            }
6167            if (updateUsage) {
6168                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6169            }
6170            mPackageUsage.write(false);
6171            if (!dexopt) {
6172                // We aren't going to dexopt, so bail early.
6173                return false;
6174            }
6175
6176            targetInstructionSet = instructionSet != null ? instructionSet :
6177                    getPrimaryInstructionSet(p.applicationInfo);
6178            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6179                return false;
6180            }
6181        }
6182        long callingId = Binder.clearCallingIdentity();
6183        try {
6184            synchronized (mInstallLock) {
6185                final String[] instructionSets = new String[] { targetInstructionSet };
6186                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6187                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6188                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6189            }
6190        } finally {
6191            Binder.restoreCallingIdentity(callingId);
6192        }
6193    }
6194
6195    public ArraySet<String> getPackagesThatNeedDexOpt() {
6196        ArraySet<String> pkgs = null;
6197        synchronized (mPackages) {
6198            for (PackageParser.Package p : mPackages.values()) {
6199                if (DEBUG_DEXOPT) {
6200                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6201                }
6202                if (!p.mDexOptPerformed.isEmpty()) {
6203                    continue;
6204                }
6205                if (pkgs == null) {
6206                    pkgs = new ArraySet<String>();
6207                }
6208                pkgs.add(p.packageName);
6209            }
6210        }
6211        return pkgs;
6212    }
6213
6214    public void shutdown() {
6215        mPackageUsage.write(true);
6216    }
6217
6218    @Override
6219    public void forceDexOpt(String packageName) {
6220        enforceSystemOrRoot("forceDexOpt");
6221
6222        PackageParser.Package pkg;
6223        synchronized (mPackages) {
6224            pkg = mPackages.get(packageName);
6225            if (pkg == null) {
6226                throw new IllegalArgumentException("Missing package: " + packageName);
6227            }
6228        }
6229
6230        synchronized (mInstallLock) {
6231            final String[] instructionSets = new String[] {
6232                    getPrimaryInstructionSet(pkg.applicationInfo) };
6233            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6234                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6235            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6236                throw new IllegalStateException("Failed to dexopt: " + res);
6237            }
6238        }
6239    }
6240
6241    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6242        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6243            Slog.w(TAG, "Unable to update from " + oldPkg.name
6244                    + " to " + newPkg.packageName
6245                    + ": old package not in system partition");
6246            return false;
6247        } else if (mPackages.get(oldPkg.name) != null) {
6248            Slog.w(TAG, "Unable to update from " + oldPkg.name
6249                    + " to " + newPkg.packageName
6250                    + ": old package still exists");
6251            return false;
6252        }
6253        return true;
6254    }
6255
6256    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6257        int[] users = sUserManager.getUserIds();
6258        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6259        if (res < 0) {
6260            return res;
6261        }
6262        for (int user : users) {
6263            if (user != 0) {
6264                res = mInstaller.createUserData(volumeUuid, packageName,
6265                        UserHandle.getUid(user, uid), user, seinfo);
6266                if (res < 0) {
6267                    return res;
6268                }
6269            }
6270        }
6271        return res;
6272    }
6273
6274    private int removeDataDirsLI(String volumeUuid, String packageName) {
6275        int[] users = sUserManager.getUserIds();
6276        int res = 0;
6277        for (int user : users) {
6278            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6279            if (resInner < 0) {
6280                res = resInner;
6281            }
6282        }
6283
6284        return res;
6285    }
6286
6287    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6288        int[] users = sUserManager.getUserIds();
6289        int res = 0;
6290        for (int user : users) {
6291            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6292            if (resInner < 0) {
6293                res = resInner;
6294            }
6295        }
6296        return res;
6297    }
6298
6299    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6300            PackageParser.Package changingLib) {
6301        if (file.path != null) {
6302            usesLibraryFiles.add(file.path);
6303            return;
6304        }
6305        PackageParser.Package p = mPackages.get(file.apk);
6306        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6307            // If we are doing this while in the middle of updating a library apk,
6308            // then we need to make sure to use that new apk for determining the
6309            // dependencies here.  (We haven't yet finished committing the new apk
6310            // to the package manager state.)
6311            if (p == null || p.packageName.equals(changingLib.packageName)) {
6312                p = changingLib;
6313            }
6314        }
6315        if (p != null) {
6316            usesLibraryFiles.addAll(p.getAllCodePaths());
6317        }
6318    }
6319
6320    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6321            PackageParser.Package changingLib) throws PackageManagerException {
6322        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6323            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6324            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6325            for (int i=0; i<N; i++) {
6326                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6327                if (file == null) {
6328                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6329                            "Package " + pkg.packageName + " requires unavailable shared library "
6330                            + pkg.usesLibraries.get(i) + "; failing!");
6331                }
6332                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6333            }
6334            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6335            for (int i=0; i<N; i++) {
6336                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6337                if (file == null) {
6338                    Slog.w(TAG, "Package " + pkg.packageName
6339                            + " desires unavailable shared library "
6340                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6341                } else {
6342                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6343                }
6344            }
6345            N = usesLibraryFiles.size();
6346            if (N > 0) {
6347                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6348            } else {
6349                pkg.usesLibraryFiles = null;
6350            }
6351        }
6352    }
6353
6354    private static boolean hasString(List<String> list, List<String> which) {
6355        if (list == null) {
6356            return false;
6357        }
6358        for (int i=list.size()-1; i>=0; i--) {
6359            for (int j=which.size()-1; j>=0; j--) {
6360                if (which.get(j).equals(list.get(i))) {
6361                    return true;
6362                }
6363            }
6364        }
6365        return false;
6366    }
6367
6368    private void updateAllSharedLibrariesLPw() {
6369        for (PackageParser.Package pkg : mPackages.values()) {
6370            try {
6371                updateSharedLibrariesLPw(pkg, null);
6372            } catch (PackageManagerException e) {
6373                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6374            }
6375        }
6376    }
6377
6378    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6379            PackageParser.Package changingPkg) {
6380        ArrayList<PackageParser.Package> res = null;
6381        for (PackageParser.Package pkg : mPackages.values()) {
6382            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6383                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6384                if (res == null) {
6385                    res = new ArrayList<PackageParser.Package>();
6386                }
6387                res.add(pkg);
6388                try {
6389                    updateSharedLibrariesLPw(pkg, changingPkg);
6390                } catch (PackageManagerException e) {
6391                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6392                }
6393            }
6394        }
6395        return res;
6396    }
6397
6398    /**
6399     * Derive the value of the {@code cpuAbiOverride} based on the provided
6400     * value and an optional stored value from the package settings.
6401     */
6402    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6403        String cpuAbiOverride = null;
6404
6405        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6406            cpuAbiOverride = null;
6407        } else if (abiOverride != null) {
6408            cpuAbiOverride = abiOverride;
6409        } else if (settings != null) {
6410            cpuAbiOverride = settings.cpuAbiOverrideString;
6411        }
6412
6413        return cpuAbiOverride;
6414    }
6415
6416    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6417            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6418        boolean success = false;
6419        try {
6420            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6421                    currentTime, user);
6422            success = true;
6423            return res;
6424        } finally {
6425            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6426                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6427            }
6428        }
6429    }
6430
6431    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6432            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6433        final File scanFile = new File(pkg.codePath);
6434        if (pkg.applicationInfo.getCodePath() == null ||
6435                pkg.applicationInfo.getResourcePath() == null) {
6436            // Bail out. The resource and code paths haven't been set.
6437            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6438                    "Code and resource paths haven't been set correctly");
6439        }
6440
6441        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6442            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6443        } else {
6444            // Only allow system apps to be flagged as core apps.
6445            pkg.coreApp = false;
6446        }
6447
6448        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6449            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6450        }
6451
6452        if (mCustomResolverComponentName != null &&
6453                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6454            setUpCustomResolverActivity(pkg);
6455        }
6456
6457        if (pkg.packageName.equals("android")) {
6458            synchronized (mPackages) {
6459                if (mAndroidApplication != null) {
6460                    Slog.w(TAG, "*************************************************");
6461                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6462                    Slog.w(TAG, " file=" + scanFile);
6463                    Slog.w(TAG, "*************************************************");
6464                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6465                            "Core android package being redefined.  Skipping.");
6466                }
6467
6468                // Set up information for our fall-back user intent resolution activity.
6469                mPlatformPackage = pkg;
6470                pkg.mVersionCode = mSdkVersion;
6471                mAndroidApplication = pkg.applicationInfo;
6472
6473                if (!mResolverReplaced) {
6474                    mResolveActivity.applicationInfo = mAndroidApplication;
6475                    mResolveActivity.name = ResolverActivity.class.getName();
6476                    mResolveActivity.packageName = mAndroidApplication.packageName;
6477                    mResolveActivity.processName = "system:ui";
6478                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6479                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6480                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6481                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6482                    mResolveActivity.exported = true;
6483                    mResolveActivity.enabled = true;
6484                    mResolveInfo.activityInfo = mResolveActivity;
6485                    mResolveInfo.priority = 0;
6486                    mResolveInfo.preferredOrder = 0;
6487                    mResolveInfo.match = 0;
6488                    mResolveComponentName = new ComponentName(
6489                            mAndroidApplication.packageName, mResolveActivity.name);
6490                }
6491            }
6492        }
6493
6494        if (DEBUG_PACKAGE_SCANNING) {
6495            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6496                Log.d(TAG, "Scanning package " + pkg.packageName);
6497        }
6498
6499        if (mPackages.containsKey(pkg.packageName)
6500                || mSharedLibraries.containsKey(pkg.packageName)) {
6501            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6502                    "Application package " + pkg.packageName
6503                    + " already installed.  Skipping duplicate.");
6504        }
6505
6506        // If we're only installing presumed-existing packages, require that the
6507        // scanned APK is both already known and at the path previously established
6508        // for it.  Previously unknown packages we pick up normally, but if we have an
6509        // a priori expectation about this package's install presence, enforce it.
6510        // With a singular exception for new system packages. When an OTA contains
6511        // a new system package, we allow the codepath to change from a system location
6512        // to the user-installed location. If we don't allow this change, any newer,
6513        // user-installed version of the application will be ignored.
6514        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6515            if (mExpectingBetter.containsKey(pkg.packageName)) {
6516                logCriticalInfo(Log.WARN,
6517                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6518            } else {
6519                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6520                if (known != null) {
6521                    if (DEBUG_PACKAGE_SCANNING) {
6522                        Log.d(TAG, "Examining " + pkg.codePath
6523                                + " and requiring known paths " + known.codePathString
6524                                + " & " + known.resourcePathString);
6525                    }
6526                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6527                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6528                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6529                                "Application package " + pkg.packageName
6530                                + " found at " + pkg.applicationInfo.getCodePath()
6531                                + " but expected at " + known.codePathString + "; ignoring.");
6532                    }
6533                }
6534            }
6535        }
6536
6537        // Initialize package source and resource directories
6538        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6539        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6540
6541        SharedUserSetting suid = null;
6542        PackageSetting pkgSetting = null;
6543
6544        if (!isSystemApp(pkg)) {
6545            // Only system apps can use these features.
6546            pkg.mOriginalPackages = null;
6547            pkg.mRealPackage = null;
6548            pkg.mAdoptPermissions = null;
6549        }
6550
6551        // writer
6552        synchronized (mPackages) {
6553            if (pkg.mSharedUserId != null) {
6554                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6555                if (suid == null) {
6556                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6557                            "Creating application package " + pkg.packageName
6558                            + " for shared user failed");
6559                }
6560                if (DEBUG_PACKAGE_SCANNING) {
6561                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6562                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6563                                + "): packages=" + suid.packages);
6564                }
6565            }
6566
6567            // Check if we are renaming from an original package name.
6568            PackageSetting origPackage = null;
6569            String realName = null;
6570            if (pkg.mOriginalPackages != null) {
6571                // This package may need to be renamed to a previously
6572                // installed name.  Let's check on that...
6573                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6574                if (pkg.mOriginalPackages.contains(renamed)) {
6575                    // This package had originally been installed as the
6576                    // original name, and we have already taken care of
6577                    // transitioning to the new one.  Just update the new
6578                    // one to continue using the old name.
6579                    realName = pkg.mRealPackage;
6580                    if (!pkg.packageName.equals(renamed)) {
6581                        // Callers into this function may have already taken
6582                        // care of renaming the package; only do it here if
6583                        // it is not already done.
6584                        pkg.setPackageName(renamed);
6585                    }
6586
6587                } else {
6588                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6589                        if ((origPackage = mSettings.peekPackageLPr(
6590                                pkg.mOriginalPackages.get(i))) != null) {
6591                            // We do have the package already installed under its
6592                            // original name...  should we use it?
6593                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6594                                // New package is not compatible with original.
6595                                origPackage = null;
6596                                continue;
6597                            } else if (origPackage.sharedUser != null) {
6598                                // Make sure uid is compatible between packages.
6599                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6600                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6601                                            + " to " + pkg.packageName + ": old uid "
6602                                            + origPackage.sharedUser.name
6603                                            + " differs from " + pkg.mSharedUserId);
6604                                    origPackage = null;
6605                                    continue;
6606                                }
6607                            } else {
6608                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6609                                        + pkg.packageName + " to old name " + origPackage.name);
6610                            }
6611                            break;
6612                        }
6613                    }
6614                }
6615            }
6616
6617            if (mTransferedPackages.contains(pkg.packageName)) {
6618                Slog.w(TAG, "Package " + pkg.packageName
6619                        + " was transferred to another, but its .apk remains");
6620            }
6621
6622            // Just create the setting, don't add it yet. For already existing packages
6623            // the PkgSetting exists already and doesn't have to be created.
6624            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6625                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6626                    pkg.applicationInfo.primaryCpuAbi,
6627                    pkg.applicationInfo.secondaryCpuAbi,
6628                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6629                    user, false);
6630            if (pkgSetting == null) {
6631                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6632                        "Creating application package " + pkg.packageName + " failed");
6633            }
6634
6635            if (pkgSetting.origPackage != null) {
6636                // If we are first transitioning from an original package,
6637                // fix up the new package's name now.  We need to do this after
6638                // looking up the package under its new name, so getPackageLP
6639                // can take care of fiddling things correctly.
6640                pkg.setPackageName(origPackage.name);
6641
6642                // File a report about this.
6643                String msg = "New package " + pkgSetting.realName
6644                        + " renamed to replace old package " + pkgSetting.name;
6645                reportSettingsProblem(Log.WARN, msg);
6646
6647                // Make a note of it.
6648                mTransferedPackages.add(origPackage.name);
6649
6650                // No longer need to retain this.
6651                pkgSetting.origPackage = null;
6652            }
6653
6654            if (realName != null) {
6655                // Make a note of it.
6656                mTransferedPackages.add(pkg.packageName);
6657            }
6658
6659            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6660                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6661            }
6662
6663            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6664                // Check all shared libraries and map to their actual file path.
6665                // We only do this here for apps not on a system dir, because those
6666                // are the only ones that can fail an install due to this.  We
6667                // will take care of the system apps by updating all of their
6668                // library paths after the scan is done.
6669                updateSharedLibrariesLPw(pkg, null);
6670            }
6671
6672            if (mFoundPolicyFile) {
6673                SELinuxMMAC.assignSeinfoValue(pkg);
6674            }
6675
6676            pkg.applicationInfo.uid = pkgSetting.appId;
6677            pkg.mExtras = pkgSetting;
6678            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6679                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6680                    // We just determined the app is signed correctly, so bring
6681                    // over the latest parsed certs.
6682                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6683                } else {
6684                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6685                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6686                                "Package " + pkg.packageName + " upgrade keys do not match the "
6687                                + "previously installed version");
6688                    } else {
6689                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6690                        String msg = "System package " + pkg.packageName
6691                            + " signature changed; retaining data.";
6692                        reportSettingsProblem(Log.WARN, msg);
6693                    }
6694                }
6695            } else {
6696                try {
6697                    verifySignaturesLP(pkgSetting, pkg);
6698                    // We just determined the app is signed correctly, so bring
6699                    // over the latest parsed certs.
6700                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6701                } catch (PackageManagerException e) {
6702                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6703                        throw e;
6704                    }
6705                    // The signature has changed, but this package is in the system
6706                    // image...  let's recover!
6707                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6708                    // However...  if this package is part of a shared user, but it
6709                    // doesn't match the signature of the shared user, let's fail.
6710                    // What this means is that you can't change the signatures
6711                    // associated with an overall shared user, which doesn't seem all
6712                    // that unreasonable.
6713                    if (pkgSetting.sharedUser != null) {
6714                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6715                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6716                            throw new PackageManagerException(
6717                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6718                                            "Signature mismatch for shared user : "
6719                                            + pkgSetting.sharedUser);
6720                        }
6721                    }
6722                    // File a report about this.
6723                    String msg = "System package " + pkg.packageName
6724                        + " signature changed; retaining data.";
6725                    reportSettingsProblem(Log.WARN, msg);
6726                }
6727            }
6728            // Verify that this new package doesn't have any content providers
6729            // that conflict with existing packages.  Only do this if the
6730            // package isn't already installed, since we don't want to break
6731            // things that are installed.
6732            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6733                final int N = pkg.providers.size();
6734                int i;
6735                for (i=0; i<N; i++) {
6736                    PackageParser.Provider p = pkg.providers.get(i);
6737                    if (p.info.authority != null) {
6738                        String names[] = p.info.authority.split(";");
6739                        for (int j = 0; j < names.length; j++) {
6740                            if (mProvidersByAuthority.containsKey(names[j])) {
6741                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6742                                final String otherPackageName =
6743                                        ((other != null && other.getComponentName() != null) ?
6744                                                other.getComponentName().getPackageName() : "?");
6745                                throw new PackageManagerException(
6746                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6747                                                "Can't install because provider name " + names[j]
6748                                                + " (in package " + pkg.applicationInfo.packageName
6749                                                + ") is already used by " + otherPackageName);
6750                            }
6751                        }
6752                    }
6753                }
6754            }
6755
6756            if (pkg.mAdoptPermissions != null) {
6757                // This package wants to adopt ownership of permissions from
6758                // another package.
6759                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6760                    final String origName = pkg.mAdoptPermissions.get(i);
6761                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6762                    if (orig != null) {
6763                        if (verifyPackageUpdateLPr(orig, pkg)) {
6764                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6765                                    + pkg.packageName);
6766                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6767                        }
6768                    }
6769                }
6770            }
6771        }
6772
6773        final String pkgName = pkg.packageName;
6774
6775        final long scanFileTime = scanFile.lastModified();
6776        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6777        pkg.applicationInfo.processName = fixProcessName(
6778                pkg.applicationInfo.packageName,
6779                pkg.applicationInfo.processName,
6780                pkg.applicationInfo.uid);
6781
6782        File dataPath;
6783        if (mPlatformPackage == pkg) {
6784            // The system package is special.
6785            dataPath = new File(Environment.getDataDirectory(), "system");
6786
6787            pkg.applicationInfo.dataDir = dataPath.getPath();
6788
6789        } else {
6790            // This is a normal package, need to make its data directory.
6791            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6792                    UserHandle.USER_OWNER, pkg.packageName);
6793
6794            boolean uidError = false;
6795            if (dataPath.exists()) {
6796                int currentUid = 0;
6797                try {
6798                    StructStat stat = Os.stat(dataPath.getPath());
6799                    currentUid = stat.st_uid;
6800                } catch (ErrnoException e) {
6801                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6802                }
6803
6804                // If we have mismatched owners for the data path, we have a problem.
6805                if (currentUid != pkg.applicationInfo.uid) {
6806                    boolean recovered = false;
6807                    if (currentUid == 0) {
6808                        // The directory somehow became owned by root.  Wow.
6809                        // This is probably because the system was stopped while
6810                        // installd was in the middle of messing with its libs
6811                        // directory.  Ask installd to fix that.
6812                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6813                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6814                        if (ret >= 0) {
6815                            recovered = true;
6816                            String msg = "Package " + pkg.packageName
6817                                    + " unexpectedly changed to uid 0; recovered to " +
6818                                    + pkg.applicationInfo.uid;
6819                            reportSettingsProblem(Log.WARN, msg);
6820                        }
6821                    }
6822                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6823                            || (scanFlags&SCAN_BOOTING) != 0)) {
6824                        // If this is a system app, we can at least delete its
6825                        // current data so the application will still work.
6826                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6827                        if (ret >= 0) {
6828                            // TODO: Kill the processes first
6829                            // Old data gone!
6830                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6831                                    ? "System package " : "Third party package ";
6832                            String msg = prefix + pkg.packageName
6833                                    + " has changed from uid: "
6834                                    + currentUid + " to "
6835                                    + pkg.applicationInfo.uid + "; old data erased";
6836                            reportSettingsProblem(Log.WARN, msg);
6837                            recovered = true;
6838
6839                            // And now re-install the app.
6840                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6841                                    pkg.applicationInfo.seinfo);
6842                            if (ret == -1) {
6843                                // Ack should not happen!
6844                                msg = prefix + pkg.packageName
6845                                        + " could not have data directory re-created after delete.";
6846                                reportSettingsProblem(Log.WARN, msg);
6847                                throw new PackageManagerException(
6848                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6849                            }
6850                        }
6851                        if (!recovered) {
6852                            mHasSystemUidErrors = true;
6853                        }
6854                    } else if (!recovered) {
6855                        // If we allow this install to proceed, we will be broken.
6856                        // Abort, abort!
6857                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6858                                "scanPackageLI");
6859                    }
6860                    if (!recovered) {
6861                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6862                            + pkg.applicationInfo.uid + "/fs_"
6863                            + currentUid;
6864                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6865                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6866                        String msg = "Package " + pkg.packageName
6867                                + " has mismatched uid: "
6868                                + currentUid + " on disk, "
6869                                + pkg.applicationInfo.uid + " in settings";
6870                        // writer
6871                        synchronized (mPackages) {
6872                            mSettings.mReadMessages.append(msg);
6873                            mSettings.mReadMessages.append('\n');
6874                            uidError = true;
6875                            if (!pkgSetting.uidError) {
6876                                reportSettingsProblem(Log.ERROR, msg);
6877                            }
6878                        }
6879                    }
6880                }
6881                pkg.applicationInfo.dataDir = dataPath.getPath();
6882                if (mShouldRestoreconData) {
6883                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6884                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6885                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6886                }
6887            } else {
6888                if (DEBUG_PACKAGE_SCANNING) {
6889                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6890                        Log.v(TAG, "Want this data dir: " + dataPath);
6891                }
6892                //invoke installer to do the actual installation
6893                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6894                        pkg.applicationInfo.seinfo);
6895                if (ret < 0) {
6896                    // Error from installer
6897                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6898                            "Unable to create data dirs [errorCode=" + ret + "]");
6899                }
6900
6901                if (dataPath.exists()) {
6902                    pkg.applicationInfo.dataDir = dataPath.getPath();
6903                } else {
6904                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6905                    pkg.applicationInfo.dataDir = null;
6906                }
6907            }
6908
6909            pkgSetting.uidError = uidError;
6910        }
6911
6912        final String path = scanFile.getPath();
6913        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6914
6915        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6916            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6917
6918            // Some system apps still use directory structure for native libraries
6919            // in which case we might end up not detecting abi solely based on apk
6920            // structure. Try to detect abi based on directory structure.
6921            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6922                    pkg.applicationInfo.primaryCpuAbi == null) {
6923                setBundledAppAbisAndRoots(pkg, pkgSetting);
6924                setNativeLibraryPaths(pkg);
6925            }
6926
6927        } else {
6928            if ((scanFlags & SCAN_MOVE) != 0) {
6929                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6930                // but we already have this packages package info in the PackageSetting. We just
6931                // use that and derive the native library path based on the new codepath.
6932                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6933                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6934            }
6935
6936            // Set native library paths again. For moves, the path will be updated based on the
6937            // ABIs we've determined above. For non-moves, the path will be updated based on the
6938            // ABIs we determined during compilation, but the path will depend on the final
6939            // package path (after the rename away from the stage path).
6940            setNativeLibraryPaths(pkg);
6941        }
6942
6943        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6944        final int[] userIds = sUserManager.getUserIds();
6945        synchronized (mInstallLock) {
6946            // Make sure all user data directories are ready to roll; we're okay
6947            // if they already exist
6948            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6949                for (int userId : userIds) {
6950                    if (userId != 0) {
6951                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6952                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6953                                pkg.applicationInfo.seinfo);
6954                    }
6955                }
6956            }
6957
6958            // Create a native library symlink only if we have native libraries
6959            // and if the native libraries are 32 bit libraries. We do not provide
6960            // this symlink for 64 bit libraries.
6961            if (pkg.applicationInfo.primaryCpuAbi != null &&
6962                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6963                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6964                for (int userId : userIds) {
6965                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6966                            nativeLibPath, userId) < 0) {
6967                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6968                                "Failed linking native library dir (user=" + userId + ")");
6969                    }
6970                }
6971            }
6972        }
6973
6974        // This is a special case for the "system" package, where the ABI is
6975        // dictated by the zygote configuration (and init.rc). We should keep track
6976        // of this ABI so that we can deal with "normal" applications that run under
6977        // the same UID correctly.
6978        if (mPlatformPackage == pkg) {
6979            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6980                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6981        }
6982
6983        // If there's a mismatch between the abi-override in the package setting
6984        // and the abiOverride specified for the install. Warn about this because we
6985        // would've already compiled the app without taking the package setting into
6986        // account.
6987        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6988            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6989                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6990                        " for package: " + pkg.packageName);
6991            }
6992        }
6993
6994        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6995        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6996        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6997
6998        // Copy the derived override back to the parsed package, so that we can
6999        // update the package settings accordingly.
7000        pkg.cpuAbiOverride = cpuAbiOverride;
7001
7002        if (DEBUG_ABI_SELECTION) {
7003            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7004                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7005                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7006        }
7007
7008        // Push the derived path down into PackageSettings so we know what to
7009        // clean up at uninstall time.
7010        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7011
7012        if (DEBUG_ABI_SELECTION) {
7013            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7014                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7015                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7016        }
7017
7018        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7019            // We don't do this here during boot because we can do it all
7020            // at once after scanning all existing packages.
7021            //
7022            // We also do this *before* we perform dexopt on this package, so that
7023            // we can avoid redundant dexopts, and also to make sure we've got the
7024            // code and package path correct.
7025            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7026                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7027        }
7028
7029        if ((scanFlags & SCAN_NO_DEX) == 0) {
7030            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7031                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7032            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7033                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7034            }
7035        }
7036        if (mFactoryTest && pkg.requestedPermissions.contains(
7037                android.Manifest.permission.FACTORY_TEST)) {
7038            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7039        }
7040
7041        ArrayList<PackageParser.Package> clientLibPkgs = null;
7042
7043        // writer
7044        synchronized (mPackages) {
7045            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7046                // Only system apps can add new shared libraries.
7047                if (pkg.libraryNames != null) {
7048                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7049                        String name = pkg.libraryNames.get(i);
7050                        boolean allowed = false;
7051                        if (pkg.isUpdatedSystemApp()) {
7052                            // New library entries can only be added through the
7053                            // system image.  This is important to get rid of a lot
7054                            // of nasty edge cases: for example if we allowed a non-
7055                            // system update of the app to add a library, then uninstalling
7056                            // the update would make the library go away, and assumptions
7057                            // we made such as through app install filtering would now
7058                            // have allowed apps on the device which aren't compatible
7059                            // with it.  Better to just have the restriction here, be
7060                            // conservative, and create many fewer cases that can negatively
7061                            // impact the user experience.
7062                            final PackageSetting sysPs = mSettings
7063                                    .getDisabledSystemPkgLPr(pkg.packageName);
7064                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7065                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7066                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7067                                        allowed = true;
7068                                        allowed = true;
7069                                        break;
7070                                    }
7071                                }
7072                            }
7073                        } else {
7074                            allowed = true;
7075                        }
7076                        if (allowed) {
7077                            if (!mSharedLibraries.containsKey(name)) {
7078                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7079                            } else if (!name.equals(pkg.packageName)) {
7080                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7081                                        + name + " already exists; skipping");
7082                            }
7083                        } else {
7084                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7085                                    + name + " that is not declared on system image; skipping");
7086                        }
7087                    }
7088                    if ((scanFlags&SCAN_BOOTING) == 0) {
7089                        // If we are not booting, we need to update any applications
7090                        // that are clients of our shared library.  If we are booting,
7091                        // this will all be done once the scan is complete.
7092                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7093                    }
7094                }
7095            }
7096        }
7097
7098        // We also need to dexopt any apps that are dependent on this library.  Note that
7099        // if these fail, we should abort the install since installing the library will
7100        // result in some apps being broken.
7101        if (clientLibPkgs != null) {
7102            if ((scanFlags & SCAN_NO_DEX) == 0) {
7103                for (int i = 0; i < clientLibPkgs.size(); i++) {
7104                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7105                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7106                            null /* instruction sets */, forceDex,
7107                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7108                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7109                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7110                                "scanPackageLI failed to dexopt clientLibPkgs");
7111                    }
7112                }
7113            }
7114        }
7115
7116        // Also need to kill any apps that are dependent on the library.
7117        if (clientLibPkgs != null) {
7118            for (int i=0; i<clientLibPkgs.size(); i++) {
7119                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7120                killApplication(clientPkg.applicationInfo.packageName,
7121                        clientPkg.applicationInfo.uid, "update lib");
7122            }
7123        }
7124
7125        // Make sure we're not adding any bogus keyset info
7126        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7127        ksms.assertScannedPackageValid(pkg);
7128
7129        // writer
7130        synchronized (mPackages) {
7131            // We don't expect installation to fail beyond this point
7132
7133            // Add the new setting to mSettings
7134            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7135            // Add the new setting to mPackages
7136            mPackages.put(pkg.applicationInfo.packageName, pkg);
7137            // Make sure we don't accidentally delete its data.
7138            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7139            while (iter.hasNext()) {
7140                PackageCleanItem item = iter.next();
7141                if (pkgName.equals(item.packageName)) {
7142                    iter.remove();
7143                }
7144            }
7145
7146            // Take care of first install / last update times.
7147            if (currentTime != 0) {
7148                if (pkgSetting.firstInstallTime == 0) {
7149                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7150                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7151                    pkgSetting.lastUpdateTime = currentTime;
7152                }
7153            } else if (pkgSetting.firstInstallTime == 0) {
7154                // We need *something*.  Take time time stamp of the file.
7155                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7156            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7157                if (scanFileTime != pkgSetting.timeStamp) {
7158                    // A package on the system image has changed; consider this
7159                    // to be an update.
7160                    pkgSetting.lastUpdateTime = scanFileTime;
7161                }
7162            }
7163
7164            // Add the package's KeySets to the global KeySetManagerService
7165            ksms.addScannedPackageLPw(pkg);
7166
7167            int N = pkg.providers.size();
7168            StringBuilder r = null;
7169            int i;
7170            for (i=0; i<N; i++) {
7171                PackageParser.Provider p = pkg.providers.get(i);
7172                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7173                        p.info.processName, pkg.applicationInfo.uid);
7174                mProviders.addProvider(p);
7175                p.syncable = p.info.isSyncable;
7176                if (p.info.authority != null) {
7177                    String names[] = p.info.authority.split(";");
7178                    p.info.authority = null;
7179                    for (int j = 0; j < names.length; j++) {
7180                        if (j == 1 && p.syncable) {
7181                            // We only want the first authority for a provider to possibly be
7182                            // syncable, so if we already added this provider using a different
7183                            // authority clear the syncable flag. We copy the provider before
7184                            // changing it because the mProviders object contains a reference
7185                            // to a provider that we don't want to change.
7186                            // Only do this for the second authority since the resulting provider
7187                            // object can be the same for all future authorities for this provider.
7188                            p = new PackageParser.Provider(p);
7189                            p.syncable = false;
7190                        }
7191                        if (!mProvidersByAuthority.containsKey(names[j])) {
7192                            mProvidersByAuthority.put(names[j], p);
7193                            if (p.info.authority == null) {
7194                                p.info.authority = names[j];
7195                            } else {
7196                                p.info.authority = p.info.authority + ";" + names[j];
7197                            }
7198                            if (DEBUG_PACKAGE_SCANNING) {
7199                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7200                                    Log.d(TAG, "Registered content provider: " + names[j]
7201                                            + ", className = " + p.info.name + ", isSyncable = "
7202                                            + p.info.isSyncable);
7203                            }
7204                        } else {
7205                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7206                            Slog.w(TAG, "Skipping provider name " + names[j] +
7207                                    " (in package " + pkg.applicationInfo.packageName +
7208                                    "): name already used by "
7209                                    + ((other != null && other.getComponentName() != null)
7210                                            ? other.getComponentName().getPackageName() : "?"));
7211                        }
7212                    }
7213                }
7214                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7215                    if (r == null) {
7216                        r = new StringBuilder(256);
7217                    } else {
7218                        r.append(' ');
7219                    }
7220                    r.append(p.info.name);
7221                }
7222            }
7223            if (r != null) {
7224                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7225            }
7226
7227            N = pkg.services.size();
7228            r = null;
7229            for (i=0; i<N; i++) {
7230                PackageParser.Service s = pkg.services.get(i);
7231                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7232                        s.info.processName, pkg.applicationInfo.uid);
7233                mServices.addService(s);
7234                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7235                    if (r == null) {
7236                        r = new StringBuilder(256);
7237                    } else {
7238                        r.append(' ');
7239                    }
7240                    r.append(s.info.name);
7241                }
7242            }
7243            if (r != null) {
7244                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7245            }
7246
7247            N = pkg.receivers.size();
7248            r = null;
7249            for (i=0; i<N; i++) {
7250                PackageParser.Activity a = pkg.receivers.get(i);
7251                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7252                        a.info.processName, pkg.applicationInfo.uid);
7253                mReceivers.addActivity(a, "receiver");
7254                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7255                    if (r == null) {
7256                        r = new StringBuilder(256);
7257                    } else {
7258                        r.append(' ');
7259                    }
7260                    r.append(a.info.name);
7261                }
7262            }
7263            if (r != null) {
7264                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7265            }
7266
7267            N = pkg.activities.size();
7268            r = null;
7269            for (i=0; i<N; i++) {
7270                PackageParser.Activity a = pkg.activities.get(i);
7271                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7272                        a.info.processName, pkg.applicationInfo.uid);
7273                mActivities.addActivity(a, "activity");
7274                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7275                    if (r == null) {
7276                        r = new StringBuilder(256);
7277                    } else {
7278                        r.append(' ');
7279                    }
7280                    r.append(a.info.name);
7281                }
7282            }
7283            if (r != null) {
7284                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7285            }
7286
7287            N = pkg.permissionGroups.size();
7288            r = null;
7289            for (i=0; i<N; i++) {
7290                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7291                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7292                if (cur == null) {
7293                    mPermissionGroups.put(pg.info.name, pg);
7294                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7295                        if (r == null) {
7296                            r = new StringBuilder(256);
7297                        } else {
7298                            r.append(' ');
7299                        }
7300                        r.append(pg.info.name);
7301                    }
7302                } else {
7303                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7304                            + pg.info.packageName + " ignored: original from "
7305                            + cur.info.packageName);
7306                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7307                        if (r == null) {
7308                            r = new StringBuilder(256);
7309                        } else {
7310                            r.append(' ');
7311                        }
7312                        r.append("DUP:");
7313                        r.append(pg.info.name);
7314                    }
7315                }
7316            }
7317            if (r != null) {
7318                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7319            }
7320
7321            N = pkg.permissions.size();
7322            r = null;
7323            for (i=0; i<N; i++) {
7324                PackageParser.Permission p = pkg.permissions.get(i);
7325
7326                // Assume by default that we did not install this permission into the system.
7327                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7328
7329                // Now that permission groups have a special meaning, we ignore permission
7330                // groups for legacy apps to prevent unexpected behavior. In particular,
7331                // permissions for one app being granted to someone just becuase they happen
7332                // to be in a group defined by another app (before this had no implications).
7333                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7334                    p.group = mPermissionGroups.get(p.info.group);
7335                    // Warn for a permission in an unknown group.
7336                    if (p.info.group != null && p.group == null) {
7337                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7338                                + p.info.packageName + " in an unknown group " + p.info.group);
7339                    }
7340                }
7341
7342                ArrayMap<String, BasePermission> permissionMap =
7343                        p.tree ? mSettings.mPermissionTrees
7344                                : mSettings.mPermissions;
7345                BasePermission bp = permissionMap.get(p.info.name);
7346
7347                // Allow system apps to redefine non-system permissions
7348                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7349                    final boolean currentOwnerIsSystem = (bp.perm != null
7350                            && isSystemApp(bp.perm.owner));
7351                    if (isSystemApp(p.owner)) {
7352                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7353                            // It's a built-in permission and no owner, take ownership now
7354                            bp.packageSetting = pkgSetting;
7355                            bp.perm = p;
7356                            bp.uid = pkg.applicationInfo.uid;
7357                            bp.sourcePackage = p.info.packageName;
7358                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7359                        } else if (!currentOwnerIsSystem) {
7360                            String msg = "New decl " + p.owner + " of permission  "
7361                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7362                            reportSettingsProblem(Log.WARN, msg);
7363                            bp = null;
7364                        }
7365                    }
7366                }
7367
7368                if (bp == null) {
7369                    bp = new BasePermission(p.info.name, p.info.packageName,
7370                            BasePermission.TYPE_NORMAL);
7371                    permissionMap.put(p.info.name, bp);
7372                }
7373
7374                if (bp.perm == null) {
7375                    if (bp.sourcePackage == null
7376                            || bp.sourcePackage.equals(p.info.packageName)) {
7377                        BasePermission tree = findPermissionTreeLP(p.info.name);
7378                        if (tree == null
7379                                || tree.sourcePackage.equals(p.info.packageName)) {
7380                            bp.packageSetting = pkgSetting;
7381                            bp.perm = p;
7382                            bp.uid = pkg.applicationInfo.uid;
7383                            bp.sourcePackage = p.info.packageName;
7384                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7385                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7386                                if (r == null) {
7387                                    r = new StringBuilder(256);
7388                                } else {
7389                                    r.append(' ');
7390                                }
7391                                r.append(p.info.name);
7392                            }
7393                        } else {
7394                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7395                                    + p.info.packageName + " ignored: base tree "
7396                                    + tree.name + " is from package "
7397                                    + tree.sourcePackage);
7398                        }
7399                    } else {
7400                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7401                                + p.info.packageName + " ignored: original from "
7402                                + bp.sourcePackage);
7403                    }
7404                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7405                    if (r == null) {
7406                        r = new StringBuilder(256);
7407                    } else {
7408                        r.append(' ');
7409                    }
7410                    r.append("DUP:");
7411                    r.append(p.info.name);
7412                }
7413                if (bp.perm == p) {
7414                    bp.protectionLevel = p.info.protectionLevel;
7415                }
7416            }
7417
7418            if (r != null) {
7419                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7420            }
7421
7422            N = pkg.instrumentation.size();
7423            r = null;
7424            for (i=0; i<N; i++) {
7425                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7426                a.info.packageName = pkg.applicationInfo.packageName;
7427                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7428                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7429                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7430                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7431                a.info.dataDir = pkg.applicationInfo.dataDir;
7432
7433                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7434                // need other information about the application, like the ABI and what not ?
7435                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7436                mInstrumentation.put(a.getComponentName(), a);
7437                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7438                    if (r == null) {
7439                        r = new StringBuilder(256);
7440                    } else {
7441                        r.append(' ');
7442                    }
7443                    r.append(a.info.name);
7444                }
7445            }
7446            if (r != null) {
7447                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7448            }
7449
7450            if (pkg.protectedBroadcasts != null) {
7451                N = pkg.protectedBroadcasts.size();
7452                for (i=0; i<N; i++) {
7453                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7454                }
7455            }
7456
7457            pkgSetting.setTimeStamp(scanFileTime);
7458
7459            // Create idmap files for pairs of (packages, overlay packages).
7460            // Note: "android", ie framework-res.apk, is handled by native layers.
7461            if (pkg.mOverlayTarget != null) {
7462                // This is an overlay package.
7463                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7464                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7465                        mOverlays.put(pkg.mOverlayTarget,
7466                                new ArrayMap<String, PackageParser.Package>());
7467                    }
7468                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7469                    map.put(pkg.packageName, pkg);
7470                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7471                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7472                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7473                                "scanPackageLI failed to createIdmap");
7474                    }
7475                }
7476            } else if (mOverlays.containsKey(pkg.packageName) &&
7477                    !pkg.packageName.equals("android")) {
7478                // This is a regular package, with one or more known overlay packages.
7479                createIdmapsForPackageLI(pkg);
7480            }
7481        }
7482
7483        return pkg;
7484    }
7485
7486    /**
7487     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7488     * is derived purely on the basis of the contents of {@code scanFile} and
7489     * {@code cpuAbiOverride}.
7490     *
7491     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7492     */
7493    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7494                                 String cpuAbiOverride, boolean extractLibs)
7495            throws PackageManagerException {
7496        // TODO: We can probably be smarter about this stuff. For installed apps,
7497        // we can calculate this information at install time once and for all. For
7498        // system apps, we can probably assume that this information doesn't change
7499        // after the first boot scan. As things stand, we do lots of unnecessary work.
7500
7501        // Give ourselves some initial paths; we'll come back for another
7502        // pass once we've determined ABI below.
7503        setNativeLibraryPaths(pkg);
7504
7505        // We would never need to extract libs for forward-locked and external packages,
7506        // since the container service will do it for us. We shouldn't attempt to
7507        // extract libs from system app when it was not updated.
7508        if (pkg.isForwardLocked() || isExternal(pkg) ||
7509            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7510            extractLibs = false;
7511        }
7512
7513        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7514        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7515
7516        NativeLibraryHelper.Handle handle = null;
7517        try {
7518            handle = NativeLibraryHelper.Handle.create(pkg);
7519            // TODO(multiArch): This can be null for apps that didn't go through the
7520            // usual installation process. We can calculate it again, like we
7521            // do during install time.
7522            //
7523            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7524            // unnecessary.
7525            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7526
7527            // Null out the abis so that they can be recalculated.
7528            pkg.applicationInfo.primaryCpuAbi = null;
7529            pkg.applicationInfo.secondaryCpuAbi = null;
7530            if (isMultiArch(pkg.applicationInfo)) {
7531                // Warn if we've set an abiOverride for multi-lib packages..
7532                // By definition, we need to copy both 32 and 64 bit libraries for
7533                // such packages.
7534                if (pkg.cpuAbiOverride != null
7535                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7536                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7537                }
7538
7539                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7540                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7541                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7542                    if (extractLibs) {
7543                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7544                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7545                                useIsaSpecificSubdirs);
7546                    } else {
7547                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7548                    }
7549                }
7550
7551                maybeThrowExceptionForMultiArchCopy(
7552                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7553
7554                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7555                    if (extractLibs) {
7556                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7557                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7558                                useIsaSpecificSubdirs);
7559                    } else {
7560                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7561                    }
7562                }
7563
7564                maybeThrowExceptionForMultiArchCopy(
7565                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7566
7567                if (abi64 >= 0) {
7568                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7569                }
7570
7571                if (abi32 >= 0) {
7572                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7573                    if (abi64 >= 0) {
7574                        pkg.applicationInfo.secondaryCpuAbi = abi;
7575                    } else {
7576                        pkg.applicationInfo.primaryCpuAbi = abi;
7577                    }
7578                }
7579            } else {
7580                String[] abiList = (cpuAbiOverride != null) ?
7581                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7582
7583                // Enable gross and lame hacks for apps that are built with old
7584                // SDK tools. We must scan their APKs for renderscript bitcode and
7585                // not launch them if it's present. Don't bother checking on devices
7586                // that don't have 64 bit support.
7587                boolean needsRenderScriptOverride = false;
7588                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7589                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7590                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7591                    needsRenderScriptOverride = true;
7592                }
7593
7594                final int copyRet;
7595                if (extractLibs) {
7596                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7597                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7598                } else {
7599                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7600                }
7601
7602                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7603                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7604                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7605                }
7606
7607                if (copyRet >= 0) {
7608                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7609                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7610                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7611                } else if (needsRenderScriptOverride) {
7612                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7613                }
7614            }
7615        } catch (IOException ioe) {
7616            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7617        } finally {
7618            IoUtils.closeQuietly(handle);
7619        }
7620
7621        // Now that we've calculated the ABIs and determined if it's an internal app,
7622        // we will go ahead and populate the nativeLibraryPath.
7623        setNativeLibraryPaths(pkg);
7624    }
7625
7626    /**
7627     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7628     * i.e, so that all packages can be run inside a single process if required.
7629     *
7630     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7631     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7632     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7633     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7634     * updating a package that belongs to a shared user.
7635     *
7636     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7637     * adds unnecessary complexity.
7638     */
7639    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7640            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7641        String requiredInstructionSet = null;
7642        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7643            requiredInstructionSet = VMRuntime.getInstructionSet(
7644                     scannedPackage.applicationInfo.primaryCpuAbi);
7645        }
7646
7647        PackageSetting requirer = null;
7648        for (PackageSetting ps : packagesForUser) {
7649            // If packagesForUser contains scannedPackage, we skip it. This will happen
7650            // when scannedPackage is an update of an existing package. Without this check,
7651            // we will never be able to change the ABI of any package belonging to a shared
7652            // user, even if it's compatible with other packages.
7653            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7654                if (ps.primaryCpuAbiString == null) {
7655                    continue;
7656                }
7657
7658                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7659                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7660                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7661                    // this but there's not much we can do.
7662                    String errorMessage = "Instruction set mismatch, "
7663                            + ((requirer == null) ? "[caller]" : requirer)
7664                            + " requires " + requiredInstructionSet + " whereas " + ps
7665                            + " requires " + instructionSet;
7666                    Slog.w(TAG, errorMessage);
7667                }
7668
7669                if (requiredInstructionSet == null) {
7670                    requiredInstructionSet = instructionSet;
7671                    requirer = ps;
7672                }
7673            }
7674        }
7675
7676        if (requiredInstructionSet != null) {
7677            String adjustedAbi;
7678            if (requirer != null) {
7679                // requirer != null implies that either scannedPackage was null or that scannedPackage
7680                // did not require an ABI, in which case we have to adjust scannedPackage to match
7681                // the ABI of the set (which is the same as requirer's ABI)
7682                adjustedAbi = requirer.primaryCpuAbiString;
7683                if (scannedPackage != null) {
7684                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7685                }
7686            } else {
7687                // requirer == null implies that we're updating all ABIs in the set to
7688                // match scannedPackage.
7689                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7690            }
7691
7692            for (PackageSetting ps : packagesForUser) {
7693                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7694                    if (ps.primaryCpuAbiString != null) {
7695                        continue;
7696                    }
7697
7698                    ps.primaryCpuAbiString = adjustedAbi;
7699                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7700                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7701                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7702
7703                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7704                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7705                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7706                            ps.primaryCpuAbiString = null;
7707                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7708                            return;
7709                        } else {
7710                            mInstaller.rmdex(ps.codePathString,
7711                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7712                        }
7713                    }
7714                }
7715            }
7716        }
7717    }
7718
7719    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7720        synchronized (mPackages) {
7721            mResolverReplaced = true;
7722            // Set up information for custom user intent resolution activity.
7723            mResolveActivity.applicationInfo = pkg.applicationInfo;
7724            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7725            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7726            mResolveActivity.processName = pkg.applicationInfo.packageName;
7727            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7728            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7729                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7730            mResolveActivity.theme = 0;
7731            mResolveActivity.exported = true;
7732            mResolveActivity.enabled = true;
7733            mResolveInfo.activityInfo = mResolveActivity;
7734            mResolveInfo.priority = 0;
7735            mResolveInfo.preferredOrder = 0;
7736            mResolveInfo.match = 0;
7737            mResolveComponentName = mCustomResolverComponentName;
7738            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7739                    mResolveComponentName);
7740        }
7741    }
7742
7743    private static String calculateBundledApkRoot(final String codePathString) {
7744        final File codePath = new File(codePathString);
7745        final File codeRoot;
7746        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7747            codeRoot = Environment.getRootDirectory();
7748        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7749            codeRoot = Environment.getOemDirectory();
7750        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7751            codeRoot = Environment.getVendorDirectory();
7752        } else {
7753            // Unrecognized code path; take its top real segment as the apk root:
7754            // e.g. /something/app/blah.apk => /something
7755            try {
7756                File f = codePath.getCanonicalFile();
7757                File parent = f.getParentFile();    // non-null because codePath is a file
7758                File tmp;
7759                while ((tmp = parent.getParentFile()) != null) {
7760                    f = parent;
7761                    parent = tmp;
7762                }
7763                codeRoot = f;
7764                Slog.w(TAG, "Unrecognized code path "
7765                        + codePath + " - using " + codeRoot);
7766            } catch (IOException e) {
7767                // Can't canonicalize the code path -- shenanigans?
7768                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7769                return Environment.getRootDirectory().getPath();
7770            }
7771        }
7772        return codeRoot.getPath();
7773    }
7774
7775    /**
7776     * Derive and set the location of native libraries for the given package,
7777     * which varies depending on where and how the package was installed.
7778     */
7779    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7780        final ApplicationInfo info = pkg.applicationInfo;
7781        final String codePath = pkg.codePath;
7782        final File codeFile = new File(codePath);
7783        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7784        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7785
7786        info.nativeLibraryRootDir = null;
7787        info.nativeLibraryRootRequiresIsa = false;
7788        info.nativeLibraryDir = null;
7789        info.secondaryNativeLibraryDir = null;
7790
7791        if (isApkFile(codeFile)) {
7792            // Monolithic install
7793            if (bundledApp) {
7794                // If "/system/lib64/apkname" exists, assume that is the per-package
7795                // native library directory to use; otherwise use "/system/lib/apkname".
7796                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7797                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7798                        getPrimaryInstructionSet(info));
7799
7800                // This is a bundled system app so choose the path based on the ABI.
7801                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7802                // is just the default path.
7803                final String apkName = deriveCodePathName(codePath);
7804                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7805                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7806                        apkName).getAbsolutePath();
7807
7808                if (info.secondaryCpuAbi != null) {
7809                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7810                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7811                            secondaryLibDir, apkName).getAbsolutePath();
7812                }
7813            } else if (asecApp) {
7814                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7815                        .getAbsolutePath();
7816            } else {
7817                final String apkName = deriveCodePathName(codePath);
7818                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7819                        .getAbsolutePath();
7820            }
7821
7822            info.nativeLibraryRootRequiresIsa = false;
7823            info.nativeLibraryDir = info.nativeLibraryRootDir;
7824        } else {
7825            // Cluster install
7826            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7827            info.nativeLibraryRootRequiresIsa = true;
7828
7829            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7830                    getPrimaryInstructionSet(info)).getAbsolutePath();
7831
7832            if (info.secondaryCpuAbi != null) {
7833                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7834                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7835            }
7836        }
7837    }
7838
7839    /**
7840     * Calculate the abis and roots for a bundled app. These can uniquely
7841     * be determined from the contents of the system partition, i.e whether
7842     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7843     * of this information, and instead assume that the system was built
7844     * sensibly.
7845     */
7846    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7847                                           PackageSetting pkgSetting) {
7848        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7849
7850        // If "/system/lib64/apkname" exists, assume that is the per-package
7851        // native library directory to use; otherwise use "/system/lib/apkname".
7852        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7853        setBundledAppAbi(pkg, apkRoot, apkName);
7854        // pkgSetting might be null during rescan following uninstall of updates
7855        // to a bundled app, so accommodate that possibility.  The settings in
7856        // that case will be established later from the parsed package.
7857        //
7858        // If the settings aren't null, sync them up with what we've just derived.
7859        // note that apkRoot isn't stored in the package settings.
7860        if (pkgSetting != null) {
7861            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7862            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7863        }
7864    }
7865
7866    /**
7867     * Deduces the ABI of a bundled app and sets the relevant fields on the
7868     * parsed pkg object.
7869     *
7870     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7871     *        under which system libraries are installed.
7872     * @param apkName the name of the installed package.
7873     */
7874    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7875        final File codeFile = new File(pkg.codePath);
7876
7877        final boolean has64BitLibs;
7878        final boolean has32BitLibs;
7879        if (isApkFile(codeFile)) {
7880            // Monolithic install
7881            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7882            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7883        } else {
7884            // Cluster install
7885            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7886            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7887                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7888                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7889                has64BitLibs = (new File(rootDir, isa)).exists();
7890            } else {
7891                has64BitLibs = false;
7892            }
7893            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7894                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7895                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7896                has32BitLibs = (new File(rootDir, isa)).exists();
7897            } else {
7898                has32BitLibs = false;
7899            }
7900        }
7901
7902        if (has64BitLibs && !has32BitLibs) {
7903            // The package has 64 bit libs, but not 32 bit libs. Its primary
7904            // ABI should be 64 bit. We can safely assume here that the bundled
7905            // native libraries correspond to the most preferred ABI in the list.
7906
7907            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7908            pkg.applicationInfo.secondaryCpuAbi = null;
7909        } else if (has32BitLibs && !has64BitLibs) {
7910            // The package has 32 bit libs but not 64 bit libs. Its primary
7911            // ABI should be 32 bit.
7912
7913            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7914            pkg.applicationInfo.secondaryCpuAbi = null;
7915        } else if (has32BitLibs && has64BitLibs) {
7916            // The application has both 64 and 32 bit bundled libraries. We check
7917            // here that the app declares multiArch support, and warn if it doesn't.
7918            //
7919            // We will be lenient here and record both ABIs. The primary will be the
7920            // ABI that's higher on the list, i.e, a device that's configured to prefer
7921            // 64 bit apps will see a 64 bit primary ABI,
7922
7923            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7924                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7925            }
7926
7927            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7928                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7929                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7930            } else {
7931                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7932                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7933            }
7934        } else {
7935            pkg.applicationInfo.primaryCpuAbi = null;
7936            pkg.applicationInfo.secondaryCpuAbi = null;
7937        }
7938    }
7939
7940    private void killApplication(String pkgName, int appId, String reason) {
7941        // Request the ActivityManager to kill the process(only for existing packages)
7942        // so that we do not end up in a confused state while the user is still using the older
7943        // version of the application while the new one gets installed.
7944        IActivityManager am = ActivityManagerNative.getDefault();
7945        if (am != null) {
7946            try {
7947                am.killApplicationWithAppId(pkgName, appId, reason);
7948            } catch (RemoteException e) {
7949            }
7950        }
7951    }
7952
7953    void removePackageLI(PackageSetting ps, boolean chatty) {
7954        if (DEBUG_INSTALL) {
7955            if (chatty)
7956                Log.d(TAG, "Removing package " + ps.name);
7957        }
7958
7959        // writer
7960        synchronized (mPackages) {
7961            mPackages.remove(ps.name);
7962            final PackageParser.Package pkg = ps.pkg;
7963            if (pkg != null) {
7964                cleanPackageDataStructuresLILPw(pkg, chatty);
7965            }
7966        }
7967    }
7968
7969    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7970        if (DEBUG_INSTALL) {
7971            if (chatty)
7972                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7973        }
7974
7975        // writer
7976        synchronized (mPackages) {
7977            mPackages.remove(pkg.applicationInfo.packageName);
7978            cleanPackageDataStructuresLILPw(pkg, chatty);
7979        }
7980    }
7981
7982    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7983        int N = pkg.providers.size();
7984        StringBuilder r = null;
7985        int i;
7986        for (i=0; i<N; i++) {
7987            PackageParser.Provider p = pkg.providers.get(i);
7988            mProviders.removeProvider(p);
7989            if (p.info.authority == null) {
7990
7991                /* There was another ContentProvider with this authority when
7992                 * this app was installed so this authority is null,
7993                 * Ignore it as we don't have to unregister the provider.
7994                 */
7995                continue;
7996            }
7997            String names[] = p.info.authority.split(";");
7998            for (int j = 0; j < names.length; j++) {
7999                if (mProvidersByAuthority.get(names[j]) == p) {
8000                    mProvidersByAuthority.remove(names[j]);
8001                    if (DEBUG_REMOVE) {
8002                        if (chatty)
8003                            Log.d(TAG, "Unregistered content provider: " + names[j]
8004                                    + ", className = " + p.info.name + ", isSyncable = "
8005                                    + p.info.isSyncable);
8006                    }
8007                }
8008            }
8009            if (DEBUG_REMOVE && chatty) {
8010                if (r == null) {
8011                    r = new StringBuilder(256);
8012                } else {
8013                    r.append(' ');
8014                }
8015                r.append(p.info.name);
8016            }
8017        }
8018        if (r != null) {
8019            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8020        }
8021
8022        N = pkg.services.size();
8023        r = null;
8024        for (i=0; i<N; i++) {
8025            PackageParser.Service s = pkg.services.get(i);
8026            mServices.removeService(s);
8027            if (chatty) {
8028                if (r == null) {
8029                    r = new StringBuilder(256);
8030                } else {
8031                    r.append(' ');
8032                }
8033                r.append(s.info.name);
8034            }
8035        }
8036        if (r != null) {
8037            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8038        }
8039
8040        N = pkg.receivers.size();
8041        r = null;
8042        for (i=0; i<N; i++) {
8043            PackageParser.Activity a = pkg.receivers.get(i);
8044            mReceivers.removeActivity(a, "receiver");
8045            if (DEBUG_REMOVE && chatty) {
8046                if (r == null) {
8047                    r = new StringBuilder(256);
8048                } else {
8049                    r.append(' ');
8050                }
8051                r.append(a.info.name);
8052            }
8053        }
8054        if (r != null) {
8055            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8056        }
8057
8058        N = pkg.activities.size();
8059        r = null;
8060        for (i=0; i<N; i++) {
8061            PackageParser.Activity a = pkg.activities.get(i);
8062            mActivities.removeActivity(a, "activity");
8063            if (DEBUG_REMOVE && chatty) {
8064                if (r == null) {
8065                    r = new StringBuilder(256);
8066                } else {
8067                    r.append(' ');
8068                }
8069                r.append(a.info.name);
8070            }
8071        }
8072        if (r != null) {
8073            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8074        }
8075
8076        N = pkg.permissions.size();
8077        r = null;
8078        for (i=0; i<N; i++) {
8079            PackageParser.Permission p = pkg.permissions.get(i);
8080            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8081            if (bp == null) {
8082                bp = mSettings.mPermissionTrees.get(p.info.name);
8083            }
8084            if (bp != null && bp.perm == p) {
8085                bp.perm = null;
8086                if (DEBUG_REMOVE && chatty) {
8087                    if (r == null) {
8088                        r = new StringBuilder(256);
8089                    } else {
8090                        r.append(' ');
8091                    }
8092                    r.append(p.info.name);
8093                }
8094            }
8095            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8096                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8097                if (appOpPerms != null) {
8098                    appOpPerms.remove(pkg.packageName);
8099                }
8100            }
8101        }
8102        if (r != null) {
8103            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8104        }
8105
8106        N = pkg.requestedPermissions.size();
8107        r = null;
8108        for (i=0; i<N; i++) {
8109            String perm = pkg.requestedPermissions.get(i);
8110            BasePermission bp = mSettings.mPermissions.get(perm);
8111            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8112                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8113                if (appOpPerms != null) {
8114                    appOpPerms.remove(pkg.packageName);
8115                    if (appOpPerms.isEmpty()) {
8116                        mAppOpPermissionPackages.remove(perm);
8117                    }
8118                }
8119            }
8120        }
8121        if (r != null) {
8122            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8123        }
8124
8125        N = pkg.instrumentation.size();
8126        r = null;
8127        for (i=0; i<N; i++) {
8128            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8129            mInstrumentation.remove(a.getComponentName());
8130            if (DEBUG_REMOVE && chatty) {
8131                if (r == null) {
8132                    r = new StringBuilder(256);
8133                } else {
8134                    r.append(' ');
8135                }
8136                r.append(a.info.name);
8137            }
8138        }
8139        if (r != null) {
8140            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8141        }
8142
8143        r = null;
8144        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8145            // Only system apps can hold shared libraries.
8146            if (pkg.libraryNames != null) {
8147                for (i=0; i<pkg.libraryNames.size(); i++) {
8148                    String name = pkg.libraryNames.get(i);
8149                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8150                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8151                        mSharedLibraries.remove(name);
8152                        if (DEBUG_REMOVE && chatty) {
8153                            if (r == null) {
8154                                r = new StringBuilder(256);
8155                            } else {
8156                                r.append(' ');
8157                            }
8158                            r.append(name);
8159                        }
8160                    }
8161                }
8162            }
8163        }
8164        if (r != null) {
8165            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8166        }
8167    }
8168
8169    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8170        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8171            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8172                return true;
8173            }
8174        }
8175        return false;
8176    }
8177
8178    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8179    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8180    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8181
8182    private void updatePermissionsLPw(String changingPkg,
8183            PackageParser.Package pkgInfo, int flags) {
8184        // Make sure there are no dangling permission trees.
8185        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8186        while (it.hasNext()) {
8187            final BasePermission bp = it.next();
8188            if (bp.packageSetting == null) {
8189                // We may not yet have parsed the package, so just see if
8190                // we still know about its settings.
8191                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8192            }
8193            if (bp.packageSetting == null) {
8194                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8195                        + " from package " + bp.sourcePackage);
8196                it.remove();
8197            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8198                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8199                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8200                            + " from package " + bp.sourcePackage);
8201                    flags |= UPDATE_PERMISSIONS_ALL;
8202                    it.remove();
8203                }
8204            }
8205        }
8206
8207        // Make sure all dynamic permissions have been assigned to a package,
8208        // and make sure there are no dangling permissions.
8209        it = mSettings.mPermissions.values().iterator();
8210        while (it.hasNext()) {
8211            final BasePermission bp = it.next();
8212            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8213                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8214                        + bp.name + " pkg=" + bp.sourcePackage
8215                        + " info=" + bp.pendingInfo);
8216                if (bp.packageSetting == null && bp.pendingInfo != null) {
8217                    final BasePermission tree = findPermissionTreeLP(bp.name);
8218                    if (tree != null && tree.perm != null) {
8219                        bp.packageSetting = tree.packageSetting;
8220                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8221                                new PermissionInfo(bp.pendingInfo));
8222                        bp.perm.info.packageName = tree.perm.info.packageName;
8223                        bp.perm.info.name = bp.name;
8224                        bp.uid = tree.uid;
8225                    }
8226                }
8227            }
8228            if (bp.packageSetting == null) {
8229                // We may not yet have parsed the package, so just see if
8230                // we still know about its settings.
8231                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8232            }
8233            if (bp.packageSetting == null) {
8234                Slog.w(TAG, "Removing dangling permission: " + bp.name
8235                        + " from package " + bp.sourcePackage);
8236                it.remove();
8237            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8238                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8239                    Slog.i(TAG, "Removing old permission: " + bp.name
8240                            + " from package " + bp.sourcePackage);
8241                    flags |= UPDATE_PERMISSIONS_ALL;
8242                    it.remove();
8243                }
8244            }
8245        }
8246
8247        // Now update the permissions for all packages, in particular
8248        // replace the granted permissions of the system packages.
8249        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8250            for (PackageParser.Package pkg : mPackages.values()) {
8251                if (pkg != pkgInfo) {
8252                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8253                            changingPkg);
8254                }
8255            }
8256        }
8257
8258        if (pkgInfo != null) {
8259            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8260        }
8261    }
8262
8263    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8264            String packageOfInterest) {
8265        // IMPORTANT: There are two types of permissions: install and runtime.
8266        // Install time permissions are granted when the app is installed to
8267        // all device users and users added in the future. Runtime permissions
8268        // are granted at runtime explicitly to specific users. Normal and signature
8269        // protected permissions are install time permissions. Dangerous permissions
8270        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8271        // otherwise they are runtime permissions. This function does not manage
8272        // runtime permissions except for the case an app targeting Lollipop MR1
8273        // being upgraded to target a newer SDK, in which case dangerous permissions
8274        // are transformed from install time to runtime ones.
8275
8276        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8277        if (ps == null) {
8278            return;
8279        }
8280
8281        PermissionsState permissionsState = ps.getPermissionsState();
8282        PermissionsState origPermissions = permissionsState;
8283
8284        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8285
8286        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8287
8288        boolean changedInstallPermission = false;
8289
8290        if (replace) {
8291            ps.installPermissionsFixed = false;
8292            if (!ps.isSharedUser()) {
8293                origPermissions = new PermissionsState(permissionsState);
8294                permissionsState.reset();
8295            }
8296        }
8297
8298        permissionsState.setGlobalGids(mGlobalGids);
8299
8300        final int N = pkg.requestedPermissions.size();
8301        for (int i=0; i<N; i++) {
8302            final String name = pkg.requestedPermissions.get(i);
8303            final BasePermission bp = mSettings.mPermissions.get(name);
8304
8305            if (DEBUG_INSTALL) {
8306                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8307            }
8308
8309            if (bp == null || bp.packageSetting == null) {
8310                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8311                    Slog.w(TAG, "Unknown permission " + name
8312                            + " in package " + pkg.packageName);
8313                }
8314                continue;
8315            }
8316
8317            final String perm = bp.name;
8318            boolean allowedSig = false;
8319            int grant = GRANT_DENIED;
8320
8321            // Keep track of app op permissions.
8322            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8323                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8324                if (pkgs == null) {
8325                    pkgs = new ArraySet<>();
8326                    mAppOpPermissionPackages.put(bp.name, pkgs);
8327                }
8328                pkgs.add(pkg.packageName);
8329            }
8330
8331            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8332            switch (level) {
8333                case PermissionInfo.PROTECTION_NORMAL: {
8334                    // For all apps normal permissions are install time ones.
8335                    grant = GRANT_INSTALL;
8336                } break;
8337
8338                case PermissionInfo.PROTECTION_DANGEROUS: {
8339                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8340                        // For legacy apps dangerous permissions are install time ones.
8341                        grant = GRANT_INSTALL_LEGACY;
8342                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8343                        // For legacy apps that became modern, install becomes runtime.
8344                        grant = GRANT_UPGRADE;
8345                    } else {
8346                        // For modern apps keep runtime permissions unchanged.
8347                        grant = GRANT_RUNTIME;
8348                    }
8349                } break;
8350
8351                case PermissionInfo.PROTECTION_SIGNATURE: {
8352                    // For all apps signature permissions are install time ones.
8353                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8354                    if (allowedSig) {
8355                        grant = GRANT_INSTALL;
8356                    }
8357                } break;
8358            }
8359
8360            if (DEBUG_INSTALL) {
8361                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8362            }
8363
8364            if (grant != GRANT_DENIED) {
8365                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8366                    // If this is an existing, non-system package, then
8367                    // we can't add any new permissions to it.
8368                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8369                        // Except...  if this is a permission that was added
8370                        // to the platform (note: need to only do this when
8371                        // updating the platform).
8372                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8373                            grant = GRANT_DENIED;
8374                        }
8375                    }
8376                }
8377
8378                switch (grant) {
8379                    case GRANT_INSTALL: {
8380                        // Revoke this as runtime permission to handle the case of
8381                        // a runtime permission being downgraded to an install one.
8382                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8383                            if (origPermissions.getRuntimePermissionState(
8384                                    bp.name, userId) != null) {
8385                                // Revoke the runtime permission and clear the flags.
8386                                origPermissions.revokeRuntimePermission(bp, userId);
8387                                origPermissions.updatePermissionFlags(bp, userId,
8388                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8389                                // If we revoked a permission permission, we have to write.
8390                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8391                                        changedRuntimePermissionUserIds, userId);
8392                            }
8393                        }
8394                        // Grant an install permission.
8395                        if (permissionsState.grantInstallPermission(bp) !=
8396                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8397                            changedInstallPermission = true;
8398                        }
8399                    } break;
8400
8401                    case GRANT_INSTALL_LEGACY: {
8402                        // Grant an install permission.
8403                        if (permissionsState.grantInstallPermission(bp) !=
8404                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8405                            changedInstallPermission = true;
8406                        }
8407                    } break;
8408
8409                    case GRANT_RUNTIME: {
8410                        // Grant previously granted runtime permissions.
8411                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8412                            PermissionState permissionState = origPermissions
8413                                    .getRuntimePermissionState(bp.name, userId);
8414                            final int flags = permissionState != null
8415                                    ? permissionState.getFlags() : 0;
8416                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8417                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8418                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8419                                    // If we cannot put the permission as it was, we have to write.
8420                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8421                                            changedRuntimePermissionUserIds, userId);
8422                                }
8423                            }
8424                            // Propagate the permission flags.
8425                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8426                        }
8427                    } break;
8428
8429                    case GRANT_UPGRADE: {
8430                        // Grant runtime permissions for a previously held install permission.
8431                        PermissionState permissionState = origPermissions
8432                                .getInstallPermissionState(bp.name);
8433                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8434
8435                        if (origPermissions.revokeInstallPermission(bp)
8436                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8437                            // We will be transferring the permission flags, so clear them.
8438                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8439                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8440                            changedInstallPermission = true;
8441                        }
8442
8443                        // If the permission is not to be promoted to runtime we ignore it and
8444                        // also its other flags as they are not applicable to install permissions.
8445                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8446                            for (int userId : currentUserIds) {
8447                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8448                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8449                                    // Transfer the permission flags.
8450                                    permissionsState.updatePermissionFlags(bp, userId,
8451                                            flags, flags);
8452                                    // If we granted the permission, we have to write.
8453                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8454                                            changedRuntimePermissionUserIds, userId);
8455                                }
8456                            }
8457                        }
8458                    } break;
8459
8460                    default: {
8461                        if (packageOfInterest == null
8462                                || packageOfInterest.equals(pkg.packageName)) {
8463                            Slog.w(TAG, "Not granting permission " + perm
8464                                    + " to package " + pkg.packageName
8465                                    + " because it was previously installed without");
8466                        }
8467                    } break;
8468                }
8469            } else {
8470                if (permissionsState.revokeInstallPermission(bp) !=
8471                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8472                    // Also drop the permission flags.
8473                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8474                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8475                    changedInstallPermission = true;
8476                    Slog.i(TAG, "Un-granting permission " + perm
8477                            + " from package " + pkg.packageName
8478                            + " (protectionLevel=" + bp.protectionLevel
8479                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8480                            + ")");
8481                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8482                    // Don't print warning for app op permissions, since it is fine for them
8483                    // not to be granted, there is a UI for the user to decide.
8484                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8485                        Slog.w(TAG, "Not granting permission " + perm
8486                                + " to package " + pkg.packageName
8487                                + " (protectionLevel=" + bp.protectionLevel
8488                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8489                                + ")");
8490                    }
8491                }
8492            }
8493        }
8494
8495        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8496                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8497            // This is the first that we have heard about this package, so the
8498            // permissions we have now selected are fixed until explicitly
8499            // changed.
8500            ps.installPermissionsFixed = true;
8501        }
8502
8503        // Persist the runtime permissions state for users with changes.
8504        for (int userId : changedRuntimePermissionUserIds) {
8505            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8506        }
8507    }
8508
8509    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8510        boolean allowed = false;
8511        final int NP = PackageParser.NEW_PERMISSIONS.length;
8512        for (int ip=0; ip<NP; ip++) {
8513            final PackageParser.NewPermissionInfo npi
8514                    = PackageParser.NEW_PERMISSIONS[ip];
8515            if (npi.name.equals(perm)
8516                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8517                allowed = true;
8518                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8519                        + pkg.packageName);
8520                break;
8521            }
8522        }
8523        return allowed;
8524    }
8525
8526    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8527            BasePermission bp, PermissionsState origPermissions) {
8528        boolean allowed;
8529        allowed = (compareSignatures(
8530                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8531                        == PackageManager.SIGNATURE_MATCH)
8532                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8533                        == PackageManager.SIGNATURE_MATCH);
8534        if (!allowed && (bp.protectionLevel
8535                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8536            if (isSystemApp(pkg)) {
8537                // For updated system applications, a system permission
8538                // is granted only if it had been defined by the original application.
8539                if (pkg.isUpdatedSystemApp()) {
8540                    final PackageSetting sysPs = mSettings
8541                            .getDisabledSystemPkgLPr(pkg.packageName);
8542                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8543                        // If the original was granted this permission, we take
8544                        // that grant decision as read and propagate it to the
8545                        // update.
8546                        if (sysPs.isPrivileged()) {
8547                            allowed = true;
8548                        }
8549                    } else {
8550                        // The system apk may have been updated with an older
8551                        // version of the one on the data partition, but which
8552                        // granted a new system permission that it didn't have
8553                        // before.  In this case we do want to allow the app to
8554                        // now get the new permission if the ancestral apk is
8555                        // privileged to get it.
8556                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8557                            for (int j=0;
8558                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8559                                if (perm.equals(
8560                                        sysPs.pkg.requestedPermissions.get(j))) {
8561                                    allowed = true;
8562                                    break;
8563                                }
8564                            }
8565                        }
8566                    }
8567                } else {
8568                    allowed = isPrivilegedApp(pkg);
8569                }
8570            }
8571        }
8572        if (!allowed) {
8573            if (!allowed && (bp.protectionLevel
8574                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8575                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8576                // If this was a previously normal/dangerous permission that got moved
8577                // to a system permission as part of the runtime permission redesign, then
8578                // we still want to blindly grant it to old apps.
8579                allowed = true;
8580            }
8581            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8582                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8583                // If this permission is to be granted to the system installer and
8584                // this app is an installer, then it gets the permission.
8585                allowed = true;
8586            }
8587            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8588                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8589                // If this permission is to be granted to the system verifier and
8590                // this app is a verifier, then it gets the permission.
8591                allowed = true;
8592            }
8593            if (!allowed && (bp.protectionLevel
8594                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8595                    && isSystemApp(pkg)) {
8596                // Any pre-installed system app is allowed to get this permission.
8597                allowed = true;
8598            }
8599            if (!allowed && (bp.protectionLevel
8600                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8601                // For development permissions, a development permission
8602                // is granted only if it was already granted.
8603                allowed = origPermissions.hasInstallPermission(perm);
8604            }
8605        }
8606        return allowed;
8607    }
8608
8609    final class ActivityIntentResolver
8610            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8611        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8612                boolean defaultOnly, int userId) {
8613            if (!sUserManager.exists(userId)) return null;
8614            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8615            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8616        }
8617
8618        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8619                int userId) {
8620            if (!sUserManager.exists(userId)) return null;
8621            mFlags = flags;
8622            return super.queryIntent(intent, resolvedType,
8623                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8624        }
8625
8626        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8627                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8628            if (!sUserManager.exists(userId)) return null;
8629            if (packageActivities == null) {
8630                return null;
8631            }
8632            mFlags = flags;
8633            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8634            final int N = packageActivities.size();
8635            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8636                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8637
8638            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8639            for (int i = 0; i < N; ++i) {
8640                intentFilters = packageActivities.get(i).intents;
8641                if (intentFilters != null && intentFilters.size() > 0) {
8642                    PackageParser.ActivityIntentInfo[] array =
8643                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8644                    intentFilters.toArray(array);
8645                    listCut.add(array);
8646                }
8647            }
8648            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8649        }
8650
8651        public final void addActivity(PackageParser.Activity a, String type) {
8652            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8653            mActivities.put(a.getComponentName(), a);
8654            if (DEBUG_SHOW_INFO)
8655                Log.v(
8656                TAG, "  " + type + " " +
8657                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8658            if (DEBUG_SHOW_INFO)
8659                Log.v(TAG, "    Class=" + a.info.name);
8660            final int NI = a.intents.size();
8661            for (int j=0; j<NI; j++) {
8662                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8663                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8664                    intent.setPriority(0);
8665                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8666                            + a.className + " with priority > 0, forcing to 0");
8667                }
8668                if (DEBUG_SHOW_INFO) {
8669                    Log.v(TAG, "    IntentFilter:");
8670                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8671                }
8672                if (!intent.debugCheck()) {
8673                    Log.w(TAG, "==> For Activity " + a.info.name);
8674                }
8675                addFilter(intent);
8676            }
8677        }
8678
8679        public final void removeActivity(PackageParser.Activity a, String type) {
8680            mActivities.remove(a.getComponentName());
8681            if (DEBUG_SHOW_INFO) {
8682                Log.v(TAG, "  " + type + " "
8683                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8684                                : a.info.name) + ":");
8685                Log.v(TAG, "    Class=" + a.info.name);
8686            }
8687            final int NI = a.intents.size();
8688            for (int j=0; j<NI; j++) {
8689                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8690                if (DEBUG_SHOW_INFO) {
8691                    Log.v(TAG, "    IntentFilter:");
8692                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8693                }
8694                removeFilter(intent);
8695            }
8696        }
8697
8698        @Override
8699        protected boolean allowFilterResult(
8700                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8701            ActivityInfo filterAi = filter.activity.info;
8702            for (int i=dest.size()-1; i>=0; i--) {
8703                ActivityInfo destAi = dest.get(i).activityInfo;
8704                if (destAi.name == filterAi.name
8705                        && destAi.packageName == filterAi.packageName) {
8706                    return false;
8707                }
8708            }
8709            return true;
8710        }
8711
8712        @Override
8713        protected ActivityIntentInfo[] newArray(int size) {
8714            return new ActivityIntentInfo[size];
8715        }
8716
8717        @Override
8718        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8719            if (!sUserManager.exists(userId)) return true;
8720            PackageParser.Package p = filter.activity.owner;
8721            if (p != null) {
8722                PackageSetting ps = (PackageSetting)p.mExtras;
8723                if (ps != null) {
8724                    // System apps are never considered stopped for purposes of
8725                    // filtering, because there may be no way for the user to
8726                    // actually re-launch them.
8727                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8728                            && ps.getStopped(userId);
8729                }
8730            }
8731            return false;
8732        }
8733
8734        @Override
8735        protected boolean isPackageForFilter(String packageName,
8736                PackageParser.ActivityIntentInfo info) {
8737            return packageName.equals(info.activity.owner.packageName);
8738        }
8739
8740        @Override
8741        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8742                int match, int userId) {
8743            if (!sUserManager.exists(userId)) return null;
8744            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8745                return null;
8746            }
8747            final PackageParser.Activity activity = info.activity;
8748            if (mSafeMode && (activity.info.applicationInfo.flags
8749                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8750                return null;
8751            }
8752            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8753            if (ps == null) {
8754                return null;
8755            }
8756            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8757                    ps.readUserState(userId), userId);
8758            if (ai == null) {
8759                return null;
8760            }
8761            final ResolveInfo res = new ResolveInfo();
8762            res.activityInfo = ai;
8763            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8764                res.filter = info;
8765            }
8766            if (info != null) {
8767                res.handleAllWebDataURI = info.handleAllWebDataURI();
8768            }
8769            res.priority = info.getPriority();
8770            res.preferredOrder = activity.owner.mPreferredOrder;
8771            //System.out.println("Result: " + res.activityInfo.className +
8772            //                   " = " + res.priority);
8773            res.match = match;
8774            res.isDefault = info.hasDefault;
8775            res.labelRes = info.labelRes;
8776            res.nonLocalizedLabel = info.nonLocalizedLabel;
8777            if (userNeedsBadging(userId)) {
8778                res.noResourceId = true;
8779            } else {
8780                res.icon = info.icon;
8781            }
8782            res.iconResourceId = info.icon;
8783            res.system = res.activityInfo.applicationInfo.isSystemApp();
8784            return res;
8785        }
8786
8787        @Override
8788        protected void sortResults(List<ResolveInfo> results) {
8789            Collections.sort(results, mResolvePrioritySorter);
8790        }
8791
8792        @Override
8793        protected void dumpFilter(PrintWriter out, String prefix,
8794                PackageParser.ActivityIntentInfo filter) {
8795            out.print(prefix); out.print(
8796                    Integer.toHexString(System.identityHashCode(filter.activity)));
8797                    out.print(' ');
8798                    filter.activity.printComponentShortName(out);
8799                    out.print(" filter ");
8800                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8801        }
8802
8803        @Override
8804        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8805            return filter.activity;
8806        }
8807
8808        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8809            PackageParser.Activity activity = (PackageParser.Activity)label;
8810            out.print(prefix); out.print(
8811                    Integer.toHexString(System.identityHashCode(activity)));
8812                    out.print(' ');
8813                    activity.printComponentShortName(out);
8814            if (count > 1) {
8815                out.print(" ("); out.print(count); out.print(" filters)");
8816            }
8817            out.println();
8818        }
8819
8820//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8821//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8822//            final List<ResolveInfo> retList = Lists.newArrayList();
8823//            while (i.hasNext()) {
8824//                final ResolveInfo resolveInfo = i.next();
8825//                if (isEnabledLP(resolveInfo.activityInfo)) {
8826//                    retList.add(resolveInfo);
8827//                }
8828//            }
8829//            return retList;
8830//        }
8831
8832        // Keys are String (activity class name), values are Activity.
8833        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8834                = new ArrayMap<ComponentName, PackageParser.Activity>();
8835        private int mFlags;
8836    }
8837
8838    private final class ServiceIntentResolver
8839            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8840        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8841                boolean defaultOnly, int userId) {
8842            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8843            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8844        }
8845
8846        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8847                int userId) {
8848            if (!sUserManager.exists(userId)) return null;
8849            mFlags = flags;
8850            return super.queryIntent(intent, resolvedType,
8851                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8852        }
8853
8854        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8855                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8856            if (!sUserManager.exists(userId)) return null;
8857            if (packageServices == null) {
8858                return null;
8859            }
8860            mFlags = flags;
8861            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8862            final int N = packageServices.size();
8863            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8864                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8865
8866            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8867            for (int i = 0; i < N; ++i) {
8868                intentFilters = packageServices.get(i).intents;
8869                if (intentFilters != null && intentFilters.size() > 0) {
8870                    PackageParser.ServiceIntentInfo[] array =
8871                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8872                    intentFilters.toArray(array);
8873                    listCut.add(array);
8874                }
8875            }
8876            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8877        }
8878
8879        public final void addService(PackageParser.Service s) {
8880            mServices.put(s.getComponentName(), s);
8881            if (DEBUG_SHOW_INFO) {
8882                Log.v(TAG, "  "
8883                        + (s.info.nonLocalizedLabel != null
8884                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8885                Log.v(TAG, "    Class=" + s.info.name);
8886            }
8887            final int NI = s.intents.size();
8888            int j;
8889            for (j=0; j<NI; j++) {
8890                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8891                if (DEBUG_SHOW_INFO) {
8892                    Log.v(TAG, "    IntentFilter:");
8893                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8894                }
8895                if (!intent.debugCheck()) {
8896                    Log.w(TAG, "==> For Service " + s.info.name);
8897                }
8898                addFilter(intent);
8899            }
8900        }
8901
8902        public final void removeService(PackageParser.Service s) {
8903            mServices.remove(s.getComponentName());
8904            if (DEBUG_SHOW_INFO) {
8905                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8906                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8907                Log.v(TAG, "    Class=" + s.info.name);
8908            }
8909            final int NI = s.intents.size();
8910            int j;
8911            for (j=0; j<NI; j++) {
8912                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8913                if (DEBUG_SHOW_INFO) {
8914                    Log.v(TAG, "    IntentFilter:");
8915                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8916                }
8917                removeFilter(intent);
8918            }
8919        }
8920
8921        @Override
8922        protected boolean allowFilterResult(
8923                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8924            ServiceInfo filterSi = filter.service.info;
8925            for (int i=dest.size()-1; i>=0; i--) {
8926                ServiceInfo destAi = dest.get(i).serviceInfo;
8927                if (destAi.name == filterSi.name
8928                        && destAi.packageName == filterSi.packageName) {
8929                    return false;
8930                }
8931            }
8932            return true;
8933        }
8934
8935        @Override
8936        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8937            return new PackageParser.ServiceIntentInfo[size];
8938        }
8939
8940        @Override
8941        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8942            if (!sUserManager.exists(userId)) return true;
8943            PackageParser.Package p = filter.service.owner;
8944            if (p != null) {
8945                PackageSetting ps = (PackageSetting)p.mExtras;
8946                if (ps != null) {
8947                    // System apps are never considered stopped for purposes of
8948                    // filtering, because there may be no way for the user to
8949                    // actually re-launch them.
8950                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8951                            && ps.getStopped(userId);
8952                }
8953            }
8954            return false;
8955        }
8956
8957        @Override
8958        protected boolean isPackageForFilter(String packageName,
8959                PackageParser.ServiceIntentInfo info) {
8960            return packageName.equals(info.service.owner.packageName);
8961        }
8962
8963        @Override
8964        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8965                int match, int userId) {
8966            if (!sUserManager.exists(userId)) return null;
8967            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8968            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8969                return null;
8970            }
8971            final PackageParser.Service service = info.service;
8972            if (mSafeMode && (service.info.applicationInfo.flags
8973                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8974                return null;
8975            }
8976            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8977            if (ps == null) {
8978                return null;
8979            }
8980            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8981                    ps.readUserState(userId), userId);
8982            if (si == null) {
8983                return null;
8984            }
8985            final ResolveInfo res = new ResolveInfo();
8986            res.serviceInfo = si;
8987            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8988                res.filter = filter;
8989            }
8990            res.priority = info.getPriority();
8991            res.preferredOrder = service.owner.mPreferredOrder;
8992            res.match = match;
8993            res.isDefault = info.hasDefault;
8994            res.labelRes = info.labelRes;
8995            res.nonLocalizedLabel = info.nonLocalizedLabel;
8996            res.icon = info.icon;
8997            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8998            return res;
8999        }
9000
9001        @Override
9002        protected void sortResults(List<ResolveInfo> results) {
9003            Collections.sort(results, mResolvePrioritySorter);
9004        }
9005
9006        @Override
9007        protected void dumpFilter(PrintWriter out, String prefix,
9008                PackageParser.ServiceIntentInfo filter) {
9009            out.print(prefix); out.print(
9010                    Integer.toHexString(System.identityHashCode(filter.service)));
9011                    out.print(' ');
9012                    filter.service.printComponentShortName(out);
9013                    out.print(" filter ");
9014                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9015        }
9016
9017        @Override
9018        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9019            return filter.service;
9020        }
9021
9022        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9023            PackageParser.Service service = (PackageParser.Service)label;
9024            out.print(prefix); out.print(
9025                    Integer.toHexString(System.identityHashCode(service)));
9026                    out.print(' ');
9027                    service.printComponentShortName(out);
9028            if (count > 1) {
9029                out.print(" ("); out.print(count); out.print(" filters)");
9030            }
9031            out.println();
9032        }
9033
9034//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9035//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9036//            final List<ResolveInfo> retList = Lists.newArrayList();
9037//            while (i.hasNext()) {
9038//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9039//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9040//                    retList.add(resolveInfo);
9041//                }
9042//            }
9043//            return retList;
9044//        }
9045
9046        // Keys are String (activity class name), values are Activity.
9047        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9048                = new ArrayMap<ComponentName, PackageParser.Service>();
9049        private int mFlags;
9050    };
9051
9052    private final class ProviderIntentResolver
9053            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9054        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9055                boolean defaultOnly, int userId) {
9056            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9057            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9058        }
9059
9060        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9061                int userId) {
9062            if (!sUserManager.exists(userId))
9063                return null;
9064            mFlags = flags;
9065            return super.queryIntent(intent, resolvedType,
9066                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9067        }
9068
9069        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9070                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9071            if (!sUserManager.exists(userId))
9072                return null;
9073            if (packageProviders == null) {
9074                return null;
9075            }
9076            mFlags = flags;
9077            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9078            final int N = packageProviders.size();
9079            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9080                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9081
9082            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9083            for (int i = 0; i < N; ++i) {
9084                intentFilters = packageProviders.get(i).intents;
9085                if (intentFilters != null && intentFilters.size() > 0) {
9086                    PackageParser.ProviderIntentInfo[] array =
9087                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9088                    intentFilters.toArray(array);
9089                    listCut.add(array);
9090                }
9091            }
9092            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9093        }
9094
9095        public final void addProvider(PackageParser.Provider p) {
9096            if (mProviders.containsKey(p.getComponentName())) {
9097                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9098                return;
9099            }
9100
9101            mProviders.put(p.getComponentName(), p);
9102            if (DEBUG_SHOW_INFO) {
9103                Log.v(TAG, "  "
9104                        + (p.info.nonLocalizedLabel != null
9105                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9106                Log.v(TAG, "    Class=" + p.info.name);
9107            }
9108            final int NI = p.intents.size();
9109            int j;
9110            for (j = 0; j < NI; j++) {
9111                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9112                if (DEBUG_SHOW_INFO) {
9113                    Log.v(TAG, "    IntentFilter:");
9114                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9115                }
9116                if (!intent.debugCheck()) {
9117                    Log.w(TAG, "==> For Provider " + p.info.name);
9118                }
9119                addFilter(intent);
9120            }
9121        }
9122
9123        public final void removeProvider(PackageParser.Provider p) {
9124            mProviders.remove(p.getComponentName());
9125            if (DEBUG_SHOW_INFO) {
9126                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9127                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9128                Log.v(TAG, "    Class=" + p.info.name);
9129            }
9130            final int NI = p.intents.size();
9131            int j;
9132            for (j = 0; j < NI; j++) {
9133                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9134                if (DEBUG_SHOW_INFO) {
9135                    Log.v(TAG, "    IntentFilter:");
9136                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9137                }
9138                removeFilter(intent);
9139            }
9140        }
9141
9142        @Override
9143        protected boolean allowFilterResult(
9144                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9145            ProviderInfo filterPi = filter.provider.info;
9146            for (int i = dest.size() - 1; i >= 0; i--) {
9147                ProviderInfo destPi = dest.get(i).providerInfo;
9148                if (destPi.name == filterPi.name
9149                        && destPi.packageName == filterPi.packageName) {
9150                    return false;
9151                }
9152            }
9153            return true;
9154        }
9155
9156        @Override
9157        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9158            return new PackageParser.ProviderIntentInfo[size];
9159        }
9160
9161        @Override
9162        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9163            if (!sUserManager.exists(userId))
9164                return true;
9165            PackageParser.Package p = filter.provider.owner;
9166            if (p != null) {
9167                PackageSetting ps = (PackageSetting) p.mExtras;
9168                if (ps != null) {
9169                    // System apps are never considered stopped for purposes of
9170                    // filtering, because there may be no way for the user to
9171                    // actually re-launch them.
9172                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9173                            && ps.getStopped(userId);
9174                }
9175            }
9176            return false;
9177        }
9178
9179        @Override
9180        protected boolean isPackageForFilter(String packageName,
9181                PackageParser.ProviderIntentInfo info) {
9182            return packageName.equals(info.provider.owner.packageName);
9183        }
9184
9185        @Override
9186        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9187                int match, int userId) {
9188            if (!sUserManager.exists(userId))
9189                return null;
9190            final PackageParser.ProviderIntentInfo info = filter;
9191            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9192                return null;
9193            }
9194            final PackageParser.Provider provider = info.provider;
9195            if (mSafeMode && (provider.info.applicationInfo.flags
9196                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9197                return null;
9198            }
9199            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9200            if (ps == null) {
9201                return null;
9202            }
9203            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9204                    ps.readUserState(userId), userId);
9205            if (pi == null) {
9206                return null;
9207            }
9208            final ResolveInfo res = new ResolveInfo();
9209            res.providerInfo = pi;
9210            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9211                res.filter = filter;
9212            }
9213            res.priority = info.getPriority();
9214            res.preferredOrder = provider.owner.mPreferredOrder;
9215            res.match = match;
9216            res.isDefault = info.hasDefault;
9217            res.labelRes = info.labelRes;
9218            res.nonLocalizedLabel = info.nonLocalizedLabel;
9219            res.icon = info.icon;
9220            res.system = res.providerInfo.applicationInfo.isSystemApp();
9221            return res;
9222        }
9223
9224        @Override
9225        protected void sortResults(List<ResolveInfo> results) {
9226            Collections.sort(results, mResolvePrioritySorter);
9227        }
9228
9229        @Override
9230        protected void dumpFilter(PrintWriter out, String prefix,
9231                PackageParser.ProviderIntentInfo filter) {
9232            out.print(prefix);
9233            out.print(
9234                    Integer.toHexString(System.identityHashCode(filter.provider)));
9235            out.print(' ');
9236            filter.provider.printComponentShortName(out);
9237            out.print(" filter ");
9238            out.println(Integer.toHexString(System.identityHashCode(filter)));
9239        }
9240
9241        @Override
9242        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9243            return filter.provider;
9244        }
9245
9246        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9247            PackageParser.Provider provider = (PackageParser.Provider)label;
9248            out.print(prefix); out.print(
9249                    Integer.toHexString(System.identityHashCode(provider)));
9250                    out.print(' ');
9251                    provider.printComponentShortName(out);
9252            if (count > 1) {
9253                out.print(" ("); out.print(count); out.print(" filters)");
9254            }
9255            out.println();
9256        }
9257
9258        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9259                = new ArrayMap<ComponentName, PackageParser.Provider>();
9260        private int mFlags;
9261    };
9262
9263    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9264            new Comparator<ResolveInfo>() {
9265        public int compare(ResolveInfo r1, ResolveInfo r2) {
9266            int v1 = r1.priority;
9267            int v2 = r2.priority;
9268            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9269            if (v1 != v2) {
9270                return (v1 > v2) ? -1 : 1;
9271            }
9272            v1 = r1.preferredOrder;
9273            v2 = r2.preferredOrder;
9274            if (v1 != v2) {
9275                return (v1 > v2) ? -1 : 1;
9276            }
9277            if (r1.isDefault != r2.isDefault) {
9278                return r1.isDefault ? -1 : 1;
9279            }
9280            v1 = r1.match;
9281            v2 = r2.match;
9282            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9283            if (v1 != v2) {
9284                return (v1 > v2) ? -1 : 1;
9285            }
9286            if (r1.system != r2.system) {
9287                return r1.system ? -1 : 1;
9288            }
9289            return 0;
9290        }
9291    };
9292
9293    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9294            new Comparator<ProviderInfo>() {
9295        public int compare(ProviderInfo p1, ProviderInfo p2) {
9296            final int v1 = p1.initOrder;
9297            final int v2 = p2.initOrder;
9298            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9299        }
9300    };
9301
9302    final void sendPackageBroadcast(final String action, final String pkg,
9303            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9304            final int[] userIds) {
9305        mHandler.post(new Runnable() {
9306            @Override
9307            public void run() {
9308                try {
9309                    final IActivityManager am = ActivityManagerNative.getDefault();
9310                    if (am == null) return;
9311                    final int[] resolvedUserIds;
9312                    if (userIds == null) {
9313                        resolvedUserIds = am.getRunningUserIds();
9314                    } else {
9315                        resolvedUserIds = userIds;
9316                    }
9317                    for (int id : resolvedUserIds) {
9318                        final Intent intent = new Intent(action,
9319                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9320                        if (extras != null) {
9321                            intent.putExtras(extras);
9322                        }
9323                        if (targetPkg != null) {
9324                            intent.setPackage(targetPkg);
9325                        }
9326                        // Modify the UID when posting to other users
9327                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9328                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9329                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9330                            intent.putExtra(Intent.EXTRA_UID, uid);
9331                        }
9332                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9333                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9334                        if (DEBUG_BROADCASTS) {
9335                            RuntimeException here = new RuntimeException("here");
9336                            here.fillInStackTrace();
9337                            Slog.d(TAG, "Sending to user " + id + ": "
9338                                    + intent.toShortString(false, true, false, false)
9339                                    + " " + intent.getExtras(), here);
9340                        }
9341                        am.broadcastIntent(null, intent, null, finishedReceiver,
9342                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9343                                null, finishedReceiver != null, false, id);
9344                    }
9345                } catch (RemoteException ex) {
9346                }
9347            }
9348        });
9349    }
9350
9351    /**
9352     * Check if the external storage media is available. This is true if there
9353     * is a mounted external storage medium or if the external storage is
9354     * emulated.
9355     */
9356    private boolean isExternalMediaAvailable() {
9357        return mMediaMounted || Environment.isExternalStorageEmulated();
9358    }
9359
9360    @Override
9361    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9362        // writer
9363        synchronized (mPackages) {
9364            if (!isExternalMediaAvailable()) {
9365                // If the external storage is no longer mounted at this point,
9366                // the caller may not have been able to delete all of this
9367                // packages files and can not delete any more.  Bail.
9368                return null;
9369            }
9370            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9371            if (lastPackage != null) {
9372                pkgs.remove(lastPackage);
9373            }
9374            if (pkgs.size() > 0) {
9375                return pkgs.get(0);
9376            }
9377        }
9378        return null;
9379    }
9380
9381    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9382        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9383                userId, andCode ? 1 : 0, packageName);
9384        if (mSystemReady) {
9385            msg.sendToTarget();
9386        } else {
9387            if (mPostSystemReadyMessages == null) {
9388                mPostSystemReadyMessages = new ArrayList<>();
9389            }
9390            mPostSystemReadyMessages.add(msg);
9391        }
9392    }
9393
9394    void startCleaningPackages() {
9395        // reader
9396        synchronized (mPackages) {
9397            if (!isExternalMediaAvailable()) {
9398                return;
9399            }
9400            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9401                return;
9402            }
9403        }
9404        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9405        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9406        IActivityManager am = ActivityManagerNative.getDefault();
9407        if (am != null) {
9408            try {
9409                am.startService(null, intent, null, mContext.getOpPackageName(),
9410                        UserHandle.USER_OWNER);
9411            } catch (RemoteException e) {
9412            }
9413        }
9414    }
9415
9416    @Override
9417    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9418            int installFlags, String installerPackageName, VerificationParams verificationParams,
9419            String packageAbiOverride) {
9420        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9421                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9422    }
9423
9424    @Override
9425    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9426            int installFlags, String installerPackageName, VerificationParams verificationParams,
9427            String packageAbiOverride, int userId) {
9428        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9429
9430        final int callingUid = Binder.getCallingUid();
9431        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9432
9433        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9434            try {
9435                if (observer != null) {
9436                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9437                }
9438            } catch (RemoteException re) {
9439            }
9440            return;
9441        }
9442
9443        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9444            installFlags |= PackageManager.INSTALL_FROM_ADB;
9445
9446        } else {
9447            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9448            // about installerPackageName.
9449
9450            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9451            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9452        }
9453
9454        UserHandle user;
9455        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9456            user = UserHandle.ALL;
9457        } else {
9458            user = new UserHandle(userId);
9459        }
9460
9461        // Only system components can circumvent runtime permissions when installing.
9462        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9463                && mContext.checkCallingOrSelfPermission(Manifest.permission
9464                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9465            throw new SecurityException("You need the "
9466                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9467                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9468        }
9469
9470        verificationParams.setInstallerUid(callingUid);
9471
9472        final File originFile = new File(originPath);
9473        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9474
9475        final Message msg = mHandler.obtainMessage(INIT_COPY);
9476        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9477                null, verificationParams, user, packageAbiOverride, null);
9478        mHandler.sendMessage(msg);
9479    }
9480
9481    void installStage(String packageName, File stagedDir, String stagedCid,
9482            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9483            String installerPackageName, int installerUid, UserHandle user) {
9484        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9485                params.referrerUri, installerUid, null);
9486        verifParams.setInstallerUid(installerUid);
9487
9488        final OriginInfo origin;
9489        if (stagedDir != null) {
9490            origin = OriginInfo.fromStagedFile(stagedDir);
9491        } else {
9492            origin = OriginInfo.fromStagedContainer(stagedCid);
9493        }
9494
9495        final Message msg = mHandler.obtainMessage(INIT_COPY);
9496        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9497                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9498                params.grantedRuntimePermissions);
9499        mHandler.sendMessage(msg);
9500    }
9501
9502    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9503        Bundle extras = new Bundle(1);
9504        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9505
9506        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9507                packageName, extras, null, null, new int[] {userId});
9508        try {
9509            IActivityManager am = ActivityManagerNative.getDefault();
9510            final boolean isSystem =
9511                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9512            if (isSystem && am.isUserRunning(userId, false)) {
9513                // The just-installed/enabled app is bundled on the system, so presumed
9514                // to be able to run automatically without needing an explicit launch.
9515                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9516                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9517                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9518                        .setPackage(packageName);
9519                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9520                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9521            }
9522        } catch (RemoteException e) {
9523            // shouldn't happen
9524            Slog.w(TAG, "Unable to bootstrap installed package", e);
9525        }
9526    }
9527
9528    @Override
9529    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9530            int userId) {
9531        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9532        PackageSetting pkgSetting;
9533        final int uid = Binder.getCallingUid();
9534        enforceCrossUserPermission(uid, userId, true, true,
9535                "setApplicationHiddenSetting for user " + userId);
9536
9537        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9538            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9539            return false;
9540        }
9541
9542        long callingId = Binder.clearCallingIdentity();
9543        try {
9544            boolean sendAdded = false;
9545            boolean sendRemoved = false;
9546            // writer
9547            synchronized (mPackages) {
9548                pkgSetting = mSettings.mPackages.get(packageName);
9549                if (pkgSetting == null) {
9550                    return false;
9551                }
9552                if (pkgSetting.getHidden(userId) != hidden) {
9553                    pkgSetting.setHidden(hidden, userId);
9554                    mSettings.writePackageRestrictionsLPr(userId);
9555                    if (hidden) {
9556                        sendRemoved = true;
9557                    } else {
9558                        sendAdded = true;
9559                    }
9560                }
9561            }
9562            if (sendAdded) {
9563                sendPackageAddedForUser(packageName, pkgSetting, userId);
9564                return true;
9565            }
9566            if (sendRemoved) {
9567                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9568                        "hiding pkg");
9569                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9570            }
9571        } finally {
9572            Binder.restoreCallingIdentity(callingId);
9573        }
9574        return false;
9575    }
9576
9577    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9578            int userId) {
9579        final PackageRemovedInfo info = new PackageRemovedInfo();
9580        info.removedPackage = packageName;
9581        info.removedUsers = new int[] {userId};
9582        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9583        info.sendBroadcast(false, false, false);
9584    }
9585
9586    /**
9587     * Returns true if application is not found or there was an error. Otherwise it returns
9588     * the hidden state of the package for the given user.
9589     */
9590    @Override
9591    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9592        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9593        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9594                false, "getApplicationHidden for user " + userId);
9595        PackageSetting pkgSetting;
9596        long callingId = Binder.clearCallingIdentity();
9597        try {
9598            // writer
9599            synchronized (mPackages) {
9600                pkgSetting = mSettings.mPackages.get(packageName);
9601                if (pkgSetting == null) {
9602                    return true;
9603                }
9604                return pkgSetting.getHidden(userId);
9605            }
9606        } finally {
9607            Binder.restoreCallingIdentity(callingId);
9608        }
9609    }
9610
9611    /**
9612     * @hide
9613     */
9614    @Override
9615    public int installExistingPackageAsUser(String packageName, int userId) {
9616        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9617                null);
9618        PackageSetting pkgSetting;
9619        final int uid = Binder.getCallingUid();
9620        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9621                + userId);
9622        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9623            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9624        }
9625
9626        long callingId = Binder.clearCallingIdentity();
9627        try {
9628            boolean sendAdded = false;
9629
9630            // writer
9631            synchronized (mPackages) {
9632                pkgSetting = mSettings.mPackages.get(packageName);
9633                if (pkgSetting == null) {
9634                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9635                }
9636                if (!pkgSetting.getInstalled(userId)) {
9637                    pkgSetting.setInstalled(true, userId);
9638                    pkgSetting.setHidden(false, userId);
9639                    mSettings.writePackageRestrictionsLPr(userId);
9640                    sendAdded = true;
9641                }
9642            }
9643
9644            if (sendAdded) {
9645                sendPackageAddedForUser(packageName, pkgSetting, userId);
9646            }
9647        } finally {
9648            Binder.restoreCallingIdentity(callingId);
9649        }
9650
9651        return PackageManager.INSTALL_SUCCEEDED;
9652    }
9653
9654    boolean isUserRestricted(int userId, String restrictionKey) {
9655        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9656        if (restrictions.getBoolean(restrictionKey, false)) {
9657            Log.w(TAG, "User is restricted: " + restrictionKey);
9658            return true;
9659        }
9660        return false;
9661    }
9662
9663    @Override
9664    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9665        mContext.enforceCallingOrSelfPermission(
9666                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9667                "Only package verification agents can verify applications");
9668
9669        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9670        final PackageVerificationResponse response = new PackageVerificationResponse(
9671                verificationCode, Binder.getCallingUid());
9672        msg.arg1 = id;
9673        msg.obj = response;
9674        mHandler.sendMessage(msg);
9675    }
9676
9677    @Override
9678    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9679            long millisecondsToDelay) {
9680        mContext.enforceCallingOrSelfPermission(
9681                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9682                "Only package verification agents can extend verification timeouts");
9683
9684        final PackageVerificationState state = mPendingVerification.get(id);
9685        final PackageVerificationResponse response = new PackageVerificationResponse(
9686                verificationCodeAtTimeout, Binder.getCallingUid());
9687
9688        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9689            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9690        }
9691        if (millisecondsToDelay < 0) {
9692            millisecondsToDelay = 0;
9693        }
9694        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9695                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9696            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9697        }
9698
9699        if ((state != null) && !state.timeoutExtended()) {
9700            state.extendTimeout();
9701
9702            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9703            msg.arg1 = id;
9704            msg.obj = response;
9705            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9706        }
9707    }
9708
9709    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9710            int verificationCode, UserHandle user) {
9711        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9712        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9713        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9714        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9715        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9716
9717        mContext.sendBroadcastAsUser(intent, user,
9718                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9719    }
9720
9721    private ComponentName matchComponentForVerifier(String packageName,
9722            List<ResolveInfo> receivers) {
9723        ActivityInfo targetReceiver = null;
9724
9725        final int NR = receivers.size();
9726        for (int i = 0; i < NR; i++) {
9727            final ResolveInfo info = receivers.get(i);
9728            if (info.activityInfo == null) {
9729                continue;
9730            }
9731
9732            if (packageName.equals(info.activityInfo.packageName)) {
9733                targetReceiver = info.activityInfo;
9734                break;
9735            }
9736        }
9737
9738        if (targetReceiver == null) {
9739            return null;
9740        }
9741
9742        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9743    }
9744
9745    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9746            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9747        if (pkgInfo.verifiers.length == 0) {
9748            return null;
9749        }
9750
9751        final int N = pkgInfo.verifiers.length;
9752        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9753        for (int i = 0; i < N; i++) {
9754            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9755
9756            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9757                    receivers);
9758            if (comp == null) {
9759                continue;
9760            }
9761
9762            final int verifierUid = getUidForVerifier(verifierInfo);
9763            if (verifierUid == -1) {
9764                continue;
9765            }
9766
9767            if (DEBUG_VERIFY) {
9768                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9769                        + " with the correct signature");
9770            }
9771            sufficientVerifiers.add(comp);
9772            verificationState.addSufficientVerifier(verifierUid);
9773        }
9774
9775        return sufficientVerifiers;
9776    }
9777
9778    private int getUidForVerifier(VerifierInfo verifierInfo) {
9779        synchronized (mPackages) {
9780            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9781            if (pkg == null) {
9782                return -1;
9783            } else if (pkg.mSignatures.length != 1) {
9784                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9785                        + " has more than one signature; ignoring");
9786                return -1;
9787            }
9788
9789            /*
9790             * If the public key of the package's signature does not match
9791             * our expected public key, then this is a different package and
9792             * we should skip.
9793             */
9794
9795            final byte[] expectedPublicKey;
9796            try {
9797                final Signature verifierSig = pkg.mSignatures[0];
9798                final PublicKey publicKey = verifierSig.getPublicKey();
9799                expectedPublicKey = publicKey.getEncoded();
9800            } catch (CertificateException e) {
9801                return -1;
9802            }
9803
9804            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9805
9806            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9807                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9808                        + " does not have the expected public key; ignoring");
9809                return -1;
9810            }
9811
9812            return pkg.applicationInfo.uid;
9813        }
9814    }
9815
9816    @Override
9817    public void finishPackageInstall(int token) {
9818        enforceSystemOrRoot("Only the system is allowed to finish installs");
9819
9820        if (DEBUG_INSTALL) {
9821            Slog.v(TAG, "BM finishing package install for " + token);
9822        }
9823
9824        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9825        mHandler.sendMessage(msg);
9826    }
9827
9828    /**
9829     * Get the verification agent timeout.
9830     *
9831     * @return verification timeout in milliseconds
9832     */
9833    private long getVerificationTimeout() {
9834        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9835                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9836                DEFAULT_VERIFICATION_TIMEOUT);
9837    }
9838
9839    /**
9840     * Get the default verification agent response code.
9841     *
9842     * @return default verification response code
9843     */
9844    private int getDefaultVerificationResponse() {
9845        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9846                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9847                DEFAULT_VERIFICATION_RESPONSE);
9848    }
9849
9850    /**
9851     * Check whether or not package verification has been enabled.
9852     *
9853     * @return true if verification should be performed
9854     */
9855    private boolean isVerificationEnabled(int userId, int installFlags) {
9856        if (!DEFAULT_VERIFY_ENABLE) {
9857            return false;
9858        }
9859
9860        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9861
9862        // Check if installing from ADB
9863        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9864            // Do not run verification in a test harness environment
9865            if (ActivityManager.isRunningInTestHarness()) {
9866                return false;
9867            }
9868            if (ensureVerifyAppsEnabled) {
9869                return true;
9870            }
9871            // Check if the developer does not want package verification for ADB installs
9872            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9873                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9874                return false;
9875            }
9876        }
9877
9878        if (ensureVerifyAppsEnabled) {
9879            return true;
9880        }
9881
9882        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9883                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9884    }
9885
9886    @Override
9887    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9888            throws RemoteException {
9889        mContext.enforceCallingOrSelfPermission(
9890                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9891                "Only intentfilter verification agents can verify applications");
9892
9893        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9894        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9895                Binder.getCallingUid(), verificationCode, failedDomains);
9896        msg.arg1 = id;
9897        msg.obj = response;
9898        mHandler.sendMessage(msg);
9899    }
9900
9901    @Override
9902    public int getIntentVerificationStatus(String packageName, int userId) {
9903        synchronized (mPackages) {
9904            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9905        }
9906    }
9907
9908    @Override
9909    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9910        mContext.enforceCallingOrSelfPermission(
9911                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9912
9913        boolean result = false;
9914        synchronized (mPackages) {
9915            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9916        }
9917        if (result) {
9918            scheduleWritePackageRestrictionsLocked(userId);
9919        }
9920        return result;
9921    }
9922
9923    @Override
9924    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9925        synchronized (mPackages) {
9926            return mSettings.getIntentFilterVerificationsLPr(packageName);
9927        }
9928    }
9929
9930    @Override
9931    public List<IntentFilter> getAllIntentFilters(String packageName) {
9932        if (TextUtils.isEmpty(packageName)) {
9933            return Collections.<IntentFilter>emptyList();
9934        }
9935        synchronized (mPackages) {
9936            PackageParser.Package pkg = mPackages.get(packageName);
9937            if (pkg == null || pkg.activities == null) {
9938                return Collections.<IntentFilter>emptyList();
9939            }
9940            final int count = pkg.activities.size();
9941            ArrayList<IntentFilter> result = new ArrayList<>();
9942            for (int n=0; n<count; n++) {
9943                PackageParser.Activity activity = pkg.activities.get(n);
9944                if (activity.intents != null || activity.intents.size() > 0) {
9945                    result.addAll(activity.intents);
9946                }
9947            }
9948            return result;
9949        }
9950    }
9951
9952    @Override
9953    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9954        mContext.enforceCallingOrSelfPermission(
9955                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9956
9957        synchronized (mPackages) {
9958            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9959            if (packageName != null) {
9960                result |= updateIntentVerificationStatus(packageName,
9961                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9962                        userId);
9963                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9964                        packageName, userId);
9965            }
9966            return result;
9967        }
9968    }
9969
9970    @Override
9971    public String getDefaultBrowserPackageName(int userId) {
9972        synchronized (mPackages) {
9973            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9974        }
9975    }
9976
9977    /**
9978     * Get the "allow unknown sources" setting.
9979     *
9980     * @return the current "allow unknown sources" setting
9981     */
9982    private int getUnknownSourcesSettings() {
9983        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9984                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9985                -1);
9986    }
9987
9988    @Override
9989    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9990        final int uid = Binder.getCallingUid();
9991        // writer
9992        synchronized (mPackages) {
9993            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9994            if (targetPackageSetting == null) {
9995                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9996            }
9997
9998            PackageSetting installerPackageSetting;
9999            if (installerPackageName != null) {
10000                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10001                if (installerPackageSetting == null) {
10002                    throw new IllegalArgumentException("Unknown installer package: "
10003                            + installerPackageName);
10004                }
10005            } else {
10006                installerPackageSetting = null;
10007            }
10008
10009            Signature[] callerSignature;
10010            Object obj = mSettings.getUserIdLPr(uid);
10011            if (obj != null) {
10012                if (obj instanceof SharedUserSetting) {
10013                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10014                } else if (obj instanceof PackageSetting) {
10015                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10016                } else {
10017                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10018                }
10019            } else {
10020                throw new SecurityException("Unknown calling uid " + uid);
10021            }
10022
10023            // Verify: can't set installerPackageName to a package that is
10024            // not signed with the same cert as the caller.
10025            if (installerPackageSetting != null) {
10026                if (compareSignatures(callerSignature,
10027                        installerPackageSetting.signatures.mSignatures)
10028                        != PackageManager.SIGNATURE_MATCH) {
10029                    throw new SecurityException(
10030                            "Caller does not have same cert as new installer package "
10031                            + installerPackageName);
10032                }
10033            }
10034
10035            // Verify: if target already has an installer package, it must
10036            // be signed with the same cert as the caller.
10037            if (targetPackageSetting.installerPackageName != null) {
10038                PackageSetting setting = mSettings.mPackages.get(
10039                        targetPackageSetting.installerPackageName);
10040                // If the currently set package isn't valid, then it's always
10041                // okay to change it.
10042                if (setting != null) {
10043                    if (compareSignatures(callerSignature,
10044                            setting.signatures.mSignatures)
10045                            != PackageManager.SIGNATURE_MATCH) {
10046                        throw new SecurityException(
10047                                "Caller does not have same cert as old installer package "
10048                                + targetPackageSetting.installerPackageName);
10049                    }
10050                }
10051            }
10052
10053            // Okay!
10054            targetPackageSetting.installerPackageName = installerPackageName;
10055            scheduleWriteSettingsLocked();
10056        }
10057    }
10058
10059    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10060        // Queue up an async operation since the package installation may take a little while.
10061        mHandler.post(new Runnable() {
10062            public void run() {
10063                mHandler.removeCallbacks(this);
10064                 // Result object to be returned
10065                PackageInstalledInfo res = new PackageInstalledInfo();
10066                res.returnCode = currentStatus;
10067                res.uid = -1;
10068                res.pkg = null;
10069                res.removedInfo = new PackageRemovedInfo();
10070                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10071                    args.doPreInstall(res.returnCode);
10072                    synchronized (mInstallLock) {
10073                        installPackageLI(args, res);
10074                    }
10075                    args.doPostInstall(res.returnCode, res.uid);
10076                }
10077
10078                // A restore should be performed at this point if (a) the install
10079                // succeeded, (b) the operation is not an update, and (c) the new
10080                // package has not opted out of backup participation.
10081                final boolean update = res.removedInfo.removedPackage != null;
10082                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10083                boolean doRestore = !update
10084                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10085
10086                // Set up the post-install work request bookkeeping.  This will be used
10087                // and cleaned up by the post-install event handling regardless of whether
10088                // there's a restore pass performed.  Token values are >= 1.
10089                int token;
10090                if (mNextInstallToken < 0) mNextInstallToken = 1;
10091                token = mNextInstallToken++;
10092
10093                PostInstallData data = new PostInstallData(args, res);
10094                mRunningInstalls.put(token, data);
10095                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10096
10097                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10098                    // Pass responsibility to the Backup Manager.  It will perform a
10099                    // restore if appropriate, then pass responsibility back to the
10100                    // Package Manager to run the post-install observer callbacks
10101                    // and broadcasts.
10102                    IBackupManager bm = IBackupManager.Stub.asInterface(
10103                            ServiceManager.getService(Context.BACKUP_SERVICE));
10104                    if (bm != null) {
10105                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10106                                + " to BM for possible restore");
10107                        try {
10108                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10109                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10110                            } else {
10111                                doRestore = false;
10112                            }
10113                        } catch (RemoteException e) {
10114                            // can't happen; the backup manager is local
10115                        } catch (Exception e) {
10116                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10117                            doRestore = false;
10118                        }
10119                    } else {
10120                        Slog.e(TAG, "Backup Manager not found!");
10121                        doRestore = false;
10122                    }
10123                }
10124
10125                if (!doRestore) {
10126                    // No restore possible, or the Backup Manager was mysteriously not
10127                    // available -- just fire the post-install work request directly.
10128                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10129                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10130                    mHandler.sendMessage(msg);
10131                }
10132            }
10133        });
10134    }
10135
10136    private abstract class HandlerParams {
10137        private static final int MAX_RETRIES = 4;
10138
10139        /**
10140         * Number of times startCopy() has been attempted and had a non-fatal
10141         * error.
10142         */
10143        private int mRetries = 0;
10144
10145        /** User handle for the user requesting the information or installation. */
10146        private final UserHandle mUser;
10147
10148        HandlerParams(UserHandle user) {
10149            mUser = user;
10150        }
10151
10152        UserHandle getUser() {
10153            return mUser;
10154        }
10155
10156        final boolean startCopy() {
10157            boolean res;
10158            try {
10159                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10160
10161                if (++mRetries > MAX_RETRIES) {
10162                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10163                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10164                    handleServiceError();
10165                    return false;
10166                } else {
10167                    handleStartCopy();
10168                    res = true;
10169                }
10170            } catch (RemoteException e) {
10171                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10172                mHandler.sendEmptyMessage(MCS_RECONNECT);
10173                res = false;
10174            }
10175            handleReturnCode();
10176            return res;
10177        }
10178
10179        final void serviceError() {
10180            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10181            handleServiceError();
10182            handleReturnCode();
10183        }
10184
10185        abstract void handleStartCopy() throws RemoteException;
10186        abstract void handleServiceError();
10187        abstract void handleReturnCode();
10188    }
10189
10190    class MeasureParams extends HandlerParams {
10191        private final PackageStats mStats;
10192        private boolean mSuccess;
10193
10194        private final IPackageStatsObserver mObserver;
10195
10196        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10197            super(new UserHandle(stats.userHandle));
10198            mObserver = observer;
10199            mStats = stats;
10200        }
10201
10202        @Override
10203        public String toString() {
10204            return "MeasureParams{"
10205                + Integer.toHexString(System.identityHashCode(this))
10206                + " " + mStats.packageName + "}";
10207        }
10208
10209        @Override
10210        void handleStartCopy() throws RemoteException {
10211            synchronized (mInstallLock) {
10212                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10213            }
10214
10215            if (mSuccess) {
10216                final boolean mounted;
10217                if (Environment.isExternalStorageEmulated()) {
10218                    mounted = true;
10219                } else {
10220                    final String status = Environment.getExternalStorageState();
10221                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10222                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10223                }
10224
10225                if (mounted) {
10226                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10227
10228                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10229                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10230
10231                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10232                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10233
10234                    // Always subtract cache size, since it's a subdirectory
10235                    mStats.externalDataSize -= mStats.externalCacheSize;
10236
10237                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10238                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10239
10240                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10241                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10242                }
10243            }
10244        }
10245
10246        @Override
10247        void handleReturnCode() {
10248            if (mObserver != null) {
10249                try {
10250                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10251                } catch (RemoteException e) {
10252                    Slog.i(TAG, "Observer no longer exists.");
10253                }
10254            }
10255        }
10256
10257        @Override
10258        void handleServiceError() {
10259            Slog.e(TAG, "Could not measure application " + mStats.packageName
10260                            + " external storage");
10261        }
10262    }
10263
10264    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10265            throws RemoteException {
10266        long result = 0;
10267        for (File path : paths) {
10268            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10269        }
10270        return result;
10271    }
10272
10273    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10274        for (File path : paths) {
10275            try {
10276                mcs.clearDirectory(path.getAbsolutePath());
10277            } catch (RemoteException e) {
10278            }
10279        }
10280    }
10281
10282    static class OriginInfo {
10283        /**
10284         * Location where install is coming from, before it has been
10285         * copied/renamed into place. This could be a single monolithic APK
10286         * file, or a cluster directory. This location may be untrusted.
10287         */
10288        final File file;
10289        final String cid;
10290
10291        /**
10292         * Flag indicating that {@link #file} or {@link #cid} has already been
10293         * staged, meaning downstream users don't need to defensively copy the
10294         * contents.
10295         */
10296        final boolean staged;
10297
10298        /**
10299         * Flag indicating that {@link #file} or {@link #cid} is an already
10300         * installed app that is being moved.
10301         */
10302        final boolean existing;
10303
10304        final String resolvedPath;
10305        final File resolvedFile;
10306
10307        static OriginInfo fromNothing() {
10308            return new OriginInfo(null, null, false, false);
10309        }
10310
10311        static OriginInfo fromUntrustedFile(File file) {
10312            return new OriginInfo(file, null, false, false);
10313        }
10314
10315        static OriginInfo fromExistingFile(File file) {
10316            return new OriginInfo(file, null, false, true);
10317        }
10318
10319        static OriginInfo fromStagedFile(File file) {
10320            return new OriginInfo(file, null, true, false);
10321        }
10322
10323        static OriginInfo fromStagedContainer(String cid) {
10324            return new OriginInfo(null, cid, true, false);
10325        }
10326
10327        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10328            this.file = file;
10329            this.cid = cid;
10330            this.staged = staged;
10331            this.existing = existing;
10332
10333            if (cid != null) {
10334                resolvedPath = PackageHelper.getSdDir(cid);
10335                resolvedFile = new File(resolvedPath);
10336            } else if (file != null) {
10337                resolvedPath = file.getAbsolutePath();
10338                resolvedFile = file;
10339            } else {
10340                resolvedPath = null;
10341                resolvedFile = null;
10342            }
10343        }
10344    }
10345
10346    class MoveInfo {
10347        final int moveId;
10348        final String fromUuid;
10349        final String toUuid;
10350        final String packageName;
10351        final String dataAppName;
10352        final int appId;
10353        final String seinfo;
10354
10355        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10356                String dataAppName, int appId, String seinfo) {
10357            this.moveId = moveId;
10358            this.fromUuid = fromUuid;
10359            this.toUuid = toUuid;
10360            this.packageName = packageName;
10361            this.dataAppName = dataAppName;
10362            this.appId = appId;
10363            this.seinfo = seinfo;
10364        }
10365    }
10366
10367    class InstallParams extends HandlerParams {
10368        final OriginInfo origin;
10369        final MoveInfo move;
10370        final IPackageInstallObserver2 observer;
10371        int installFlags;
10372        final String installerPackageName;
10373        final String volumeUuid;
10374        final VerificationParams verificationParams;
10375        private InstallArgs mArgs;
10376        private int mRet;
10377        final String packageAbiOverride;
10378        final String[] grantedRuntimePermissions;
10379
10380
10381        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10382                int installFlags, String installerPackageName, String volumeUuid,
10383                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10384                String[] grantedPermissions) {
10385            super(user);
10386            this.origin = origin;
10387            this.move = move;
10388            this.observer = observer;
10389            this.installFlags = installFlags;
10390            this.installerPackageName = installerPackageName;
10391            this.volumeUuid = volumeUuid;
10392            this.verificationParams = verificationParams;
10393            this.packageAbiOverride = packageAbiOverride;
10394            this.grantedRuntimePermissions = grantedPermissions;
10395        }
10396
10397        @Override
10398        public String toString() {
10399            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10400                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10401        }
10402
10403        public ManifestDigest getManifestDigest() {
10404            if (verificationParams == null) {
10405                return null;
10406            }
10407            return verificationParams.getManifestDigest();
10408        }
10409
10410        private int installLocationPolicy(PackageInfoLite pkgLite) {
10411            String packageName = pkgLite.packageName;
10412            int installLocation = pkgLite.installLocation;
10413            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10414            // reader
10415            synchronized (mPackages) {
10416                PackageParser.Package pkg = mPackages.get(packageName);
10417                if (pkg != null) {
10418                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10419                        // Check for downgrading.
10420                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10421                            try {
10422                                checkDowngrade(pkg, pkgLite);
10423                            } catch (PackageManagerException e) {
10424                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10425                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10426                            }
10427                        }
10428                        // Check for updated system application.
10429                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10430                            if (onSd) {
10431                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10432                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10433                            }
10434                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10435                        } else {
10436                            if (onSd) {
10437                                // Install flag overrides everything.
10438                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10439                            }
10440                            // If current upgrade specifies particular preference
10441                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10442                                // Application explicitly specified internal.
10443                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10444                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10445                                // App explictly prefers external. Let policy decide
10446                            } else {
10447                                // Prefer previous location
10448                                if (isExternal(pkg)) {
10449                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10450                                }
10451                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10452                            }
10453                        }
10454                    } else {
10455                        // Invalid install. Return error code
10456                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10457                    }
10458                }
10459            }
10460            // All the special cases have been taken care of.
10461            // Return result based on recommended install location.
10462            if (onSd) {
10463                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10464            }
10465            return pkgLite.recommendedInstallLocation;
10466        }
10467
10468        /*
10469         * Invoke remote method to get package information and install
10470         * location values. Override install location based on default
10471         * policy if needed and then create install arguments based
10472         * on the install location.
10473         */
10474        public void handleStartCopy() throws RemoteException {
10475            int ret = PackageManager.INSTALL_SUCCEEDED;
10476
10477            // If we're already staged, we've firmly committed to an install location
10478            if (origin.staged) {
10479                if (origin.file != null) {
10480                    installFlags |= PackageManager.INSTALL_INTERNAL;
10481                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10482                } else if (origin.cid != null) {
10483                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10484                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10485                } else {
10486                    throw new IllegalStateException("Invalid stage location");
10487                }
10488            }
10489
10490            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10491            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10492
10493            PackageInfoLite pkgLite = null;
10494
10495            if (onInt && onSd) {
10496                // Check if both bits are set.
10497                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10498                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10499            } else {
10500                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10501                        packageAbiOverride);
10502
10503                /*
10504                 * If we have too little free space, try to free cache
10505                 * before giving up.
10506                 */
10507                if (!origin.staged && pkgLite.recommendedInstallLocation
10508                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10509                    // TODO: focus freeing disk space on the target device
10510                    final StorageManager storage = StorageManager.from(mContext);
10511                    final long lowThreshold = storage.getStorageLowBytes(
10512                            Environment.getDataDirectory());
10513
10514                    final long sizeBytes = mContainerService.calculateInstalledSize(
10515                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10516
10517                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10518                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10519                                installFlags, packageAbiOverride);
10520                    }
10521
10522                    /*
10523                     * The cache free must have deleted the file we
10524                     * downloaded to install.
10525                     *
10526                     * TODO: fix the "freeCache" call to not delete
10527                     *       the file we care about.
10528                     */
10529                    if (pkgLite.recommendedInstallLocation
10530                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10531                        pkgLite.recommendedInstallLocation
10532                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10533                    }
10534                }
10535            }
10536
10537            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10538                int loc = pkgLite.recommendedInstallLocation;
10539                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10540                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10541                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10542                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10543                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10544                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10545                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10546                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10547                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10548                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10549                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10550                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10551                } else {
10552                    // Override with defaults if needed.
10553                    loc = installLocationPolicy(pkgLite);
10554                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10555                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10556                    } else if (!onSd && !onInt) {
10557                        // Override install location with flags
10558                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10559                            // Set the flag to install on external media.
10560                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10561                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10562                        } else {
10563                            // Make sure the flag for installing on external
10564                            // media is unset
10565                            installFlags |= PackageManager.INSTALL_INTERNAL;
10566                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10567                        }
10568                    }
10569                }
10570            }
10571
10572            final InstallArgs args = createInstallArgs(this);
10573            mArgs = args;
10574
10575            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10576                 /*
10577                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10578                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10579                 */
10580                int userIdentifier = getUser().getIdentifier();
10581                if (userIdentifier == UserHandle.USER_ALL
10582                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10583                    userIdentifier = UserHandle.USER_OWNER;
10584                }
10585
10586                /*
10587                 * Determine if we have any installed package verifiers. If we
10588                 * do, then we'll defer to them to verify the packages.
10589                 */
10590                final int requiredUid = mRequiredVerifierPackage == null ? -1
10591                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10592                if (!origin.existing && requiredUid != -1
10593                        && isVerificationEnabled(userIdentifier, installFlags)) {
10594                    final Intent verification = new Intent(
10595                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10596                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10597                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10598                            PACKAGE_MIME_TYPE);
10599                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10600
10601                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10602                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10603                            0 /* TODO: Which userId? */);
10604
10605                    if (DEBUG_VERIFY) {
10606                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10607                                + verification.toString() + " with " + pkgLite.verifiers.length
10608                                + " optional verifiers");
10609                    }
10610
10611                    final int verificationId = mPendingVerificationToken++;
10612
10613                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10614
10615                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10616                            installerPackageName);
10617
10618                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10619                            installFlags);
10620
10621                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10622                            pkgLite.packageName);
10623
10624                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10625                            pkgLite.versionCode);
10626
10627                    if (verificationParams != null) {
10628                        if (verificationParams.getVerificationURI() != null) {
10629                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10630                                 verificationParams.getVerificationURI());
10631                        }
10632                        if (verificationParams.getOriginatingURI() != null) {
10633                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10634                                  verificationParams.getOriginatingURI());
10635                        }
10636                        if (verificationParams.getReferrer() != null) {
10637                            verification.putExtra(Intent.EXTRA_REFERRER,
10638                                  verificationParams.getReferrer());
10639                        }
10640                        if (verificationParams.getOriginatingUid() >= 0) {
10641                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10642                                  verificationParams.getOriginatingUid());
10643                        }
10644                        if (verificationParams.getInstallerUid() >= 0) {
10645                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10646                                  verificationParams.getInstallerUid());
10647                        }
10648                    }
10649
10650                    final PackageVerificationState verificationState = new PackageVerificationState(
10651                            requiredUid, args);
10652
10653                    mPendingVerification.append(verificationId, verificationState);
10654
10655                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10656                            receivers, verificationState);
10657
10658                    // Apps installed for "all" users use the device owner to verify the app
10659                    UserHandle verifierUser = getUser();
10660                    if (verifierUser == UserHandle.ALL) {
10661                        verifierUser = UserHandle.OWNER;
10662                    }
10663
10664                    /*
10665                     * If any sufficient verifiers were listed in the package
10666                     * manifest, attempt to ask them.
10667                     */
10668                    if (sufficientVerifiers != null) {
10669                        final int N = sufficientVerifiers.size();
10670                        if (N == 0) {
10671                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10672                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10673                        } else {
10674                            for (int i = 0; i < N; i++) {
10675                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10676
10677                                final Intent sufficientIntent = new Intent(verification);
10678                                sufficientIntent.setComponent(verifierComponent);
10679                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10680                            }
10681                        }
10682                    }
10683
10684                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10685                            mRequiredVerifierPackage, receivers);
10686                    if (ret == PackageManager.INSTALL_SUCCEEDED
10687                            && mRequiredVerifierPackage != null) {
10688                        /*
10689                         * Send the intent to the required verification agent,
10690                         * but only start the verification timeout after the
10691                         * target BroadcastReceivers have run.
10692                         */
10693                        verification.setComponent(requiredVerifierComponent);
10694                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10695                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10696                                new BroadcastReceiver() {
10697                                    @Override
10698                                    public void onReceive(Context context, Intent intent) {
10699                                        final Message msg = mHandler
10700                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10701                                        msg.arg1 = verificationId;
10702                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10703                                    }
10704                                }, null, 0, null, null);
10705
10706                        /*
10707                         * We don't want the copy to proceed until verification
10708                         * succeeds, so null out this field.
10709                         */
10710                        mArgs = null;
10711                    }
10712                } else {
10713                    /*
10714                     * No package verification is enabled, so immediately start
10715                     * the remote call to initiate copy using temporary file.
10716                     */
10717                    ret = args.copyApk(mContainerService, true);
10718                }
10719            }
10720
10721            mRet = ret;
10722        }
10723
10724        @Override
10725        void handleReturnCode() {
10726            // If mArgs is null, then MCS couldn't be reached. When it
10727            // reconnects, it will try again to install. At that point, this
10728            // will succeed.
10729            if (mArgs != null) {
10730                processPendingInstall(mArgs, mRet);
10731            }
10732        }
10733
10734        @Override
10735        void handleServiceError() {
10736            mArgs = createInstallArgs(this);
10737            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10738        }
10739
10740        public boolean isForwardLocked() {
10741            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10742        }
10743    }
10744
10745    /**
10746     * Used during creation of InstallArgs
10747     *
10748     * @param installFlags package installation flags
10749     * @return true if should be installed on external storage
10750     */
10751    private static boolean installOnExternalAsec(int installFlags) {
10752        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10753            return false;
10754        }
10755        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10756            return true;
10757        }
10758        return false;
10759    }
10760
10761    /**
10762     * Used during creation of InstallArgs
10763     *
10764     * @param installFlags package installation flags
10765     * @return true if should be installed as forward locked
10766     */
10767    private static boolean installForwardLocked(int installFlags) {
10768        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10769    }
10770
10771    private InstallArgs createInstallArgs(InstallParams params) {
10772        if (params.move != null) {
10773            return new MoveInstallArgs(params);
10774        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10775            return new AsecInstallArgs(params);
10776        } else {
10777            return new FileInstallArgs(params);
10778        }
10779    }
10780
10781    /**
10782     * Create args that describe an existing installed package. Typically used
10783     * when cleaning up old installs, or used as a move source.
10784     */
10785    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10786            String resourcePath, String[] instructionSets) {
10787        final boolean isInAsec;
10788        if (installOnExternalAsec(installFlags)) {
10789            /* Apps on SD card are always in ASEC containers. */
10790            isInAsec = true;
10791        } else if (installForwardLocked(installFlags)
10792                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10793            /*
10794             * Forward-locked apps are only in ASEC containers if they're the
10795             * new style
10796             */
10797            isInAsec = true;
10798        } else {
10799            isInAsec = false;
10800        }
10801
10802        if (isInAsec) {
10803            return new AsecInstallArgs(codePath, instructionSets,
10804                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10805        } else {
10806            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10807        }
10808    }
10809
10810    static abstract class InstallArgs {
10811        /** @see InstallParams#origin */
10812        final OriginInfo origin;
10813        /** @see InstallParams#move */
10814        final MoveInfo move;
10815
10816        final IPackageInstallObserver2 observer;
10817        // Always refers to PackageManager flags only
10818        final int installFlags;
10819        final String installerPackageName;
10820        final String volumeUuid;
10821        final ManifestDigest manifestDigest;
10822        final UserHandle user;
10823        final String abiOverride;
10824        final String[] installGrantPermissions;
10825
10826        // The list of instruction sets supported by this app. This is currently
10827        // only used during the rmdex() phase to clean up resources. We can get rid of this
10828        // if we move dex files under the common app path.
10829        /* nullable */ String[] instructionSets;
10830
10831        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10832                int installFlags, String installerPackageName, String volumeUuid,
10833                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10834                String abiOverride, String[] installGrantPermissions) {
10835            this.origin = origin;
10836            this.move = move;
10837            this.installFlags = installFlags;
10838            this.observer = observer;
10839            this.installerPackageName = installerPackageName;
10840            this.volumeUuid = volumeUuid;
10841            this.manifestDigest = manifestDigest;
10842            this.user = user;
10843            this.instructionSets = instructionSets;
10844            this.abiOverride = abiOverride;
10845            this.installGrantPermissions = installGrantPermissions;
10846        }
10847
10848        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10849        abstract int doPreInstall(int status);
10850
10851        /**
10852         * Rename package into final resting place. All paths on the given
10853         * scanned package should be updated to reflect the rename.
10854         */
10855        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10856        abstract int doPostInstall(int status, int uid);
10857
10858        /** @see PackageSettingBase#codePathString */
10859        abstract String getCodePath();
10860        /** @see PackageSettingBase#resourcePathString */
10861        abstract String getResourcePath();
10862
10863        // Need installer lock especially for dex file removal.
10864        abstract void cleanUpResourcesLI();
10865        abstract boolean doPostDeleteLI(boolean delete);
10866
10867        /**
10868         * Called before the source arguments are copied. This is used mostly
10869         * for MoveParams when it needs to read the source file to put it in the
10870         * destination.
10871         */
10872        int doPreCopy() {
10873            return PackageManager.INSTALL_SUCCEEDED;
10874        }
10875
10876        /**
10877         * Called after the source arguments are copied. This is used mostly for
10878         * MoveParams when it needs to read the source file to put it in the
10879         * destination.
10880         *
10881         * @return
10882         */
10883        int doPostCopy(int uid) {
10884            return PackageManager.INSTALL_SUCCEEDED;
10885        }
10886
10887        protected boolean isFwdLocked() {
10888            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10889        }
10890
10891        protected boolean isExternalAsec() {
10892            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10893        }
10894
10895        UserHandle getUser() {
10896            return user;
10897        }
10898    }
10899
10900    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10901        if (!allCodePaths.isEmpty()) {
10902            if (instructionSets == null) {
10903                throw new IllegalStateException("instructionSet == null");
10904            }
10905            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10906            for (String codePath : allCodePaths) {
10907                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10908                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10909                    if (retCode < 0) {
10910                        Slog.w(TAG, "Couldn't remove dex file for package: "
10911                                + " at location " + codePath + ", retcode=" + retCode);
10912                        // we don't consider this to be a failure of the core package deletion
10913                    }
10914                }
10915            }
10916        }
10917    }
10918
10919    /**
10920     * Logic to handle installation of non-ASEC applications, including copying
10921     * and renaming logic.
10922     */
10923    class FileInstallArgs extends InstallArgs {
10924        private File codeFile;
10925        private File resourceFile;
10926
10927        // Example topology:
10928        // /data/app/com.example/base.apk
10929        // /data/app/com.example/split_foo.apk
10930        // /data/app/com.example/lib/arm/libfoo.so
10931        // /data/app/com.example/lib/arm64/libfoo.so
10932        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10933
10934        /** New install */
10935        FileInstallArgs(InstallParams params) {
10936            super(params.origin, params.move, params.observer, params.installFlags,
10937                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10938                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10939                    params.grantedRuntimePermissions);
10940            if (isFwdLocked()) {
10941                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10942            }
10943        }
10944
10945        /** Existing install */
10946        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10947            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10948                    null, null);
10949            this.codeFile = (codePath != null) ? new File(codePath) : null;
10950            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10951        }
10952
10953        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10954            if (origin.staged) {
10955                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10956                codeFile = origin.file;
10957                resourceFile = origin.file;
10958                return PackageManager.INSTALL_SUCCEEDED;
10959            }
10960
10961            try {
10962                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10963                codeFile = tempDir;
10964                resourceFile = tempDir;
10965            } catch (IOException e) {
10966                Slog.w(TAG, "Failed to create copy file: " + e);
10967                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10968            }
10969
10970            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10971                @Override
10972                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10973                    if (!FileUtils.isValidExtFilename(name)) {
10974                        throw new IllegalArgumentException("Invalid filename: " + name);
10975                    }
10976                    try {
10977                        final File file = new File(codeFile, name);
10978                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10979                                O_RDWR | O_CREAT, 0644);
10980                        Os.chmod(file.getAbsolutePath(), 0644);
10981                        return new ParcelFileDescriptor(fd);
10982                    } catch (ErrnoException e) {
10983                        throw new RemoteException("Failed to open: " + e.getMessage());
10984                    }
10985                }
10986            };
10987
10988            int ret = PackageManager.INSTALL_SUCCEEDED;
10989            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10990            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10991                Slog.e(TAG, "Failed to copy package");
10992                return ret;
10993            }
10994
10995            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10996            NativeLibraryHelper.Handle handle = null;
10997            try {
10998                handle = NativeLibraryHelper.Handle.create(codeFile);
10999                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11000                        abiOverride);
11001            } catch (IOException e) {
11002                Slog.e(TAG, "Copying native libraries failed", e);
11003                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11004            } finally {
11005                IoUtils.closeQuietly(handle);
11006            }
11007
11008            return ret;
11009        }
11010
11011        int doPreInstall(int status) {
11012            if (status != PackageManager.INSTALL_SUCCEEDED) {
11013                cleanUp();
11014            }
11015            return status;
11016        }
11017
11018        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11019            if (status != PackageManager.INSTALL_SUCCEEDED) {
11020                cleanUp();
11021                return false;
11022            }
11023
11024            final File targetDir = codeFile.getParentFile();
11025            final File beforeCodeFile = codeFile;
11026            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11027
11028            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11029            try {
11030                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11031            } catch (ErrnoException e) {
11032                Slog.w(TAG, "Failed to rename", e);
11033                return false;
11034            }
11035
11036            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11037                Slog.w(TAG, "Failed to restorecon");
11038                return false;
11039            }
11040
11041            // Reflect the rename internally
11042            codeFile = afterCodeFile;
11043            resourceFile = afterCodeFile;
11044
11045            // Reflect the rename in scanned details
11046            pkg.codePath = afterCodeFile.getAbsolutePath();
11047            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11048                    pkg.baseCodePath);
11049            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11050                    pkg.splitCodePaths);
11051
11052            // Reflect the rename in app info
11053            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11054            pkg.applicationInfo.setCodePath(pkg.codePath);
11055            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11056            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11057            pkg.applicationInfo.setResourcePath(pkg.codePath);
11058            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11059            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11060
11061            return true;
11062        }
11063
11064        int doPostInstall(int status, int uid) {
11065            if (status != PackageManager.INSTALL_SUCCEEDED) {
11066                cleanUp();
11067            }
11068            return status;
11069        }
11070
11071        @Override
11072        String getCodePath() {
11073            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11074        }
11075
11076        @Override
11077        String getResourcePath() {
11078            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11079        }
11080
11081        private boolean cleanUp() {
11082            if (codeFile == null || !codeFile.exists()) {
11083                return false;
11084            }
11085
11086            if (codeFile.isDirectory()) {
11087                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11088            } else {
11089                codeFile.delete();
11090            }
11091
11092            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11093                resourceFile.delete();
11094            }
11095
11096            return true;
11097        }
11098
11099        void cleanUpResourcesLI() {
11100            // Try enumerating all code paths before deleting
11101            List<String> allCodePaths = Collections.EMPTY_LIST;
11102            if (codeFile != null && codeFile.exists()) {
11103                try {
11104                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11105                    allCodePaths = pkg.getAllCodePaths();
11106                } catch (PackageParserException e) {
11107                    // Ignored; we tried our best
11108                }
11109            }
11110
11111            cleanUp();
11112            removeDexFiles(allCodePaths, instructionSets);
11113        }
11114
11115        boolean doPostDeleteLI(boolean delete) {
11116            // XXX err, shouldn't we respect the delete flag?
11117            cleanUpResourcesLI();
11118            return true;
11119        }
11120    }
11121
11122    private boolean isAsecExternal(String cid) {
11123        final String asecPath = PackageHelper.getSdFilesystem(cid);
11124        return !asecPath.startsWith(mAsecInternalPath);
11125    }
11126
11127    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11128            PackageManagerException {
11129        if (copyRet < 0) {
11130            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11131                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11132                throw new PackageManagerException(copyRet, message);
11133            }
11134        }
11135    }
11136
11137    /**
11138     * Extract the MountService "container ID" from the full code path of an
11139     * .apk.
11140     */
11141    static String cidFromCodePath(String fullCodePath) {
11142        int eidx = fullCodePath.lastIndexOf("/");
11143        String subStr1 = fullCodePath.substring(0, eidx);
11144        int sidx = subStr1.lastIndexOf("/");
11145        return subStr1.substring(sidx+1, eidx);
11146    }
11147
11148    /**
11149     * Logic to handle installation of ASEC applications, including copying and
11150     * renaming logic.
11151     */
11152    class AsecInstallArgs extends InstallArgs {
11153        static final String RES_FILE_NAME = "pkg.apk";
11154        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11155
11156        String cid;
11157        String packagePath;
11158        String resourcePath;
11159
11160        /** New install */
11161        AsecInstallArgs(InstallParams params) {
11162            super(params.origin, params.move, params.observer, params.installFlags,
11163                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11164                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11165                    params.grantedRuntimePermissions);
11166        }
11167
11168        /** Existing install */
11169        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11170                        boolean isExternal, boolean isForwardLocked) {
11171            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11172                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11173                    instructionSets, null, null);
11174            // Hackily pretend we're still looking at a full code path
11175            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11176                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11177            }
11178
11179            // Extract cid from fullCodePath
11180            int eidx = fullCodePath.lastIndexOf("/");
11181            String subStr1 = fullCodePath.substring(0, eidx);
11182            int sidx = subStr1.lastIndexOf("/");
11183            cid = subStr1.substring(sidx+1, eidx);
11184            setMountPath(subStr1);
11185        }
11186
11187        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11188            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11189                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11190                    instructionSets, null, null);
11191            this.cid = cid;
11192            setMountPath(PackageHelper.getSdDir(cid));
11193        }
11194
11195        void createCopyFile() {
11196            cid = mInstallerService.allocateExternalStageCidLegacy();
11197        }
11198
11199        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11200            if (origin.staged) {
11201                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11202                cid = origin.cid;
11203                setMountPath(PackageHelper.getSdDir(cid));
11204                return PackageManager.INSTALL_SUCCEEDED;
11205            }
11206
11207            if (temp) {
11208                createCopyFile();
11209            } else {
11210                /*
11211                 * Pre-emptively destroy the container since it's destroyed if
11212                 * copying fails due to it existing anyway.
11213                 */
11214                PackageHelper.destroySdDir(cid);
11215            }
11216
11217            final String newMountPath = imcs.copyPackageToContainer(
11218                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11219                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11220
11221            if (newMountPath != null) {
11222                setMountPath(newMountPath);
11223                return PackageManager.INSTALL_SUCCEEDED;
11224            } else {
11225                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11226            }
11227        }
11228
11229        @Override
11230        String getCodePath() {
11231            return packagePath;
11232        }
11233
11234        @Override
11235        String getResourcePath() {
11236            return resourcePath;
11237        }
11238
11239        int doPreInstall(int status) {
11240            if (status != PackageManager.INSTALL_SUCCEEDED) {
11241                // Destroy container
11242                PackageHelper.destroySdDir(cid);
11243            } else {
11244                boolean mounted = PackageHelper.isContainerMounted(cid);
11245                if (!mounted) {
11246                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11247                            Process.SYSTEM_UID);
11248                    if (newMountPath != null) {
11249                        setMountPath(newMountPath);
11250                    } else {
11251                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11252                    }
11253                }
11254            }
11255            return status;
11256        }
11257
11258        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11259            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11260            String newMountPath = null;
11261            if (PackageHelper.isContainerMounted(cid)) {
11262                // Unmount the container
11263                if (!PackageHelper.unMountSdDir(cid)) {
11264                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11265                    return false;
11266                }
11267            }
11268            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11269                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11270                        " which might be stale. Will try to clean up.");
11271                // Clean up the stale container and proceed to recreate.
11272                if (!PackageHelper.destroySdDir(newCacheId)) {
11273                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11274                    return false;
11275                }
11276                // Successfully cleaned up stale container. Try to rename again.
11277                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11278                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11279                            + " inspite of cleaning it up.");
11280                    return false;
11281                }
11282            }
11283            if (!PackageHelper.isContainerMounted(newCacheId)) {
11284                Slog.w(TAG, "Mounting container " + newCacheId);
11285                newMountPath = PackageHelper.mountSdDir(newCacheId,
11286                        getEncryptKey(), Process.SYSTEM_UID);
11287            } else {
11288                newMountPath = PackageHelper.getSdDir(newCacheId);
11289            }
11290            if (newMountPath == null) {
11291                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11292                return false;
11293            }
11294            Log.i(TAG, "Succesfully renamed " + cid +
11295                    " to " + newCacheId +
11296                    " at new path: " + newMountPath);
11297            cid = newCacheId;
11298
11299            final File beforeCodeFile = new File(packagePath);
11300            setMountPath(newMountPath);
11301            final File afterCodeFile = new File(packagePath);
11302
11303            // Reflect the rename in scanned details
11304            pkg.codePath = afterCodeFile.getAbsolutePath();
11305            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11306                    pkg.baseCodePath);
11307            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11308                    pkg.splitCodePaths);
11309
11310            // Reflect the rename in app info
11311            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11312            pkg.applicationInfo.setCodePath(pkg.codePath);
11313            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11314            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11315            pkg.applicationInfo.setResourcePath(pkg.codePath);
11316            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11317            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11318
11319            return true;
11320        }
11321
11322        private void setMountPath(String mountPath) {
11323            final File mountFile = new File(mountPath);
11324
11325            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11326            if (monolithicFile.exists()) {
11327                packagePath = monolithicFile.getAbsolutePath();
11328                if (isFwdLocked()) {
11329                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11330                } else {
11331                    resourcePath = packagePath;
11332                }
11333            } else {
11334                packagePath = mountFile.getAbsolutePath();
11335                resourcePath = packagePath;
11336            }
11337        }
11338
11339        int doPostInstall(int status, int uid) {
11340            if (status != PackageManager.INSTALL_SUCCEEDED) {
11341                cleanUp();
11342            } else {
11343                final int groupOwner;
11344                final String protectedFile;
11345                if (isFwdLocked()) {
11346                    groupOwner = UserHandle.getSharedAppGid(uid);
11347                    protectedFile = RES_FILE_NAME;
11348                } else {
11349                    groupOwner = -1;
11350                    protectedFile = null;
11351                }
11352
11353                if (uid < Process.FIRST_APPLICATION_UID
11354                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11355                    Slog.e(TAG, "Failed to finalize " + cid);
11356                    PackageHelper.destroySdDir(cid);
11357                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11358                }
11359
11360                boolean mounted = PackageHelper.isContainerMounted(cid);
11361                if (!mounted) {
11362                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11363                }
11364            }
11365            return status;
11366        }
11367
11368        private void cleanUp() {
11369            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11370
11371            // Destroy secure container
11372            PackageHelper.destroySdDir(cid);
11373        }
11374
11375        private List<String> getAllCodePaths() {
11376            final File codeFile = new File(getCodePath());
11377            if (codeFile != null && codeFile.exists()) {
11378                try {
11379                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11380                    return pkg.getAllCodePaths();
11381                } catch (PackageParserException e) {
11382                    // Ignored; we tried our best
11383                }
11384            }
11385            return Collections.EMPTY_LIST;
11386        }
11387
11388        void cleanUpResourcesLI() {
11389            // Enumerate all code paths before deleting
11390            cleanUpResourcesLI(getAllCodePaths());
11391        }
11392
11393        private void cleanUpResourcesLI(List<String> allCodePaths) {
11394            cleanUp();
11395            removeDexFiles(allCodePaths, instructionSets);
11396        }
11397
11398        String getPackageName() {
11399            return getAsecPackageName(cid);
11400        }
11401
11402        boolean doPostDeleteLI(boolean delete) {
11403            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11404            final List<String> allCodePaths = getAllCodePaths();
11405            boolean mounted = PackageHelper.isContainerMounted(cid);
11406            if (mounted) {
11407                // Unmount first
11408                if (PackageHelper.unMountSdDir(cid)) {
11409                    mounted = false;
11410                }
11411            }
11412            if (!mounted && delete) {
11413                cleanUpResourcesLI(allCodePaths);
11414            }
11415            return !mounted;
11416        }
11417
11418        @Override
11419        int doPreCopy() {
11420            if (isFwdLocked()) {
11421                if (!PackageHelper.fixSdPermissions(cid,
11422                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11423                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11424                }
11425            }
11426
11427            return PackageManager.INSTALL_SUCCEEDED;
11428        }
11429
11430        @Override
11431        int doPostCopy(int uid) {
11432            if (isFwdLocked()) {
11433                if (uid < Process.FIRST_APPLICATION_UID
11434                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11435                                RES_FILE_NAME)) {
11436                    Slog.e(TAG, "Failed to finalize " + cid);
11437                    PackageHelper.destroySdDir(cid);
11438                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11439                }
11440            }
11441
11442            return PackageManager.INSTALL_SUCCEEDED;
11443        }
11444    }
11445
11446    /**
11447     * Logic to handle movement of existing installed applications.
11448     */
11449    class MoveInstallArgs extends InstallArgs {
11450        private File codeFile;
11451        private File resourceFile;
11452
11453        /** New install */
11454        MoveInstallArgs(InstallParams params) {
11455            super(params.origin, params.move, params.observer, params.installFlags,
11456                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11457                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11458                    params.grantedRuntimePermissions);
11459        }
11460
11461        int copyApk(IMediaContainerService imcs, boolean temp) {
11462            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11463                    + move.fromUuid + " to " + move.toUuid);
11464            synchronized (mInstaller) {
11465                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11466                        move.dataAppName, move.appId, move.seinfo) != 0) {
11467                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11468                }
11469            }
11470
11471            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11472            resourceFile = codeFile;
11473            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11474
11475            return PackageManager.INSTALL_SUCCEEDED;
11476        }
11477
11478        int doPreInstall(int status) {
11479            if (status != PackageManager.INSTALL_SUCCEEDED) {
11480                cleanUp(move.toUuid);
11481            }
11482            return status;
11483        }
11484
11485        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11486            if (status != PackageManager.INSTALL_SUCCEEDED) {
11487                cleanUp(move.toUuid);
11488                return false;
11489            }
11490
11491            // Reflect the move in app info
11492            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11493            pkg.applicationInfo.setCodePath(pkg.codePath);
11494            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11495            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11496            pkg.applicationInfo.setResourcePath(pkg.codePath);
11497            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11498            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11499
11500            return true;
11501        }
11502
11503        int doPostInstall(int status, int uid) {
11504            if (status == PackageManager.INSTALL_SUCCEEDED) {
11505                cleanUp(move.fromUuid);
11506            } else {
11507                cleanUp(move.toUuid);
11508            }
11509            return status;
11510        }
11511
11512        @Override
11513        String getCodePath() {
11514            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11515        }
11516
11517        @Override
11518        String getResourcePath() {
11519            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11520        }
11521
11522        private boolean cleanUp(String volumeUuid) {
11523            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11524                    move.dataAppName);
11525            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11526            synchronized (mInstallLock) {
11527                // Clean up both app data and code
11528                removeDataDirsLI(volumeUuid, move.packageName);
11529                if (codeFile.isDirectory()) {
11530                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11531                } else {
11532                    codeFile.delete();
11533                }
11534            }
11535            return true;
11536        }
11537
11538        void cleanUpResourcesLI() {
11539            throw new UnsupportedOperationException();
11540        }
11541
11542        boolean doPostDeleteLI(boolean delete) {
11543            throw new UnsupportedOperationException();
11544        }
11545    }
11546
11547    static String getAsecPackageName(String packageCid) {
11548        int idx = packageCid.lastIndexOf("-");
11549        if (idx == -1) {
11550            return packageCid;
11551        }
11552        return packageCid.substring(0, idx);
11553    }
11554
11555    // Utility method used to create code paths based on package name and available index.
11556    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11557        String idxStr = "";
11558        int idx = 1;
11559        // Fall back to default value of idx=1 if prefix is not
11560        // part of oldCodePath
11561        if (oldCodePath != null) {
11562            String subStr = oldCodePath;
11563            // Drop the suffix right away
11564            if (suffix != null && subStr.endsWith(suffix)) {
11565                subStr = subStr.substring(0, subStr.length() - suffix.length());
11566            }
11567            // If oldCodePath already contains prefix find out the
11568            // ending index to either increment or decrement.
11569            int sidx = subStr.lastIndexOf(prefix);
11570            if (sidx != -1) {
11571                subStr = subStr.substring(sidx + prefix.length());
11572                if (subStr != null) {
11573                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11574                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11575                    }
11576                    try {
11577                        idx = Integer.parseInt(subStr);
11578                        if (idx <= 1) {
11579                            idx++;
11580                        } else {
11581                            idx--;
11582                        }
11583                    } catch(NumberFormatException e) {
11584                    }
11585                }
11586            }
11587        }
11588        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11589        return prefix + idxStr;
11590    }
11591
11592    private File getNextCodePath(File targetDir, String packageName) {
11593        int suffix = 1;
11594        File result;
11595        do {
11596            result = new File(targetDir, packageName + "-" + suffix);
11597            suffix++;
11598        } while (result.exists());
11599        return result;
11600    }
11601
11602    // Utility method that returns the relative package path with respect
11603    // to the installation directory. Like say for /data/data/com.test-1.apk
11604    // string com.test-1 is returned.
11605    static String deriveCodePathName(String codePath) {
11606        if (codePath == null) {
11607            return null;
11608        }
11609        final File codeFile = new File(codePath);
11610        final String name = codeFile.getName();
11611        if (codeFile.isDirectory()) {
11612            return name;
11613        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11614            final int lastDot = name.lastIndexOf('.');
11615            return name.substring(0, lastDot);
11616        } else {
11617            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11618            return null;
11619        }
11620    }
11621
11622    class PackageInstalledInfo {
11623        String name;
11624        int uid;
11625        // The set of users that originally had this package installed.
11626        int[] origUsers;
11627        // The set of users that now have this package installed.
11628        int[] newUsers;
11629        PackageParser.Package pkg;
11630        int returnCode;
11631        String returnMsg;
11632        PackageRemovedInfo removedInfo;
11633
11634        public void setError(int code, String msg) {
11635            returnCode = code;
11636            returnMsg = msg;
11637            Slog.w(TAG, msg);
11638        }
11639
11640        public void setError(String msg, PackageParserException e) {
11641            returnCode = e.error;
11642            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11643            Slog.w(TAG, msg, e);
11644        }
11645
11646        public void setError(String msg, PackageManagerException e) {
11647            returnCode = e.error;
11648            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11649            Slog.w(TAG, msg, e);
11650        }
11651
11652        // In some error cases we want to convey more info back to the observer
11653        String origPackage;
11654        String origPermission;
11655    }
11656
11657    /*
11658     * Install a non-existing package.
11659     */
11660    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11661            UserHandle user, String installerPackageName, String volumeUuid,
11662            PackageInstalledInfo res) {
11663        // Remember this for later, in case we need to rollback this install
11664        String pkgName = pkg.packageName;
11665
11666        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11667        final boolean dataDirExists = Environment
11668                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11669        synchronized(mPackages) {
11670            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11671                // A package with the same name is already installed, though
11672                // it has been renamed to an older name.  The package we
11673                // are trying to install should be installed as an update to
11674                // the existing one, but that has not been requested, so bail.
11675                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11676                        + " without first uninstalling package running as "
11677                        + mSettings.mRenamedPackages.get(pkgName));
11678                return;
11679            }
11680            if (mPackages.containsKey(pkgName)) {
11681                // Don't allow installation over an existing package with the same name.
11682                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11683                        + " without first uninstalling.");
11684                return;
11685            }
11686        }
11687
11688        try {
11689            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11690                    System.currentTimeMillis(), user);
11691
11692            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11693            // delete the partially installed application. the data directory will have to be
11694            // restored if it was already existing
11695            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11696                // remove package from internal structures.  Note that we want deletePackageX to
11697                // delete the package data and cache directories that it created in
11698                // scanPackageLocked, unless those directories existed before we even tried to
11699                // install.
11700                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11701                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11702                                res.removedInfo, true);
11703            }
11704
11705        } catch (PackageManagerException e) {
11706            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11707        }
11708    }
11709
11710    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11711        // Can't rotate keys during boot or if sharedUser.
11712        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11713                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11714            return false;
11715        }
11716        // app is using upgradeKeySets; make sure all are valid
11717        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11718        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11719        for (int i = 0; i < upgradeKeySets.length; i++) {
11720            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11721                Slog.wtf(TAG, "Package "
11722                         + (oldPs.name != null ? oldPs.name : "<null>")
11723                         + " contains upgrade-key-set reference to unknown key-set: "
11724                         + upgradeKeySets[i]
11725                         + " reverting to signatures check.");
11726                return false;
11727            }
11728        }
11729        return true;
11730    }
11731
11732    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11733        // Upgrade keysets are being used.  Determine if new package has a superset of the
11734        // required keys.
11735        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11736        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11737        for (int i = 0; i < upgradeKeySets.length; i++) {
11738            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11739            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11740                return true;
11741            }
11742        }
11743        return false;
11744    }
11745
11746    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11747            UserHandle user, String installerPackageName, String volumeUuid,
11748            PackageInstalledInfo res) {
11749        final PackageParser.Package oldPackage;
11750        final String pkgName = pkg.packageName;
11751        final int[] allUsers;
11752        final boolean[] perUserInstalled;
11753        final boolean weFroze;
11754
11755        // First find the old package info and check signatures
11756        synchronized(mPackages) {
11757            oldPackage = mPackages.get(pkgName);
11758            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11759            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11760            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11761                if(!checkUpgradeKeySetLP(ps, pkg)) {
11762                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11763                            "New package not signed by keys specified by upgrade-keysets: "
11764                            + pkgName);
11765                    return;
11766                }
11767            } else {
11768                // default to original signature matching
11769                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11770                    != PackageManager.SIGNATURE_MATCH) {
11771                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11772                            "New package has a different signature: " + pkgName);
11773                    return;
11774                }
11775            }
11776
11777            // In case of rollback, remember per-user/profile install state
11778            allUsers = sUserManager.getUserIds();
11779            perUserInstalled = new boolean[allUsers.length];
11780            for (int i = 0; i < allUsers.length; i++) {
11781                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11782            }
11783
11784            // Mark the app as frozen to prevent launching during the upgrade
11785            // process, and then kill all running instances
11786            if (!ps.frozen) {
11787                ps.frozen = true;
11788                weFroze = true;
11789            } else {
11790                weFroze = false;
11791            }
11792        }
11793
11794        // Now that we're guarded by frozen state, kill app during upgrade
11795        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11796
11797        try {
11798            boolean sysPkg = (isSystemApp(oldPackage));
11799            if (sysPkg) {
11800                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11801                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11802            } else {
11803                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11804                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11805            }
11806        } finally {
11807            // Regardless of success or failure of upgrade steps above, always
11808            // unfreeze the package if we froze it
11809            if (weFroze) {
11810                unfreezePackage(pkgName);
11811            }
11812        }
11813    }
11814
11815    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11816            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11817            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11818            String volumeUuid, PackageInstalledInfo res) {
11819        String pkgName = deletedPackage.packageName;
11820        boolean deletedPkg = true;
11821        boolean updatedSettings = false;
11822
11823        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11824                + deletedPackage);
11825        long origUpdateTime;
11826        if (pkg.mExtras != null) {
11827            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11828        } else {
11829            origUpdateTime = 0;
11830        }
11831
11832        // First delete the existing package while retaining the data directory
11833        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11834                res.removedInfo, true)) {
11835            // If the existing package wasn't successfully deleted
11836            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11837            deletedPkg = false;
11838        } else {
11839            // Successfully deleted the old package; proceed with replace.
11840
11841            // If deleted package lived in a container, give users a chance to
11842            // relinquish resources before killing.
11843            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11844                if (DEBUG_INSTALL) {
11845                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11846                }
11847                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11848                final ArrayList<String> pkgList = new ArrayList<String>(1);
11849                pkgList.add(deletedPackage.applicationInfo.packageName);
11850                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11851            }
11852
11853            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11854            try {
11855                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11856                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11857                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11858                        perUserInstalled, res, user);
11859                updatedSettings = true;
11860            } catch (PackageManagerException e) {
11861                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11862            }
11863        }
11864
11865        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11866            // remove package from internal structures.  Note that we want deletePackageX to
11867            // delete the package data and cache directories that it created in
11868            // scanPackageLocked, unless those directories existed before we even tried to
11869            // install.
11870            if(updatedSettings) {
11871                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11872                deletePackageLI(
11873                        pkgName, null, true, allUsers, perUserInstalled,
11874                        PackageManager.DELETE_KEEP_DATA,
11875                                res.removedInfo, true);
11876            }
11877            // Since we failed to install the new package we need to restore the old
11878            // package that we deleted.
11879            if (deletedPkg) {
11880                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11881                File restoreFile = new File(deletedPackage.codePath);
11882                // Parse old package
11883                boolean oldExternal = isExternal(deletedPackage);
11884                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11885                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11886                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11887                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11888                try {
11889                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11890                } catch (PackageManagerException e) {
11891                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11892                            + e.getMessage());
11893                    return;
11894                }
11895                // Restore of old package succeeded. Update permissions.
11896                // writer
11897                synchronized (mPackages) {
11898                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11899                            UPDATE_PERMISSIONS_ALL);
11900                    // can downgrade to reader
11901                    mSettings.writeLPr();
11902                }
11903                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11904            }
11905        }
11906    }
11907
11908    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11909            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11910            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11911            String volumeUuid, PackageInstalledInfo res) {
11912        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11913                + ", old=" + deletedPackage);
11914        boolean disabledSystem = false;
11915        boolean updatedSettings = false;
11916        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11917        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11918                != 0) {
11919            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11920        }
11921        String packageName = deletedPackage.packageName;
11922        if (packageName == null) {
11923            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11924                    "Attempt to delete null packageName.");
11925            return;
11926        }
11927        PackageParser.Package oldPkg;
11928        PackageSetting oldPkgSetting;
11929        // reader
11930        synchronized (mPackages) {
11931            oldPkg = mPackages.get(packageName);
11932            oldPkgSetting = mSettings.mPackages.get(packageName);
11933            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11934                    (oldPkgSetting == null)) {
11935                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11936                        "Couldn't find package:" + packageName + " information");
11937                return;
11938            }
11939        }
11940
11941        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11942        res.removedInfo.removedPackage = packageName;
11943        // Remove existing system package
11944        removePackageLI(oldPkgSetting, true);
11945        // writer
11946        synchronized (mPackages) {
11947            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11948            if (!disabledSystem && deletedPackage != null) {
11949                // We didn't need to disable the .apk as a current system package,
11950                // which means we are replacing another update that is already
11951                // installed.  We need to make sure to delete the older one's .apk.
11952                res.removedInfo.args = createInstallArgsForExisting(0,
11953                        deletedPackage.applicationInfo.getCodePath(),
11954                        deletedPackage.applicationInfo.getResourcePath(),
11955                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11956            } else {
11957                res.removedInfo.args = null;
11958            }
11959        }
11960
11961        // Successfully disabled the old package. Now proceed with re-installation
11962        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11963
11964        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11965        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11966
11967        PackageParser.Package newPackage = null;
11968        try {
11969            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11970            if (newPackage.mExtras != null) {
11971                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11972                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11973                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11974
11975                // is the update attempting to change shared user? that isn't going to work...
11976                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11977                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11978                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11979                            + " to " + newPkgSetting.sharedUser);
11980                    updatedSettings = true;
11981                }
11982            }
11983
11984            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11985                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11986                        perUserInstalled, res, user);
11987                updatedSettings = true;
11988            }
11989
11990        } catch (PackageManagerException e) {
11991            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11992        }
11993
11994        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11995            // Re installation failed. Restore old information
11996            // Remove new pkg information
11997            if (newPackage != null) {
11998                removeInstalledPackageLI(newPackage, true);
11999            }
12000            // Add back the old system package
12001            try {
12002                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12003            } catch (PackageManagerException e) {
12004                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12005            }
12006            // Restore the old system information in Settings
12007            synchronized (mPackages) {
12008                if (disabledSystem) {
12009                    mSettings.enableSystemPackageLPw(packageName);
12010                }
12011                if (updatedSettings) {
12012                    mSettings.setInstallerPackageName(packageName,
12013                            oldPkgSetting.installerPackageName);
12014                }
12015                mSettings.writeLPr();
12016            }
12017        }
12018    }
12019
12020    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12021            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12022            UserHandle user) {
12023        String pkgName = newPackage.packageName;
12024        synchronized (mPackages) {
12025            //write settings. the installStatus will be incomplete at this stage.
12026            //note that the new package setting would have already been
12027            //added to mPackages. It hasn't been persisted yet.
12028            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12029            mSettings.writeLPr();
12030        }
12031
12032        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12033
12034        synchronized (mPackages) {
12035            updatePermissionsLPw(newPackage.packageName, newPackage,
12036                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12037                            ? UPDATE_PERMISSIONS_ALL : 0));
12038            // For system-bundled packages, we assume that installing an upgraded version
12039            // of the package implies that the user actually wants to run that new code,
12040            // so we enable the package.
12041            PackageSetting ps = mSettings.mPackages.get(pkgName);
12042            if (ps != null) {
12043                if (isSystemApp(newPackage)) {
12044                    // NB: implicit assumption that system package upgrades apply to all users
12045                    if (DEBUG_INSTALL) {
12046                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12047                    }
12048                    if (res.origUsers != null) {
12049                        for (int userHandle : res.origUsers) {
12050                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12051                                    userHandle, installerPackageName);
12052                        }
12053                    }
12054                    // Also convey the prior install/uninstall state
12055                    if (allUsers != null && perUserInstalled != null) {
12056                        for (int i = 0; i < allUsers.length; i++) {
12057                            if (DEBUG_INSTALL) {
12058                                Slog.d(TAG, "    user " + allUsers[i]
12059                                        + " => " + perUserInstalled[i]);
12060                            }
12061                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12062                        }
12063                        // these install state changes will be persisted in the
12064                        // upcoming call to mSettings.writeLPr().
12065                    }
12066                }
12067                // It's implied that when a user requests installation, they want the app to be
12068                // installed and enabled.
12069                int userId = user.getIdentifier();
12070                if (userId != UserHandle.USER_ALL) {
12071                    ps.setInstalled(true, userId);
12072                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12073                }
12074            }
12075            res.name = pkgName;
12076            res.uid = newPackage.applicationInfo.uid;
12077            res.pkg = newPackage;
12078            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12079            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12080            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12081            //to update install status
12082            mSettings.writeLPr();
12083        }
12084    }
12085
12086    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12087        final int installFlags = args.installFlags;
12088        final String installerPackageName = args.installerPackageName;
12089        final String volumeUuid = args.volumeUuid;
12090        final File tmpPackageFile = new File(args.getCodePath());
12091        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12092        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12093                || (args.volumeUuid != null));
12094        boolean replace = false;
12095        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12096        if (args.move != null) {
12097            // moving a complete application; perfom an initial scan on the new install location
12098            scanFlags |= SCAN_INITIAL;
12099        }
12100        // Result object to be returned
12101        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12102
12103        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12104        // Retrieve PackageSettings and parse package
12105        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12106                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12107                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12108        PackageParser pp = new PackageParser();
12109        pp.setSeparateProcesses(mSeparateProcesses);
12110        pp.setDisplayMetrics(mMetrics);
12111
12112        final PackageParser.Package pkg;
12113        try {
12114            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12115        } catch (PackageParserException e) {
12116            res.setError("Failed parse during installPackageLI", e);
12117            return;
12118        }
12119
12120        // Mark that we have an install time CPU ABI override.
12121        pkg.cpuAbiOverride = args.abiOverride;
12122
12123        String pkgName = res.name = pkg.packageName;
12124        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12125            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12126                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12127                return;
12128            }
12129        }
12130
12131        try {
12132            pp.collectCertificates(pkg, parseFlags);
12133            pp.collectManifestDigest(pkg);
12134        } catch (PackageParserException e) {
12135            res.setError("Failed collect during installPackageLI", e);
12136            return;
12137        }
12138
12139        /* If the installer passed in a manifest digest, compare it now. */
12140        if (args.manifestDigest != null) {
12141            if (DEBUG_INSTALL) {
12142                final String parsedManifest = pkg.manifestDigest == null ? "null"
12143                        : pkg.manifestDigest.toString();
12144                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12145                        + parsedManifest);
12146            }
12147
12148            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12149                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12150                return;
12151            }
12152        } else if (DEBUG_INSTALL) {
12153            final String parsedManifest = pkg.manifestDigest == null
12154                    ? "null" : pkg.manifestDigest.toString();
12155            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12156        }
12157
12158        // Get rid of all references to package scan path via parser.
12159        pp = null;
12160        String oldCodePath = null;
12161        boolean systemApp = false;
12162        synchronized (mPackages) {
12163            // Check if installing already existing package
12164            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12165                String oldName = mSettings.mRenamedPackages.get(pkgName);
12166                if (pkg.mOriginalPackages != null
12167                        && pkg.mOriginalPackages.contains(oldName)
12168                        && mPackages.containsKey(oldName)) {
12169                    // This package is derived from an original package,
12170                    // and this device has been updating from that original
12171                    // name.  We must continue using the original name, so
12172                    // rename the new package here.
12173                    pkg.setPackageName(oldName);
12174                    pkgName = pkg.packageName;
12175                    replace = true;
12176                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12177                            + oldName + " pkgName=" + pkgName);
12178                } else if (mPackages.containsKey(pkgName)) {
12179                    // This package, under its official name, already exists
12180                    // on the device; we should replace it.
12181                    replace = true;
12182                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12183                }
12184
12185                // Prevent apps opting out from runtime permissions
12186                if (replace) {
12187                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12188                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12189                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12190                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12191                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12192                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12193                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12194                                        + " doesn't support runtime permissions but the old"
12195                                        + " target SDK " + oldTargetSdk + " does.");
12196                        return;
12197                    }
12198                }
12199            }
12200
12201            PackageSetting ps = mSettings.mPackages.get(pkgName);
12202            if (ps != null) {
12203                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12204
12205                // Quick sanity check that we're signed correctly if updating;
12206                // we'll check this again later when scanning, but we want to
12207                // bail early here before tripping over redefined permissions.
12208                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12209                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12210                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12211                                + pkg.packageName + " upgrade keys do not match the "
12212                                + "previously installed version");
12213                        return;
12214                    }
12215                } else {
12216                    try {
12217                        verifySignaturesLP(ps, pkg);
12218                    } catch (PackageManagerException e) {
12219                        res.setError(e.error, e.getMessage());
12220                        return;
12221                    }
12222                }
12223
12224                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12225                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12226                    systemApp = (ps.pkg.applicationInfo.flags &
12227                            ApplicationInfo.FLAG_SYSTEM) != 0;
12228                }
12229                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12230            }
12231
12232            // Check whether the newly-scanned package wants to define an already-defined perm
12233            int N = pkg.permissions.size();
12234            for (int i = N-1; i >= 0; i--) {
12235                PackageParser.Permission perm = pkg.permissions.get(i);
12236                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12237                if (bp != null) {
12238                    // If the defining package is signed with our cert, it's okay.  This
12239                    // also includes the "updating the same package" case, of course.
12240                    // "updating same package" could also involve key-rotation.
12241                    final boolean sigsOk;
12242                    if (bp.sourcePackage.equals(pkg.packageName)
12243                            && (bp.packageSetting instanceof PackageSetting)
12244                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12245                                    scanFlags))) {
12246                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12247                    } else {
12248                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12249                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12250                    }
12251                    if (!sigsOk) {
12252                        // If the owning package is the system itself, we log but allow
12253                        // install to proceed; we fail the install on all other permission
12254                        // redefinitions.
12255                        if (!bp.sourcePackage.equals("android")) {
12256                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12257                                    + pkg.packageName + " attempting to redeclare permission "
12258                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12259                            res.origPermission = perm.info.name;
12260                            res.origPackage = bp.sourcePackage;
12261                            return;
12262                        } else {
12263                            Slog.w(TAG, "Package " + pkg.packageName
12264                                    + " attempting to redeclare system permission "
12265                                    + perm.info.name + "; ignoring new declaration");
12266                            pkg.permissions.remove(i);
12267                        }
12268                    }
12269                }
12270            }
12271
12272        }
12273
12274        if (systemApp && onExternal) {
12275            // Disable updates to system apps on sdcard
12276            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12277                    "Cannot install updates to system apps on sdcard");
12278            return;
12279        }
12280
12281        if (args.move != null) {
12282            // We did an in-place move, so dex is ready to roll
12283            scanFlags |= SCAN_NO_DEX;
12284            scanFlags |= SCAN_MOVE;
12285
12286            synchronized (mPackages) {
12287                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12288                if (ps == null) {
12289                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12290                            "Missing settings for moved package " + pkgName);
12291                }
12292
12293                // We moved the entire application as-is, so bring over the
12294                // previously derived ABI information.
12295                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12296                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12297            }
12298
12299        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12300            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12301            scanFlags |= SCAN_NO_DEX;
12302
12303            try {
12304                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12305                        true /* extract libs */);
12306            } catch (PackageManagerException pme) {
12307                Slog.e(TAG, "Error deriving application ABI", pme);
12308                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12309                return;
12310            }
12311
12312            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12313            int result = mPackageDexOptimizer
12314                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12315                            false /* defer */, false /* inclDependencies */);
12316            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12317                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12318                return;
12319            }
12320        }
12321
12322        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12323            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12324            return;
12325        }
12326
12327        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12328
12329        if (replace) {
12330            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12331                    installerPackageName, volumeUuid, res);
12332        } else {
12333            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12334                    args.user, installerPackageName, volumeUuid, res);
12335        }
12336        synchronized (mPackages) {
12337            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12338            if (ps != null) {
12339                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12340            }
12341        }
12342    }
12343
12344    private void startIntentFilterVerifications(int userId, boolean replacing,
12345            PackageParser.Package pkg) {
12346        if (mIntentFilterVerifierComponent == null) {
12347            Slog.w(TAG, "No IntentFilter verification will not be done as "
12348                    + "there is no IntentFilterVerifier available!");
12349            return;
12350        }
12351
12352        final int verifierUid = getPackageUid(
12353                mIntentFilterVerifierComponent.getPackageName(),
12354                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12355
12356        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12357        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12358        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12359        mHandler.sendMessage(msg);
12360    }
12361
12362    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12363            PackageParser.Package pkg) {
12364        int size = pkg.activities.size();
12365        if (size == 0) {
12366            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12367                    "No activity, so no need to verify any IntentFilter!");
12368            return;
12369        }
12370
12371        final boolean hasDomainURLs = hasDomainURLs(pkg);
12372        if (!hasDomainURLs) {
12373            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12374                    "No domain URLs, so no need to verify any IntentFilter!");
12375            return;
12376        }
12377
12378        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12379                + " if any IntentFilter from the " + size
12380                + " Activities needs verification ...");
12381
12382        int count = 0;
12383        final String packageName = pkg.packageName;
12384
12385        synchronized (mPackages) {
12386            // If this is a new install and we see that we've already run verification for this
12387            // package, we have nothing to do: it means the state was restored from backup.
12388            if (!replacing) {
12389                IntentFilterVerificationInfo ivi =
12390                        mSettings.getIntentFilterVerificationLPr(packageName);
12391                if (ivi != null) {
12392                    if (DEBUG_DOMAIN_VERIFICATION) {
12393                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12394                                + ivi.getStatusString());
12395                    }
12396                    return;
12397                }
12398            }
12399
12400            // If any filters need to be verified, then all need to be.
12401            boolean needToVerify = false;
12402            for (PackageParser.Activity a : pkg.activities) {
12403                for (ActivityIntentInfo filter : a.intents) {
12404                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12405                        if (DEBUG_DOMAIN_VERIFICATION) {
12406                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12407                        }
12408                        needToVerify = true;
12409                        break;
12410                    }
12411                }
12412            }
12413
12414            if (needToVerify) {
12415                final int verificationId = mIntentFilterVerificationToken++;
12416                for (PackageParser.Activity a : pkg.activities) {
12417                    for (ActivityIntentInfo filter : a.intents) {
12418                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12419                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12420                                    "Verification needed for IntentFilter:" + filter.toString());
12421                            mIntentFilterVerifier.addOneIntentFilterVerification(
12422                                    verifierUid, userId, verificationId, filter, packageName);
12423                            count++;
12424                        }
12425                    }
12426                }
12427            }
12428        }
12429
12430        if (count > 0) {
12431            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12432                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12433                    +  " for userId:" + userId);
12434            mIntentFilterVerifier.startVerifications(userId);
12435        } else {
12436            if (DEBUG_DOMAIN_VERIFICATION) {
12437                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12438            }
12439        }
12440    }
12441
12442    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12443        final ComponentName cn  = filter.activity.getComponentName();
12444        final String packageName = cn.getPackageName();
12445
12446        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12447                packageName);
12448        if (ivi == null) {
12449            return true;
12450        }
12451        int status = ivi.getStatus();
12452        switch (status) {
12453            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12454            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12455                return true;
12456
12457            default:
12458                // Nothing to do
12459                return false;
12460        }
12461    }
12462
12463    private static boolean isMultiArch(PackageSetting ps) {
12464        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12465    }
12466
12467    private static boolean isMultiArch(ApplicationInfo info) {
12468        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12469    }
12470
12471    private static boolean isExternal(PackageParser.Package pkg) {
12472        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12473    }
12474
12475    private static boolean isExternal(PackageSetting ps) {
12476        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12477    }
12478
12479    private static boolean isExternal(ApplicationInfo info) {
12480        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12481    }
12482
12483    private static boolean isSystemApp(PackageParser.Package pkg) {
12484        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12485    }
12486
12487    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12488        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12489    }
12490
12491    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12492        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12493    }
12494
12495    private static boolean isSystemApp(PackageSetting ps) {
12496        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12497    }
12498
12499    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12500        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12501    }
12502
12503    private int packageFlagsToInstallFlags(PackageSetting ps) {
12504        int installFlags = 0;
12505        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12506            // This existing package was an external ASEC install when we have
12507            // the external flag without a UUID
12508            installFlags |= PackageManager.INSTALL_EXTERNAL;
12509        }
12510        if (ps.isForwardLocked()) {
12511            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12512        }
12513        return installFlags;
12514    }
12515
12516    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12517        if (isExternal(pkg)) {
12518            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12519                return mSettings.getExternalVersion();
12520            } else {
12521                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12522            }
12523        } else {
12524            return mSettings.getInternalVersion();
12525        }
12526    }
12527
12528    private void deleteTempPackageFiles() {
12529        final FilenameFilter filter = new FilenameFilter() {
12530            public boolean accept(File dir, String name) {
12531                return name.startsWith("vmdl") && name.endsWith(".tmp");
12532            }
12533        };
12534        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12535            file.delete();
12536        }
12537    }
12538
12539    @Override
12540    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12541            int flags) {
12542        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12543                flags);
12544    }
12545
12546    @Override
12547    public void deletePackage(final String packageName,
12548            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12549        mContext.enforceCallingOrSelfPermission(
12550                android.Manifest.permission.DELETE_PACKAGES, null);
12551        Preconditions.checkNotNull(packageName);
12552        Preconditions.checkNotNull(observer);
12553        final int uid = Binder.getCallingUid();
12554        if (UserHandle.getUserId(uid) != userId) {
12555            mContext.enforceCallingPermission(
12556                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12557                    "deletePackage for user " + userId);
12558        }
12559        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12560            try {
12561                observer.onPackageDeleted(packageName,
12562                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12563            } catch (RemoteException re) {
12564            }
12565            return;
12566        }
12567
12568        boolean uninstallBlocked = false;
12569        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12570            int[] users = sUserManager.getUserIds();
12571            for (int i = 0; i < users.length; ++i) {
12572                if (getBlockUninstallForUser(packageName, users[i])) {
12573                    uninstallBlocked = true;
12574                    break;
12575                }
12576            }
12577        } else {
12578            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12579        }
12580        if (uninstallBlocked) {
12581            try {
12582                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12583                        null);
12584            } catch (RemoteException re) {
12585            }
12586            return;
12587        }
12588
12589        if (DEBUG_REMOVE) {
12590            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12591        }
12592        // Queue up an async operation since the package deletion may take a little while.
12593        mHandler.post(new Runnable() {
12594            public void run() {
12595                mHandler.removeCallbacks(this);
12596                final int returnCode = deletePackageX(packageName, userId, flags);
12597                if (observer != null) {
12598                    try {
12599                        observer.onPackageDeleted(packageName, returnCode, null);
12600                    } catch (RemoteException e) {
12601                        Log.i(TAG, "Observer no longer exists.");
12602                    } //end catch
12603                } //end if
12604            } //end run
12605        });
12606    }
12607
12608    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12609        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12610                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12611        try {
12612            if (dpm != null) {
12613                if (dpm.isDeviceOwner(packageName)) {
12614                    return true;
12615                }
12616                int[] users;
12617                if (userId == UserHandle.USER_ALL) {
12618                    users = sUserManager.getUserIds();
12619                } else {
12620                    users = new int[]{userId};
12621                }
12622                for (int i = 0; i < users.length; ++i) {
12623                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12624                        return true;
12625                    }
12626                }
12627            }
12628        } catch (RemoteException e) {
12629        }
12630        return false;
12631    }
12632
12633    /**
12634     *  This method is an internal method that could be get invoked either
12635     *  to delete an installed package or to clean up a failed installation.
12636     *  After deleting an installed package, a broadcast is sent to notify any
12637     *  listeners that the package has been installed. For cleaning up a failed
12638     *  installation, the broadcast is not necessary since the package's
12639     *  installation wouldn't have sent the initial broadcast either
12640     *  The key steps in deleting a package are
12641     *  deleting the package information in internal structures like mPackages,
12642     *  deleting the packages base directories through installd
12643     *  updating mSettings to reflect current status
12644     *  persisting settings for later use
12645     *  sending a broadcast if necessary
12646     */
12647    private int deletePackageX(String packageName, int userId, int flags) {
12648        final PackageRemovedInfo info = new PackageRemovedInfo();
12649        final boolean res;
12650
12651        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12652                ? UserHandle.ALL : new UserHandle(userId);
12653
12654        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12655            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12656            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12657        }
12658
12659        boolean removedForAllUsers = false;
12660        boolean systemUpdate = false;
12661
12662        // for the uninstall-updates case and restricted profiles, remember the per-
12663        // userhandle installed state
12664        int[] allUsers;
12665        boolean[] perUserInstalled;
12666        synchronized (mPackages) {
12667            PackageSetting ps = mSettings.mPackages.get(packageName);
12668            allUsers = sUserManager.getUserIds();
12669            perUserInstalled = new boolean[allUsers.length];
12670            for (int i = 0; i < allUsers.length; i++) {
12671                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12672            }
12673        }
12674
12675        synchronized (mInstallLock) {
12676            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12677            res = deletePackageLI(packageName, removeForUser,
12678                    true, allUsers, perUserInstalled,
12679                    flags | REMOVE_CHATTY, info, true);
12680            systemUpdate = info.isRemovedPackageSystemUpdate;
12681            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12682                removedForAllUsers = true;
12683            }
12684            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12685                    + " removedForAllUsers=" + removedForAllUsers);
12686        }
12687
12688        if (res) {
12689            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12690
12691            // If the removed package was a system update, the old system package
12692            // was re-enabled; we need to broadcast this information
12693            if (systemUpdate) {
12694                Bundle extras = new Bundle(1);
12695                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12696                        ? info.removedAppId : info.uid);
12697                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12698
12699                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12700                        extras, null, null, null);
12701                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12702                        extras, null, null, null);
12703                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12704                        null, packageName, null, null);
12705            }
12706        }
12707        // Force a gc here.
12708        Runtime.getRuntime().gc();
12709        // Delete the resources here after sending the broadcast to let
12710        // other processes clean up before deleting resources.
12711        if (info.args != null) {
12712            synchronized (mInstallLock) {
12713                info.args.doPostDeleteLI(true);
12714            }
12715        }
12716
12717        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12718    }
12719
12720    class PackageRemovedInfo {
12721        String removedPackage;
12722        int uid = -1;
12723        int removedAppId = -1;
12724        int[] removedUsers = null;
12725        boolean isRemovedPackageSystemUpdate = false;
12726        // Clean up resources deleted packages.
12727        InstallArgs args = null;
12728
12729        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12730            Bundle extras = new Bundle(1);
12731            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12732            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12733            if (replacing) {
12734                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12735            }
12736            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12737            if (removedPackage != null) {
12738                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12739                        extras, null, null, removedUsers);
12740                if (fullRemove && !replacing) {
12741                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12742                            extras, null, null, removedUsers);
12743                }
12744            }
12745            if (removedAppId >= 0) {
12746                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12747                        removedUsers);
12748            }
12749        }
12750    }
12751
12752    /*
12753     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12754     * flag is not set, the data directory is removed as well.
12755     * make sure this flag is set for partially installed apps. If not its meaningless to
12756     * delete a partially installed application.
12757     */
12758    private void removePackageDataLI(PackageSetting ps,
12759            int[] allUserHandles, boolean[] perUserInstalled,
12760            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12761        String packageName = ps.name;
12762        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12763        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12764        // Retrieve object to delete permissions for shared user later on
12765        final PackageSetting deletedPs;
12766        // reader
12767        synchronized (mPackages) {
12768            deletedPs = mSettings.mPackages.get(packageName);
12769            if (outInfo != null) {
12770                outInfo.removedPackage = packageName;
12771                outInfo.removedUsers = deletedPs != null
12772                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12773                        : null;
12774            }
12775        }
12776        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12777            removeDataDirsLI(ps.volumeUuid, packageName);
12778            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12779        }
12780        // writer
12781        synchronized (mPackages) {
12782            if (deletedPs != null) {
12783                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12784                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12785                    clearDefaultBrowserIfNeeded(packageName);
12786                    if (outInfo != null) {
12787                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12788                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12789                    }
12790                    updatePermissionsLPw(deletedPs.name, null, 0);
12791                    if (deletedPs.sharedUser != null) {
12792                        // Remove permissions associated with package. Since runtime
12793                        // permissions are per user we have to kill the removed package
12794                        // or packages running under the shared user of the removed
12795                        // package if revoking the permissions requested only by the removed
12796                        // package is successful and this causes a change in gids.
12797                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12798                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12799                                    userId);
12800                            if (userIdToKill == UserHandle.USER_ALL
12801                                    || userIdToKill >= UserHandle.USER_OWNER) {
12802                                // If gids changed for this user, kill all affected packages.
12803                                mHandler.post(new Runnable() {
12804                                    @Override
12805                                    public void run() {
12806                                        // This has to happen with no lock held.
12807                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12808                                                KILL_APP_REASON_GIDS_CHANGED);
12809                                    }
12810                                });
12811                                break;
12812                            }
12813                        }
12814                    }
12815                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12816                }
12817                // make sure to preserve per-user disabled state if this removal was just
12818                // a downgrade of a system app to the factory package
12819                if (allUserHandles != null && perUserInstalled != null) {
12820                    if (DEBUG_REMOVE) {
12821                        Slog.d(TAG, "Propagating install state across downgrade");
12822                    }
12823                    for (int i = 0; i < allUserHandles.length; i++) {
12824                        if (DEBUG_REMOVE) {
12825                            Slog.d(TAG, "    user " + allUserHandles[i]
12826                                    + " => " + perUserInstalled[i]);
12827                        }
12828                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12829                    }
12830                }
12831            }
12832            // can downgrade to reader
12833            if (writeSettings) {
12834                // Save settings now
12835                mSettings.writeLPr();
12836            }
12837        }
12838        if (outInfo != null) {
12839            // A user ID was deleted here. Go through all users and remove it
12840            // from KeyStore.
12841            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12842        }
12843    }
12844
12845    static boolean locationIsPrivileged(File path) {
12846        try {
12847            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12848                    .getCanonicalPath();
12849            return path.getCanonicalPath().startsWith(privilegedAppDir);
12850        } catch (IOException e) {
12851            Slog.e(TAG, "Unable to access code path " + path);
12852        }
12853        return false;
12854    }
12855
12856    /*
12857     * Tries to delete system package.
12858     */
12859    private boolean deleteSystemPackageLI(PackageSetting newPs,
12860            int[] allUserHandles, boolean[] perUserInstalled,
12861            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12862        final boolean applyUserRestrictions
12863                = (allUserHandles != null) && (perUserInstalled != null);
12864        PackageSetting disabledPs = null;
12865        // Confirm if the system package has been updated
12866        // An updated system app can be deleted. This will also have to restore
12867        // the system pkg from system partition
12868        // reader
12869        synchronized (mPackages) {
12870            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12871        }
12872        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12873                + " disabledPs=" + disabledPs);
12874        if (disabledPs == null) {
12875            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12876            return false;
12877        } else if (DEBUG_REMOVE) {
12878            Slog.d(TAG, "Deleting system pkg from data partition");
12879        }
12880        if (DEBUG_REMOVE) {
12881            if (applyUserRestrictions) {
12882                Slog.d(TAG, "Remembering install states:");
12883                for (int i = 0; i < allUserHandles.length; i++) {
12884                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12885                }
12886            }
12887        }
12888        // Delete the updated package
12889        outInfo.isRemovedPackageSystemUpdate = true;
12890        if (disabledPs.versionCode < newPs.versionCode) {
12891            // Delete data for downgrades
12892            flags &= ~PackageManager.DELETE_KEEP_DATA;
12893        } else {
12894            // Preserve data by setting flag
12895            flags |= PackageManager.DELETE_KEEP_DATA;
12896        }
12897        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12898                allUserHandles, perUserInstalled, outInfo, writeSettings);
12899        if (!ret) {
12900            return false;
12901        }
12902        // writer
12903        synchronized (mPackages) {
12904            // Reinstate the old system package
12905            mSettings.enableSystemPackageLPw(newPs.name);
12906            // Remove any native libraries from the upgraded package.
12907            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12908        }
12909        // Install the system package
12910        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12911        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12912        if (locationIsPrivileged(disabledPs.codePath)) {
12913            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12914        }
12915
12916        final PackageParser.Package newPkg;
12917        try {
12918            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12919        } catch (PackageManagerException e) {
12920            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12921            return false;
12922        }
12923
12924        // writer
12925        synchronized (mPackages) {
12926            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12927
12928            updatePermissionsLPw(newPkg.packageName, newPkg,
12929                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12930
12931            if (applyUserRestrictions) {
12932                if (DEBUG_REMOVE) {
12933                    Slog.d(TAG, "Propagating install state across reinstall");
12934                }
12935                for (int i = 0; i < allUserHandles.length; i++) {
12936                    if (DEBUG_REMOVE) {
12937                        Slog.d(TAG, "    user " + allUserHandles[i]
12938                                + " => " + perUserInstalled[i]);
12939                    }
12940                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12941
12942                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12943                }
12944                // Regardless of writeSettings we need to ensure that this restriction
12945                // state propagation is persisted
12946                mSettings.writeAllUsersPackageRestrictionsLPr();
12947            }
12948            // can downgrade to reader here
12949            if (writeSettings) {
12950                mSettings.writeLPr();
12951            }
12952        }
12953        return true;
12954    }
12955
12956    private boolean deleteInstalledPackageLI(PackageSetting ps,
12957            boolean deleteCodeAndResources, int flags,
12958            int[] allUserHandles, boolean[] perUserInstalled,
12959            PackageRemovedInfo outInfo, boolean writeSettings) {
12960        if (outInfo != null) {
12961            outInfo.uid = ps.appId;
12962        }
12963
12964        // Delete package data from internal structures and also remove data if flag is set
12965        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12966
12967        // Delete application code and resources
12968        if (deleteCodeAndResources && (outInfo != null)) {
12969            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12970                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12971            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12972        }
12973        return true;
12974    }
12975
12976    @Override
12977    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12978            int userId) {
12979        mContext.enforceCallingOrSelfPermission(
12980                android.Manifest.permission.DELETE_PACKAGES, null);
12981        synchronized (mPackages) {
12982            PackageSetting ps = mSettings.mPackages.get(packageName);
12983            if (ps == null) {
12984                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12985                return false;
12986            }
12987            if (!ps.getInstalled(userId)) {
12988                // Can't block uninstall for an app that is not installed or enabled.
12989                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12990                return false;
12991            }
12992            ps.setBlockUninstall(blockUninstall, userId);
12993            mSettings.writePackageRestrictionsLPr(userId);
12994        }
12995        return true;
12996    }
12997
12998    @Override
12999    public boolean getBlockUninstallForUser(String packageName, int userId) {
13000        synchronized (mPackages) {
13001            PackageSetting ps = mSettings.mPackages.get(packageName);
13002            if (ps == null) {
13003                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13004                return false;
13005            }
13006            return ps.getBlockUninstall(userId);
13007        }
13008    }
13009
13010    /*
13011     * This method handles package deletion in general
13012     */
13013    private boolean deletePackageLI(String packageName, UserHandle user,
13014            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13015            int flags, PackageRemovedInfo outInfo,
13016            boolean writeSettings) {
13017        if (packageName == null) {
13018            Slog.w(TAG, "Attempt to delete null packageName.");
13019            return false;
13020        }
13021        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13022        PackageSetting ps;
13023        boolean dataOnly = false;
13024        int removeUser = -1;
13025        int appId = -1;
13026        synchronized (mPackages) {
13027            ps = mSettings.mPackages.get(packageName);
13028            if (ps == null) {
13029                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13030                return false;
13031            }
13032            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13033                    && user.getIdentifier() != UserHandle.USER_ALL) {
13034                // The caller is asking that the package only be deleted for a single
13035                // user.  To do this, we just mark its uninstalled state and delete
13036                // its data.  If this is a system app, we only allow this to happen if
13037                // they have set the special DELETE_SYSTEM_APP which requests different
13038                // semantics than normal for uninstalling system apps.
13039                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13040                ps.setUserState(user.getIdentifier(),
13041                        COMPONENT_ENABLED_STATE_DEFAULT,
13042                        false, //installed
13043                        true,  //stopped
13044                        true,  //notLaunched
13045                        false, //hidden
13046                        null, null, null,
13047                        false, // blockUninstall
13048                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13049                if (!isSystemApp(ps)) {
13050                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13051                        // Other user still have this package installed, so all
13052                        // we need to do is clear this user's data and save that
13053                        // it is uninstalled.
13054                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13055                        removeUser = user.getIdentifier();
13056                        appId = ps.appId;
13057                        scheduleWritePackageRestrictionsLocked(removeUser);
13058                    } else {
13059                        // We need to set it back to 'installed' so the uninstall
13060                        // broadcasts will be sent correctly.
13061                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13062                        ps.setInstalled(true, user.getIdentifier());
13063                    }
13064                } else {
13065                    // This is a system app, so we assume that the
13066                    // other users still have this package installed, so all
13067                    // we need to do is clear this user's data and save that
13068                    // it is uninstalled.
13069                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13070                    removeUser = user.getIdentifier();
13071                    appId = ps.appId;
13072                    scheduleWritePackageRestrictionsLocked(removeUser);
13073                }
13074            }
13075        }
13076
13077        if (removeUser >= 0) {
13078            // From above, we determined that we are deleting this only
13079            // for a single user.  Continue the work here.
13080            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13081            if (outInfo != null) {
13082                outInfo.removedPackage = packageName;
13083                outInfo.removedAppId = appId;
13084                outInfo.removedUsers = new int[] {removeUser};
13085            }
13086            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13087            removeKeystoreDataIfNeeded(removeUser, appId);
13088            schedulePackageCleaning(packageName, removeUser, false);
13089            synchronized (mPackages) {
13090                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13091                    scheduleWritePackageRestrictionsLocked(removeUser);
13092                }
13093                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13094            }
13095            return true;
13096        }
13097
13098        if (dataOnly) {
13099            // Delete application data first
13100            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13101            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13102            return true;
13103        }
13104
13105        boolean ret = false;
13106        if (isSystemApp(ps)) {
13107            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13108            // When an updated system application is deleted we delete the existing resources as well and
13109            // fall back to existing code in system partition
13110            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13111                    flags, outInfo, writeSettings);
13112        } else {
13113            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13114            // Kill application pre-emptively especially for apps on sd.
13115            killApplication(packageName, ps.appId, "uninstall pkg");
13116            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13117                    allUserHandles, perUserInstalled,
13118                    outInfo, writeSettings);
13119        }
13120
13121        return ret;
13122    }
13123
13124    private final class ClearStorageConnection implements ServiceConnection {
13125        IMediaContainerService mContainerService;
13126
13127        @Override
13128        public void onServiceConnected(ComponentName name, IBinder service) {
13129            synchronized (this) {
13130                mContainerService = IMediaContainerService.Stub.asInterface(service);
13131                notifyAll();
13132            }
13133        }
13134
13135        @Override
13136        public void onServiceDisconnected(ComponentName name) {
13137        }
13138    }
13139
13140    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13141        final boolean mounted;
13142        if (Environment.isExternalStorageEmulated()) {
13143            mounted = true;
13144        } else {
13145            final String status = Environment.getExternalStorageState();
13146
13147            mounted = status.equals(Environment.MEDIA_MOUNTED)
13148                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13149        }
13150
13151        if (!mounted) {
13152            return;
13153        }
13154
13155        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13156        int[] users;
13157        if (userId == UserHandle.USER_ALL) {
13158            users = sUserManager.getUserIds();
13159        } else {
13160            users = new int[] { userId };
13161        }
13162        final ClearStorageConnection conn = new ClearStorageConnection();
13163        if (mContext.bindServiceAsUser(
13164                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13165            try {
13166                for (int curUser : users) {
13167                    long timeout = SystemClock.uptimeMillis() + 5000;
13168                    synchronized (conn) {
13169                        long now = SystemClock.uptimeMillis();
13170                        while (conn.mContainerService == null && now < timeout) {
13171                            try {
13172                                conn.wait(timeout - now);
13173                            } catch (InterruptedException e) {
13174                            }
13175                        }
13176                    }
13177                    if (conn.mContainerService == null) {
13178                        return;
13179                    }
13180
13181                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13182                    clearDirectory(conn.mContainerService,
13183                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13184                    if (allData) {
13185                        clearDirectory(conn.mContainerService,
13186                                userEnv.buildExternalStorageAppDataDirs(packageName));
13187                        clearDirectory(conn.mContainerService,
13188                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13189                    }
13190                }
13191            } finally {
13192                mContext.unbindService(conn);
13193            }
13194        }
13195    }
13196
13197    @Override
13198    public void clearApplicationUserData(final String packageName,
13199            final IPackageDataObserver observer, final int userId) {
13200        mContext.enforceCallingOrSelfPermission(
13201                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13202        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13203        // Queue up an async operation since the package deletion may take a little while.
13204        mHandler.post(new Runnable() {
13205            public void run() {
13206                mHandler.removeCallbacks(this);
13207                final boolean succeeded;
13208                synchronized (mInstallLock) {
13209                    succeeded = clearApplicationUserDataLI(packageName, userId);
13210                }
13211                clearExternalStorageDataSync(packageName, userId, true);
13212                if (succeeded) {
13213                    // invoke DeviceStorageMonitor's update method to clear any notifications
13214                    DeviceStorageMonitorInternal
13215                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13216                    if (dsm != null) {
13217                        dsm.checkMemory();
13218                    }
13219                }
13220                if(observer != null) {
13221                    try {
13222                        observer.onRemoveCompleted(packageName, succeeded);
13223                    } catch (RemoteException e) {
13224                        Log.i(TAG, "Observer no longer exists.");
13225                    }
13226                } //end if observer
13227            } //end run
13228        });
13229    }
13230
13231    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13232        if (packageName == null) {
13233            Slog.w(TAG, "Attempt to delete null packageName.");
13234            return false;
13235        }
13236
13237        // Try finding details about the requested package
13238        PackageParser.Package pkg;
13239        synchronized (mPackages) {
13240            pkg = mPackages.get(packageName);
13241            if (pkg == null) {
13242                final PackageSetting ps = mSettings.mPackages.get(packageName);
13243                if (ps != null) {
13244                    pkg = ps.pkg;
13245                }
13246            }
13247
13248            if (pkg == null) {
13249                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13250                return false;
13251            }
13252
13253            PackageSetting ps = (PackageSetting) pkg.mExtras;
13254            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13255        }
13256
13257        // Always delete data directories for package, even if we found no other
13258        // record of app. This helps users recover from UID mismatches without
13259        // resorting to a full data wipe.
13260        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13261        if (retCode < 0) {
13262            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13263            return false;
13264        }
13265
13266        final int appId = pkg.applicationInfo.uid;
13267        removeKeystoreDataIfNeeded(userId, appId);
13268
13269        // Create a native library symlink only if we have native libraries
13270        // and if the native libraries are 32 bit libraries. We do not provide
13271        // this symlink for 64 bit libraries.
13272        if (pkg.applicationInfo.primaryCpuAbi != null &&
13273                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13274            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13275            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13276                    nativeLibPath, userId) < 0) {
13277                Slog.w(TAG, "Failed linking native library dir");
13278                return false;
13279            }
13280        }
13281
13282        return true;
13283    }
13284
13285    /**
13286     * Reverts user permission state changes (permissions and flags) in
13287     * all packages for a given user.
13288     *
13289     * @param userId The device user for which to do a reset.
13290     */
13291    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13292        final int packageCount = mPackages.size();
13293        for (int i = 0; i < packageCount; i++) {
13294            PackageParser.Package pkg = mPackages.valueAt(i);
13295            PackageSetting ps = (PackageSetting) pkg.mExtras;
13296            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13297        }
13298    }
13299
13300    /**
13301     * Reverts user permission state changes (permissions and flags).
13302     *
13303     * @param ps The package for which to reset.
13304     * @param userId The device user for which to do a reset.
13305     */
13306    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13307            final PackageSetting ps, final int userId) {
13308        if (ps.pkg == null) {
13309            return;
13310        }
13311
13312        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13313                | FLAG_PERMISSION_USER_FIXED
13314                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13315
13316        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13317                | FLAG_PERMISSION_POLICY_FIXED;
13318
13319        boolean writeInstallPermissions = false;
13320        boolean writeRuntimePermissions = false;
13321
13322        final int permissionCount = ps.pkg.requestedPermissions.size();
13323        for (int i = 0; i < permissionCount; i++) {
13324            String permission = ps.pkg.requestedPermissions.get(i);
13325
13326            BasePermission bp = mSettings.mPermissions.get(permission);
13327            if (bp == null) {
13328                continue;
13329            }
13330
13331            // If shared user we just reset the state to which only this app contributed.
13332            if (ps.sharedUser != null) {
13333                boolean used = false;
13334                final int packageCount = ps.sharedUser.packages.size();
13335                for (int j = 0; j < packageCount; j++) {
13336                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13337                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13338                            && pkg.pkg.requestedPermissions.contains(permission)) {
13339                        used = true;
13340                        break;
13341                    }
13342                }
13343                if (used) {
13344                    continue;
13345                }
13346            }
13347
13348            PermissionsState permissionsState = ps.getPermissionsState();
13349
13350            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13351
13352            // Always clear the user settable flags.
13353            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13354                    bp.name) != null;
13355            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13356                if (hasInstallState) {
13357                    writeInstallPermissions = true;
13358                } else {
13359                    writeRuntimePermissions = true;
13360                }
13361            }
13362
13363            // Below is only runtime permission handling.
13364            if (!bp.isRuntime()) {
13365                continue;
13366            }
13367
13368            // Never clobber system or policy.
13369            if ((oldFlags & policyOrSystemFlags) != 0) {
13370                continue;
13371            }
13372
13373            // If this permission was granted by default, make sure it is.
13374            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13375                if (permissionsState.grantRuntimePermission(bp, userId)
13376                        != PERMISSION_OPERATION_FAILURE) {
13377                    writeRuntimePermissions = true;
13378                }
13379            } else {
13380                // Otherwise, reset the permission.
13381                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13382                switch (revokeResult) {
13383                    case PERMISSION_OPERATION_SUCCESS: {
13384                        writeRuntimePermissions = true;
13385                    } break;
13386
13387                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13388                        writeRuntimePermissions = true;
13389                        // If gids changed for this user, kill all affected packages.
13390                        mHandler.post(new Runnable() {
13391                            @Override
13392                            public void run() {
13393                                // This has to happen with no lock held.
13394                                killSettingPackagesForUser(ps, userId,
13395                                        KILL_APP_REASON_GIDS_CHANGED);
13396                            }
13397                        });
13398                    } break;
13399                }
13400            }
13401        }
13402
13403        // Synchronously write as we are taking permissions away.
13404        if (writeRuntimePermissions) {
13405            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13406        }
13407
13408        // Synchronously write as we are taking permissions away.
13409        if (writeInstallPermissions) {
13410            mSettings.writeLPr();
13411        }
13412    }
13413
13414    /**
13415     * Remove entries from the keystore daemon. Will only remove it if the
13416     * {@code appId} is valid.
13417     */
13418    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13419        if (appId < 0) {
13420            return;
13421        }
13422
13423        final KeyStore keyStore = KeyStore.getInstance();
13424        if (keyStore != null) {
13425            if (userId == UserHandle.USER_ALL) {
13426                for (final int individual : sUserManager.getUserIds()) {
13427                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13428                }
13429            } else {
13430                keyStore.clearUid(UserHandle.getUid(userId, appId));
13431            }
13432        } else {
13433            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13434        }
13435    }
13436
13437    @Override
13438    public void deleteApplicationCacheFiles(final String packageName,
13439            final IPackageDataObserver observer) {
13440        mContext.enforceCallingOrSelfPermission(
13441                android.Manifest.permission.DELETE_CACHE_FILES, null);
13442        // Queue up an async operation since the package deletion may take a little while.
13443        final int userId = UserHandle.getCallingUserId();
13444        mHandler.post(new Runnable() {
13445            public void run() {
13446                mHandler.removeCallbacks(this);
13447                final boolean succeded;
13448                synchronized (mInstallLock) {
13449                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13450                }
13451                clearExternalStorageDataSync(packageName, userId, false);
13452                if (observer != null) {
13453                    try {
13454                        observer.onRemoveCompleted(packageName, succeded);
13455                    } catch (RemoteException e) {
13456                        Log.i(TAG, "Observer no longer exists.");
13457                    }
13458                } //end if observer
13459            } //end run
13460        });
13461    }
13462
13463    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13464        if (packageName == null) {
13465            Slog.w(TAG, "Attempt to delete null packageName.");
13466            return false;
13467        }
13468        PackageParser.Package p;
13469        synchronized (mPackages) {
13470            p = mPackages.get(packageName);
13471        }
13472        if (p == null) {
13473            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13474            return false;
13475        }
13476        final ApplicationInfo applicationInfo = p.applicationInfo;
13477        if (applicationInfo == null) {
13478            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13479            return false;
13480        }
13481        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13482        if (retCode < 0) {
13483            Slog.w(TAG, "Couldn't remove cache files for package: "
13484                       + packageName + " u" + userId);
13485            return false;
13486        }
13487        return true;
13488    }
13489
13490    @Override
13491    public void getPackageSizeInfo(final String packageName, int userHandle,
13492            final IPackageStatsObserver observer) {
13493        mContext.enforceCallingOrSelfPermission(
13494                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13495        if (packageName == null) {
13496            throw new IllegalArgumentException("Attempt to get size of null packageName");
13497        }
13498
13499        PackageStats stats = new PackageStats(packageName, userHandle);
13500
13501        /*
13502         * Queue up an async operation since the package measurement may take a
13503         * little while.
13504         */
13505        Message msg = mHandler.obtainMessage(INIT_COPY);
13506        msg.obj = new MeasureParams(stats, observer);
13507        mHandler.sendMessage(msg);
13508    }
13509
13510    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13511            PackageStats pStats) {
13512        if (packageName == null) {
13513            Slog.w(TAG, "Attempt to get size of null packageName.");
13514            return false;
13515        }
13516        PackageParser.Package p;
13517        boolean dataOnly = false;
13518        String libDirRoot = null;
13519        String asecPath = null;
13520        PackageSetting ps = null;
13521        synchronized (mPackages) {
13522            p = mPackages.get(packageName);
13523            ps = mSettings.mPackages.get(packageName);
13524            if(p == null) {
13525                dataOnly = true;
13526                if((ps == null) || (ps.pkg == null)) {
13527                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13528                    return false;
13529                }
13530                p = ps.pkg;
13531            }
13532            if (ps != null) {
13533                libDirRoot = ps.legacyNativeLibraryPathString;
13534            }
13535            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13536                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13537                if (secureContainerId != null) {
13538                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13539                }
13540            }
13541        }
13542        String publicSrcDir = null;
13543        if(!dataOnly) {
13544            final ApplicationInfo applicationInfo = p.applicationInfo;
13545            if (applicationInfo == null) {
13546                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13547                return false;
13548            }
13549            if (p.isForwardLocked()) {
13550                publicSrcDir = applicationInfo.getBaseResourcePath();
13551            }
13552        }
13553        // TODO: extend to measure size of split APKs
13554        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13555        // not just the first level.
13556        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13557        // just the primary.
13558        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13559        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13560                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13561        if (res < 0) {
13562            return false;
13563        }
13564
13565        // Fix-up for forward-locked applications in ASEC containers.
13566        if (!isExternal(p)) {
13567            pStats.codeSize += pStats.externalCodeSize;
13568            pStats.externalCodeSize = 0L;
13569        }
13570
13571        return true;
13572    }
13573
13574
13575    @Override
13576    public void addPackageToPreferred(String packageName) {
13577        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13578    }
13579
13580    @Override
13581    public void removePackageFromPreferred(String packageName) {
13582        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13583    }
13584
13585    @Override
13586    public List<PackageInfo> getPreferredPackages(int flags) {
13587        return new ArrayList<PackageInfo>();
13588    }
13589
13590    private int getUidTargetSdkVersionLockedLPr(int uid) {
13591        Object obj = mSettings.getUserIdLPr(uid);
13592        if (obj instanceof SharedUserSetting) {
13593            final SharedUserSetting sus = (SharedUserSetting) obj;
13594            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13595            final Iterator<PackageSetting> it = sus.packages.iterator();
13596            while (it.hasNext()) {
13597                final PackageSetting ps = it.next();
13598                if (ps.pkg != null) {
13599                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13600                    if (v < vers) vers = v;
13601                }
13602            }
13603            return vers;
13604        } else if (obj instanceof PackageSetting) {
13605            final PackageSetting ps = (PackageSetting) obj;
13606            if (ps.pkg != null) {
13607                return ps.pkg.applicationInfo.targetSdkVersion;
13608            }
13609        }
13610        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13611    }
13612
13613    @Override
13614    public void addPreferredActivity(IntentFilter filter, int match,
13615            ComponentName[] set, ComponentName activity, int userId) {
13616        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13617                "Adding preferred");
13618    }
13619
13620    private void addPreferredActivityInternal(IntentFilter filter, int match,
13621            ComponentName[] set, ComponentName activity, boolean always, int userId,
13622            String opname) {
13623        // writer
13624        int callingUid = Binder.getCallingUid();
13625        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13626        if (filter.countActions() == 0) {
13627            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13628            return;
13629        }
13630        synchronized (mPackages) {
13631            if (mContext.checkCallingOrSelfPermission(
13632                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13633                    != PackageManager.PERMISSION_GRANTED) {
13634                if (getUidTargetSdkVersionLockedLPr(callingUid)
13635                        < Build.VERSION_CODES.FROYO) {
13636                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13637                            + callingUid);
13638                    return;
13639                }
13640                mContext.enforceCallingOrSelfPermission(
13641                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13642            }
13643
13644            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13645            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13646                    + userId + ":");
13647            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13648            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13649            scheduleWritePackageRestrictionsLocked(userId);
13650        }
13651    }
13652
13653    @Override
13654    public void replacePreferredActivity(IntentFilter filter, int match,
13655            ComponentName[] set, ComponentName activity, int userId) {
13656        if (filter.countActions() != 1) {
13657            throw new IllegalArgumentException(
13658                    "replacePreferredActivity expects filter to have only 1 action.");
13659        }
13660        if (filter.countDataAuthorities() != 0
13661                || filter.countDataPaths() != 0
13662                || filter.countDataSchemes() > 1
13663                || filter.countDataTypes() != 0) {
13664            throw new IllegalArgumentException(
13665                    "replacePreferredActivity expects filter to have no data authorities, " +
13666                    "paths, or types; and at most one scheme.");
13667        }
13668
13669        final int callingUid = Binder.getCallingUid();
13670        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13671        synchronized (mPackages) {
13672            if (mContext.checkCallingOrSelfPermission(
13673                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13674                    != PackageManager.PERMISSION_GRANTED) {
13675                if (getUidTargetSdkVersionLockedLPr(callingUid)
13676                        < Build.VERSION_CODES.FROYO) {
13677                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13678                            + Binder.getCallingUid());
13679                    return;
13680                }
13681                mContext.enforceCallingOrSelfPermission(
13682                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13683            }
13684
13685            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13686            if (pir != null) {
13687                // Get all of the existing entries that exactly match this filter.
13688                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13689                if (existing != null && existing.size() == 1) {
13690                    PreferredActivity cur = existing.get(0);
13691                    if (DEBUG_PREFERRED) {
13692                        Slog.i(TAG, "Checking replace of preferred:");
13693                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13694                        if (!cur.mPref.mAlways) {
13695                            Slog.i(TAG, "  -- CUR; not mAlways!");
13696                        } else {
13697                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13698                            Slog.i(TAG, "  -- CUR: mSet="
13699                                    + Arrays.toString(cur.mPref.mSetComponents));
13700                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13701                            Slog.i(TAG, "  -- NEW: mMatch="
13702                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13703                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13704                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13705                        }
13706                    }
13707                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13708                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13709                            && cur.mPref.sameSet(set)) {
13710                        // Setting the preferred activity to what it happens to be already
13711                        if (DEBUG_PREFERRED) {
13712                            Slog.i(TAG, "Replacing with same preferred activity "
13713                                    + cur.mPref.mShortComponent + " for user "
13714                                    + userId + ":");
13715                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13716                        }
13717                        return;
13718                    }
13719                }
13720
13721                if (existing != null) {
13722                    if (DEBUG_PREFERRED) {
13723                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13724                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13725                    }
13726                    for (int i = 0; i < existing.size(); i++) {
13727                        PreferredActivity pa = existing.get(i);
13728                        if (DEBUG_PREFERRED) {
13729                            Slog.i(TAG, "Removing existing preferred activity "
13730                                    + pa.mPref.mComponent + ":");
13731                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13732                        }
13733                        pir.removeFilter(pa);
13734                    }
13735                }
13736            }
13737            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13738                    "Replacing preferred");
13739        }
13740    }
13741
13742    @Override
13743    public void clearPackagePreferredActivities(String packageName) {
13744        final int uid = Binder.getCallingUid();
13745        // writer
13746        synchronized (mPackages) {
13747            PackageParser.Package pkg = mPackages.get(packageName);
13748            if (pkg == null || pkg.applicationInfo.uid != uid) {
13749                if (mContext.checkCallingOrSelfPermission(
13750                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13751                        != PackageManager.PERMISSION_GRANTED) {
13752                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13753                            < Build.VERSION_CODES.FROYO) {
13754                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13755                                + Binder.getCallingUid());
13756                        return;
13757                    }
13758                    mContext.enforceCallingOrSelfPermission(
13759                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13760                }
13761            }
13762
13763            int user = UserHandle.getCallingUserId();
13764            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13765                scheduleWritePackageRestrictionsLocked(user);
13766            }
13767        }
13768    }
13769
13770    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13771    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13772        ArrayList<PreferredActivity> removed = null;
13773        boolean changed = false;
13774        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13775            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13776            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13777            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13778                continue;
13779            }
13780            Iterator<PreferredActivity> it = pir.filterIterator();
13781            while (it.hasNext()) {
13782                PreferredActivity pa = it.next();
13783                // Mark entry for removal only if it matches the package name
13784                // and the entry is of type "always".
13785                if (packageName == null ||
13786                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13787                                && pa.mPref.mAlways)) {
13788                    if (removed == null) {
13789                        removed = new ArrayList<PreferredActivity>();
13790                    }
13791                    removed.add(pa);
13792                }
13793            }
13794            if (removed != null) {
13795                for (int j=0; j<removed.size(); j++) {
13796                    PreferredActivity pa = removed.get(j);
13797                    pir.removeFilter(pa);
13798                }
13799                changed = true;
13800            }
13801        }
13802        return changed;
13803    }
13804
13805    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13806    private void clearIntentFilterVerificationsLPw(int userId) {
13807        final int packageCount = mPackages.size();
13808        for (int i = 0; i < packageCount; i++) {
13809            PackageParser.Package pkg = mPackages.valueAt(i);
13810            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13811        }
13812    }
13813
13814    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13815    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13816        if (userId == UserHandle.USER_ALL) {
13817            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13818                    sUserManager.getUserIds())) {
13819                for (int oneUserId : sUserManager.getUserIds()) {
13820                    scheduleWritePackageRestrictionsLocked(oneUserId);
13821                }
13822            }
13823        } else {
13824            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13825                scheduleWritePackageRestrictionsLocked(userId);
13826            }
13827        }
13828    }
13829
13830    void clearDefaultBrowserIfNeeded(String packageName) {
13831        for (int oneUserId : sUserManager.getUserIds()) {
13832            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13833            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13834            if (packageName.equals(defaultBrowserPackageName)) {
13835                setDefaultBrowserPackageName(null, oneUserId);
13836            }
13837        }
13838    }
13839
13840    @Override
13841    public void resetApplicationPreferences(int userId) {
13842        mContext.enforceCallingOrSelfPermission(
13843                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13844        // writer
13845        synchronized (mPackages) {
13846            final long identity = Binder.clearCallingIdentity();
13847            try {
13848                clearPackagePreferredActivitiesLPw(null, userId);
13849                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13850                // TODO: We have to reset the default SMS and Phone. This requires
13851                // significant refactoring to keep all default apps in the package
13852                // manager (cleaner but more work) or have the services provide
13853                // callbacks to the package manager to request a default app reset.
13854                applyFactoryDefaultBrowserLPw(userId);
13855                clearIntentFilterVerificationsLPw(userId);
13856                primeDomainVerificationsLPw(userId);
13857                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13858                scheduleWritePackageRestrictionsLocked(userId);
13859            } finally {
13860                Binder.restoreCallingIdentity(identity);
13861            }
13862        }
13863    }
13864
13865    @Override
13866    public int getPreferredActivities(List<IntentFilter> outFilters,
13867            List<ComponentName> outActivities, String packageName) {
13868
13869        int num = 0;
13870        final int userId = UserHandle.getCallingUserId();
13871        // reader
13872        synchronized (mPackages) {
13873            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13874            if (pir != null) {
13875                final Iterator<PreferredActivity> it = pir.filterIterator();
13876                while (it.hasNext()) {
13877                    final PreferredActivity pa = it.next();
13878                    if (packageName == null
13879                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13880                                    && pa.mPref.mAlways)) {
13881                        if (outFilters != null) {
13882                            outFilters.add(new IntentFilter(pa));
13883                        }
13884                        if (outActivities != null) {
13885                            outActivities.add(pa.mPref.mComponent);
13886                        }
13887                    }
13888                }
13889            }
13890        }
13891
13892        return num;
13893    }
13894
13895    @Override
13896    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13897            int userId) {
13898        int callingUid = Binder.getCallingUid();
13899        if (callingUid != Process.SYSTEM_UID) {
13900            throw new SecurityException(
13901                    "addPersistentPreferredActivity can only be run by the system");
13902        }
13903        if (filter.countActions() == 0) {
13904            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13905            return;
13906        }
13907        synchronized (mPackages) {
13908            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13909                    " :");
13910            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13911            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13912                    new PersistentPreferredActivity(filter, activity));
13913            scheduleWritePackageRestrictionsLocked(userId);
13914        }
13915    }
13916
13917    @Override
13918    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13919        int callingUid = Binder.getCallingUid();
13920        if (callingUid != Process.SYSTEM_UID) {
13921            throw new SecurityException(
13922                    "clearPackagePersistentPreferredActivities can only be run by the system");
13923        }
13924        ArrayList<PersistentPreferredActivity> removed = null;
13925        boolean changed = false;
13926        synchronized (mPackages) {
13927            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13928                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13929                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13930                        .valueAt(i);
13931                if (userId != thisUserId) {
13932                    continue;
13933                }
13934                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13935                while (it.hasNext()) {
13936                    PersistentPreferredActivity ppa = it.next();
13937                    // Mark entry for removal only if it matches the package name.
13938                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13939                        if (removed == null) {
13940                            removed = new ArrayList<PersistentPreferredActivity>();
13941                        }
13942                        removed.add(ppa);
13943                    }
13944                }
13945                if (removed != null) {
13946                    for (int j=0; j<removed.size(); j++) {
13947                        PersistentPreferredActivity ppa = removed.get(j);
13948                        ppir.removeFilter(ppa);
13949                    }
13950                    changed = true;
13951                }
13952            }
13953
13954            if (changed) {
13955                scheduleWritePackageRestrictionsLocked(userId);
13956            }
13957        }
13958    }
13959
13960    /**
13961     * Common machinery for picking apart a restored XML blob and passing
13962     * it to a caller-supplied functor to be applied to the running system.
13963     */
13964    private void restoreFromXml(XmlPullParser parser, int userId,
13965            String expectedStartTag, BlobXmlRestorer functor)
13966            throws IOException, XmlPullParserException {
13967        int type;
13968        while ((type = parser.next()) != XmlPullParser.START_TAG
13969                && type != XmlPullParser.END_DOCUMENT) {
13970        }
13971        if (type != XmlPullParser.START_TAG) {
13972            // oops didn't find a start tag?!
13973            if (DEBUG_BACKUP) {
13974                Slog.e(TAG, "Didn't find start tag during restore");
13975            }
13976            return;
13977        }
13978
13979        // this is supposed to be TAG_PREFERRED_BACKUP
13980        if (!expectedStartTag.equals(parser.getName())) {
13981            if (DEBUG_BACKUP) {
13982                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13983            }
13984            return;
13985        }
13986
13987        // skip interfering stuff, then we're aligned with the backing implementation
13988        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13989        functor.apply(parser, userId);
13990    }
13991
13992    private interface BlobXmlRestorer {
13993        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13994    }
13995
13996    /**
13997     * Non-Binder method, support for the backup/restore mechanism: write the
13998     * full set of preferred activities in its canonical XML format.  Returns the
13999     * XML output as a byte array, or null if there is none.
14000     */
14001    @Override
14002    public byte[] getPreferredActivityBackup(int userId) {
14003        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14004            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14005        }
14006
14007        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14008        try {
14009            final XmlSerializer serializer = new FastXmlSerializer();
14010            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14011            serializer.startDocument(null, true);
14012            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14013
14014            synchronized (mPackages) {
14015                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14016            }
14017
14018            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14019            serializer.endDocument();
14020            serializer.flush();
14021        } catch (Exception e) {
14022            if (DEBUG_BACKUP) {
14023                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14024            }
14025            return null;
14026        }
14027
14028        return dataStream.toByteArray();
14029    }
14030
14031    @Override
14032    public void restorePreferredActivities(byte[] backup, int userId) {
14033        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14034            throw new SecurityException("Only the system may call restorePreferredActivities()");
14035        }
14036
14037        try {
14038            final XmlPullParser parser = Xml.newPullParser();
14039            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14040            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14041                    new BlobXmlRestorer() {
14042                        @Override
14043                        public void apply(XmlPullParser parser, int userId)
14044                                throws XmlPullParserException, IOException {
14045                            synchronized (mPackages) {
14046                                mSettings.readPreferredActivitiesLPw(parser, userId);
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    /**
14058     * Non-Binder method, support for the backup/restore mechanism: write the
14059     * default browser (etc) settings in its canonical XML format.  Returns the default
14060     * browser XML representation as a byte array, or null if there is none.
14061     */
14062    @Override
14063    public byte[] getDefaultAppsBackup(int userId) {
14064        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14065            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14066        }
14067
14068        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14069        try {
14070            final XmlSerializer serializer = new FastXmlSerializer();
14071            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14072            serializer.startDocument(null, true);
14073            serializer.startTag(null, TAG_DEFAULT_APPS);
14074
14075            synchronized (mPackages) {
14076                mSettings.writeDefaultAppsLPr(serializer, userId);
14077            }
14078
14079            serializer.endTag(null, TAG_DEFAULT_APPS);
14080            serializer.endDocument();
14081            serializer.flush();
14082        } catch (Exception e) {
14083            if (DEBUG_BACKUP) {
14084                Slog.e(TAG, "Unable to write default apps for backup", e);
14085            }
14086            return null;
14087        }
14088
14089        return dataStream.toByteArray();
14090    }
14091
14092    @Override
14093    public void restoreDefaultApps(byte[] backup, int userId) {
14094        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14095            throw new SecurityException("Only the system may call restoreDefaultApps()");
14096        }
14097
14098        try {
14099            final XmlPullParser parser = Xml.newPullParser();
14100            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14101            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14102                    new BlobXmlRestorer() {
14103                        @Override
14104                        public void apply(XmlPullParser parser, int userId)
14105                                throws XmlPullParserException, IOException {
14106                            synchronized (mPackages) {
14107                                mSettings.readDefaultAppsLPw(parser, userId);
14108                            }
14109                        }
14110                    } );
14111        } catch (Exception e) {
14112            if (DEBUG_BACKUP) {
14113                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14114            }
14115        }
14116    }
14117
14118    @Override
14119    public byte[] getIntentFilterVerificationBackup(int userId) {
14120        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14121            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14122        }
14123
14124        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14125        try {
14126            final XmlSerializer serializer = new FastXmlSerializer();
14127            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14128            serializer.startDocument(null, true);
14129            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14130
14131            synchronized (mPackages) {
14132                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14133            }
14134
14135            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14136            serializer.endDocument();
14137            serializer.flush();
14138        } catch (Exception e) {
14139            if (DEBUG_BACKUP) {
14140                Slog.e(TAG, "Unable to write default apps for backup", e);
14141            }
14142            return null;
14143        }
14144
14145        return dataStream.toByteArray();
14146    }
14147
14148    @Override
14149    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14150        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14151            throw new SecurityException("Only the system may call restorePreferredActivities()");
14152        }
14153
14154        try {
14155            final XmlPullParser parser = Xml.newPullParser();
14156            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14157            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14158                    new BlobXmlRestorer() {
14159                        @Override
14160                        public void apply(XmlPullParser parser, int userId)
14161                                throws XmlPullParserException, IOException {
14162                            synchronized (mPackages) {
14163                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14164                                mSettings.writeLPr();
14165                            }
14166                        }
14167                    } );
14168        } catch (Exception e) {
14169            if (DEBUG_BACKUP) {
14170                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14171            }
14172        }
14173    }
14174
14175    @Override
14176    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14177            int sourceUserId, int targetUserId, int flags) {
14178        mContext.enforceCallingOrSelfPermission(
14179                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14180        int callingUid = Binder.getCallingUid();
14181        enforceOwnerRights(ownerPackage, callingUid);
14182        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14183        if (intentFilter.countActions() == 0) {
14184            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14185            return;
14186        }
14187        synchronized (mPackages) {
14188            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14189                    ownerPackage, targetUserId, flags);
14190            CrossProfileIntentResolver resolver =
14191                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14192            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14193            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14194            if (existing != null) {
14195                int size = existing.size();
14196                for (int i = 0; i < size; i++) {
14197                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14198                        return;
14199                    }
14200                }
14201            }
14202            resolver.addFilter(newFilter);
14203            scheduleWritePackageRestrictionsLocked(sourceUserId);
14204        }
14205    }
14206
14207    @Override
14208    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14209        mContext.enforceCallingOrSelfPermission(
14210                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14211        int callingUid = Binder.getCallingUid();
14212        enforceOwnerRights(ownerPackage, callingUid);
14213        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14214        synchronized (mPackages) {
14215            CrossProfileIntentResolver resolver =
14216                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14217            ArraySet<CrossProfileIntentFilter> set =
14218                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14219            for (CrossProfileIntentFilter filter : set) {
14220                if (filter.getOwnerPackage().equals(ownerPackage)) {
14221                    resolver.removeFilter(filter);
14222                }
14223            }
14224            scheduleWritePackageRestrictionsLocked(sourceUserId);
14225        }
14226    }
14227
14228    // Enforcing that callingUid is owning pkg on userId
14229    private void enforceOwnerRights(String pkg, int callingUid) {
14230        // The system owns everything.
14231        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14232            return;
14233        }
14234        int callingUserId = UserHandle.getUserId(callingUid);
14235        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14236        if (pi == null) {
14237            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14238                    + callingUserId);
14239        }
14240        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14241            throw new SecurityException("Calling uid " + callingUid
14242                    + " does not own package " + pkg);
14243        }
14244    }
14245
14246    @Override
14247    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14248        Intent intent = new Intent(Intent.ACTION_MAIN);
14249        intent.addCategory(Intent.CATEGORY_HOME);
14250
14251        final int callingUserId = UserHandle.getCallingUserId();
14252        List<ResolveInfo> list = queryIntentActivities(intent, null,
14253                PackageManager.GET_META_DATA, callingUserId);
14254        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14255                true, false, false, callingUserId);
14256
14257        allHomeCandidates.clear();
14258        if (list != null) {
14259            for (ResolveInfo ri : list) {
14260                allHomeCandidates.add(ri);
14261            }
14262        }
14263        return (preferred == null || preferred.activityInfo == null)
14264                ? null
14265                : new ComponentName(preferred.activityInfo.packageName,
14266                        preferred.activityInfo.name);
14267    }
14268
14269    @Override
14270    public void setApplicationEnabledSetting(String appPackageName,
14271            int newState, int flags, int userId, String callingPackage) {
14272        if (!sUserManager.exists(userId)) return;
14273        if (callingPackage == null) {
14274            callingPackage = Integer.toString(Binder.getCallingUid());
14275        }
14276        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14277    }
14278
14279    @Override
14280    public void setComponentEnabledSetting(ComponentName componentName,
14281            int newState, int flags, int userId) {
14282        if (!sUserManager.exists(userId)) return;
14283        setEnabledSetting(componentName.getPackageName(),
14284                componentName.getClassName(), newState, flags, userId, null);
14285    }
14286
14287    private void setEnabledSetting(final String packageName, String className, int newState,
14288            final int flags, int userId, String callingPackage) {
14289        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14290              || newState == COMPONENT_ENABLED_STATE_ENABLED
14291              || newState == COMPONENT_ENABLED_STATE_DISABLED
14292              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14293              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14294            throw new IllegalArgumentException("Invalid new component state: "
14295                    + newState);
14296        }
14297        PackageSetting pkgSetting;
14298        final int uid = Binder.getCallingUid();
14299        final int permission = mContext.checkCallingOrSelfPermission(
14300                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14301        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14302        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14303        boolean sendNow = false;
14304        boolean isApp = (className == null);
14305        String componentName = isApp ? packageName : className;
14306        int packageUid = -1;
14307        ArrayList<String> components;
14308
14309        // writer
14310        synchronized (mPackages) {
14311            pkgSetting = mSettings.mPackages.get(packageName);
14312            if (pkgSetting == null) {
14313                if (className == null) {
14314                    throw new IllegalArgumentException(
14315                            "Unknown package: " + packageName);
14316                }
14317                throw new IllegalArgumentException(
14318                        "Unknown component: " + packageName
14319                        + "/" + className);
14320            }
14321            // Allow root and verify that userId is not being specified by a different user
14322            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14323                throw new SecurityException(
14324                        "Permission Denial: attempt to change component state from pid="
14325                        + Binder.getCallingPid()
14326                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14327            }
14328            if (className == null) {
14329                // We're dealing with an application/package level state change
14330                if (pkgSetting.getEnabled(userId) == newState) {
14331                    // Nothing to do
14332                    return;
14333                }
14334                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14335                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14336                    // Don't care about who enables an app.
14337                    callingPackage = null;
14338                }
14339                pkgSetting.setEnabled(newState, userId, callingPackage);
14340                // pkgSetting.pkg.mSetEnabled = newState;
14341            } else {
14342                // We're dealing with a component level state change
14343                // First, verify that this is a valid class name.
14344                PackageParser.Package pkg = pkgSetting.pkg;
14345                if (pkg == null || !pkg.hasComponentClassName(className)) {
14346                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14347                        throw new IllegalArgumentException("Component class " + className
14348                                + " does not exist in " + packageName);
14349                    } else {
14350                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14351                                + className + " does not exist in " + packageName);
14352                    }
14353                }
14354                switch (newState) {
14355                case COMPONENT_ENABLED_STATE_ENABLED:
14356                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14357                        return;
14358                    }
14359                    break;
14360                case COMPONENT_ENABLED_STATE_DISABLED:
14361                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14362                        return;
14363                    }
14364                    break;
14365                case COMPONENT_ENABLED_STATE_DEFAULT:
14366                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14367                        return;
14368                    }
14369                    break;
14370                default:
14371                    Slog.e(TAG, "Invalid new component state: " + newState);
14372                    return;
14373                }
14374            }
14375            scheduleWritePackageRestrictionsLocked(userId);
14376            components = mPendingBroadcasts.get(userId, packageName);
14377            final boolean newPackage = components == null;
14378            if (newPackage) {
14379                components = new ArrayList<String>();
14380            }
14381            if (!components.contains(componentName)) {
14382                components.add(componentName);
14383            }
14384            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14385                sendNow = true;
14386                // Purge entry from pending broadcast list if another one exists already
14387                // since we are sending one right away.
14388                mPendingBroadcasts.remove(userId, packageName);
14389            } else {
14390                if (newPackage) {
14391                    mPendingBroadcasts.put(userId, packageName, components);
14392                }
14393                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14394                    // Schedule a message
14395                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14396                }
14397            }
14398        }
14399
14400        long callingId = Binder.clearCallingIdentity();
14401        try {
14402            if (sendNow) {
14403                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14404                sendPackageChangedBroadcast(packageName,
14405                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14406            }
14407        } finally {
14408            Binder.restoreCallingIdentity(callingId);
14409        }
14410    }
14411
14412    private void sendPackageChangedBroadcast(String packageName,
14413            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14414        if (DEBUG_INSTALL)
14415            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14416                    + componentNames);
14417        Bundle extras = new Bundle(4);
14418        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14419        String nameList[] = new String[componentNames.size()];
14420        componentNames.toArray(nameList);
14421        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14422        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14423        extras.putInt(Intent.EXTRA_UID, packageUid);
14424        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14425                new int[] {UserHandle.getUserId(packageUid)});
14426    }
14427
14428    @Override
14429    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14430        if (!sUserManager.exists(userId)) return;
14431        final int uid = Binder.getCallingUid();
14432        final int permission = mContext.checkCallingOrSelfPermission(
14433                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14434        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14435        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14436        // writer
14437        synchronized (mPackages) {
14438            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14439                    allowedByPermission, uid, userId)) {
14440                scheduleWritePackageRestrictionsLocked(userId);
14441            }
14442        }
14443    }
14444
14445    @Override
14446    public String getInstallerPackageName(String packageName) {
14447        // reader
14448        synchronized (mPackages) {
14449            return mSettings.getInstallerPackageNameLPr(packageName);
14450        }
14451    }
14452
14453    @Override
14454    public int getApplicationEnabledSetting(String packageName, int userId) {
14455        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14456        int uid = Binder.getCallingUid();
14457        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14458        // reader
14459        synchronized (mPackages) {
14460            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14461        }
14462    }
14463
14464    @Override
14465    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14466        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14467        int uid = Binder.getCallingUid();
14468        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14469        // reader
14470        synchronized (mPackages) {
14471            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14472        }
14473    }
14474
14475    @Override
14476    public void enterSafeMode() {
14477        enforceSystemOrRoot("Only the system can request entering safe mode");
14478
14479        if (!mSystemReady) {
14480            mSafeMode = true;
14481        }
14482    }
14483
14484    @Override
14485    public void systemReady() {
14486        mSystemReady = true;
14487
14488        // Read the compatibilty setting when the system is ready.
14489        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14490                mContext.getContentResolver(),
14491                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14492        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14493        if (DEBUG_SETTINGS) {
14494            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14495        }
14496
14497        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14498
14499        synchronized (mPackages) {
14500            // Verify that all of the preferred activity components actually
14501            // exist.  It is possible for applications to be updated and at
14502            // that point remove a previously declared activity component that
14503            // had been set as a preferred activity.  We try to clean this up
14504            // the next time we encounter that preferred activity, but it is
14505            // possible for the user flow to never be able to return to that
14506            // situation so here we do a sanity check to make sure we haven't
14507            // left any junk around.
14508            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14509            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14510                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14511                removed.clear();
14512                for (PreferredActivity pa : pir.filterSet()) {
14513                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14514                        removed.add(pa);
14515                    }
14516                }
14517                if (removed.size() > 0) {
14518                    for (int r=0; r<removed.size(); r++) {
14519                        PreferredActivity pa = removed.get(r);
14520                        Slog.w(TAG, "Removing dangling preferred activity: "
14521                                + pa.mPref.mComponent);
14522                        pir.removeFilter(pa);
14523                    }
14524                    mSettings.writePackageRestrictionsLPr(
14525                            mSettings.mPreferredActivities.keyAt(i));
14526                }
14527            }
14528
14529            for (int userId : UserManagerService.getInstance().getUserIds()) {
14530                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14531                    grantPermissionsUserIds = ArrayUtils.appendInt(
14532                            grantPermissionsUserIds, userId);
14533                }
14534            }
14535        }
14536        sUserManager.systemReady();
14537
14538        // If we upgraded grant all default permissions before kicking off.
14539        for (int userId : grantPermissionsUserIds) {
14540            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14541        }
14542
14543        // Kick off any messages waiting for system ready
14544        if (mPostSystemReadyMessages != null) {
14545            for (Message msg : mPostSystemReadyMessages) {
14546                msg.sendToTarget();
14547            }
14548            mPostSystemReadyMessages = null;
14549        }
14550
14551        // Watch for external volumes that come and go over time
14552        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14553        storage.registerListener(mStorageListener);
14554
14555        mInstallerService.systemReady();
14556        mPackageDexOptimizer.systemReady();
14557
14558        MountServiceInternal mountServiceInternal = LocalServices.getService(
14559                MountServiceInternal.class);
14560        mountServiceInternal.addExternalStoragePolicy(
14561                new MountServiceInternal.ExternalStorageMountPolicy() {
14562            @Override
14563            public int getMountMode(int uid, String packageName) {
14564                if (Process.isIsolated(uid)) {
14565                    return Zygote.MOUNT_EXTERNAL_NONE;
14566                }
14567                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14568                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14569                }
14570                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14571                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14572                }
14573                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14574                    return Zygote.MOUNT_EXTERNAL_READ;
14575                }
14576                return Zygote.MOUNT_EXTERNAL_WRITE;
14577            }
14578
14579            @Override
14580            public boolean hasExternalStorage(int uid, String packageName) {
14581                return true;
14582            }
14583        });
14584    }
14585
14586    @Override
14587    public boolean isSafeMode() {
14588        return mSafeMode;
14589    }
14590
14591    @Override
14592    public boolean hasSystemUidErrors() {
14593        return mHasSystemUidErrors;
14594    }
14595
14596    static String arrayToString(int[] array) {
14597        StringBuffer buf = new StringBuffer(128);
14598        buf.append('[');
14599        if (array != null) {
14600            for (int i=0; i<array.length; i++) {
14601                if (i > 0) buf.append(", ");
14602                buf.append(array[i]);
14603            }
14604        }
14605        buf.append(']');
14606        return buf.toString();
14607    }
14608
14609    static class DumpState {
14610        public static final int DUMP_LIBS = 1 << 0;
14611        public static final int DUMP_FEATURES = 1 << 1;
14612        public static final int DUMP_RESOLVERS = 1 << 2;
14613        public static final int DUMP_PERMISSIONS = 1 << 3;
14614        public static final int DUMP_PACKAGES = 1 << 4;
14615        public static final int DUMP_SHARED_USERS = 1 << 5;
14616        public static final int DUMP_MESSAGES = 1 << 6;
14617        public static final int DUMP_PROVIDERS = 1 << 7;
14618        public static final int DUMP_VERIFIERS = 1 << 8;
14619        public static final int DUMP_PREFERRED = 1 << 9;
14620        public static final int DUMP_PREFERRED_XML = 1 << 10;
14621        public static final int DUMP_KEYSETS = 1 << 11;
14622        public static final int DUMP_VERSION = 1 << 12;
14623        public static final int DUMP_INSTALLS = 1 << 13;
14624        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14625        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14626
14627        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14628
14629        private int mTypes;
14630
14631        private int mOptions;
14632
14633        private boolean mTitlePrinted;
14634
14635        private SharedUserSetting mSharedUser;
14636
14637        public boolean isDumping(int type) {
14638            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14639                return true;
14640            }
14641
14642            return (mTypes & type) != 0;
14643        }
14644
14645        public void setDump(int type) {
14646            mTypes |= type;
14647        }
14648
14649        public boolean isOptionEnabled(int option) {
14650            return (mOptions & option) != 0;
14651        }
14652
14653        public void setOptionEnabled(int option) {
14654            mOptions |= option;
14655        }
14656
14657        public boolean onTitlePrinted() {
14658            final boolean printed = mTitlePrinted;
14659            mTitlePrinted = true;
14660            return printed;
14661        }
14662
14663        public boolean getTitlePrinted() {
14664            return mTitlePrinted;
14665        }
14666
14667        public void setTitlePrinted(boolean enabled) {
14668            mTitlePrinted = enabled;
14669        }
14670
14671        public SharedUserSetting getSharedUser() {
14672            return mSharedUser;
14673        }
14674
14675        public void setSharedUser(SharedUserSetting user) {
14676            mSharedUser = user;
14677        }
14678    }
14679
14680    @Override
14681    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14682        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14683                != PackageManager.PERMISSION_GRANTED) {
14684            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14685                    + Binder.getCallingPid()
14686                    + ", uid=" + Binder.getCallingUid()
14687                    + " without permission "
14688                    + android.Manifest.permission.DUMP);
14689            return;
14690        }
14691
14692        DumpState dumpState = new DumpState();
14693        boolean fullPreferred = false;
14694        boolean checkin = false;
14695
14696        String packageName = null;
14697        ArraySet<String> permissionNames = null;
14698
14699        int opti = 0;
14700        while (opti < args.length) {
14701            String opt = args[opti];
14702            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14703                break;
14704            }
14705            opti++;
14706
14707            if ("-a".equals(opt)) {
14708                // Right now we only know how to print all.
14709            } else if ("-h".equals(opt)) {
14710                pw.println("Package manager dump options:");
14711                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14712                pw.println("    --checkin: dump for a checkin");
14713                pw.println("    -f: print details of intent filters");
14714                pw.println("    -h: print this help");
14715                pw.println("  cmd may be one of:");
14716                pw.println("    l[ibraries]: list known shared libraries");
14717                pw.println("    f[ibraries]: list device features");
14718                pw.println("    k[eysets]: print known keysets");
14719                pw.println("    r[esolvers]: dump intent resolvers");
14720                pw.println("    perm[issions]: dump permissions");
14721                pw.println("    permission [name ...]: dump declaration and use of given permission");
14722                pw.println("    pref[erred]: print preferred package settings");
14723                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14724                pw.println("    prov[iders]: dump content providers");
14725                pw.println("    p[ackages]: dump installed packages");
14726                pw.println("    s[hared-users]: dump shared user IDs");
14727                pw.println("    m[essages]: print collected runtime messages");
14728                pw.println("    v[erifiers]: print package verifier info");
14729                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14730                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14731                pw.println("    version: print database version info");
14732                pw.println("    write: write current settings now");
14733                pw.println("    installs: details about install sessions");
14734                pw.println("    <package.name>: info about given package");
14735                return;
14736            } else if ("--checkin".equals(opt)) {
14737                checkin = true;
14738            } else if ("-f".equals(opt)) {
14739                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14740            } else {
14741                pw.println("Unknown argument: " + opt + "; use -h for help");
14742            }
14743        }
14744
14745        // Is the caller requesting to dump a particular piece of data?
14746        if (opti < args.length) {
14747            String cmd = args[opti];
14748            opti++;
14749            // Is this a package name?
14750            if ("android".equals(cmd) || cmd.contains(".")) {
14751                packageName = cmd;
14752                // When dumping a single package, we always dump all of its
14753                // filter information since the amount of data will be reasonable.
14754                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14755            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14756                dumpState.setDump(DumpState.DUMP_LIBS);
14757            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14758                dumpState.setDump(DumpState.DUMP_FEATURES);
14759            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14760                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14761            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14762                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14763            } else if ("permission".equals(cmd)) {
14764                if (opti >= args.length) {
14765                    pw.println("Error: permission requires permission name");
14766                    return;
14767                }
14768                permissionNames = new ArraySet<>();
14769                while (opti < args.length) {
14770                    permissionNames.add(args[opti]);
14771                    opti++;
14772                }
14773                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14774                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14775            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14776                dumpState.setDump(DumpState.DUMP_PREFERRED);
14777            } else if ("preferred-xml".equals(cmd)) {
14778                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14779                if (opti < args.length && "--full".equals(args[opti])) {
14780                    fullPreferred = true;
14781                    opti++;
14782                }
14783            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14784                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14785            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14786                dumpState.setDump(DumpState.DUMP_PACKAGES);
14787            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14788                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14789            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14790                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14791            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14792                dumpState.setDump(DumpState.DUMP_MESSAGES);
14793            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14794                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14795            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14796                    || "intent-filter-verifiers".equals(cmd)) {
14797                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14798            } else if ("version".equals(cmd)) {
14799                dumpState.setDump(DumpState.DUMP_VERSION);
14800            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14801                dumpState.setDump(DumpState.DUMP_KEYSETS);
14802            } else if ("installs".equals(cmd)) {
14803                dumpState.setDump(DumpState.DUMP_INSTALLS);
14804            } else if ("write".equals(cmd)) {
14805                synchronized (mPackages) {
14806                    mSettings.writeLPr();
14807                    pw.println("Settings written.");
14808                    return;
14809                }
14810            }
14811        }
14812
14813        if (checkin) {
14814            pw.println("vers,1");
14815        }
14816
14817        // reader
14818        synchronized (mPackages) {
14819            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14820                if (!checkin) {
14821                    if (dumpState.onTitlePrinted())
14822                        pw.println();
14823                    pw.println("Database versions:");
14824                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14825                }
14826            }
14827
14828            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14829                if (!checkin) {
14830                    if (dumpState.onTitlePrinted())
14831                        pw.println();
14832                    pw.println("Verifiers:");
14833                    pw.print("  Required: ");
14834                    pw.print(mRequiredVerifierPackage);
14835                    pw.print(" (uid=");
14836                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14837                    pw.println(")");
14838                } else if (mRequiredVerifierPackage != null) {
14839                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14840                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14841                }
14842            }
14843
14844            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14845                    packageName == null) {
14846                if (mIntentFilterVerifierComponent != null) {
14847                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14848                    if (!checkin) {
14849                        if (dumpState.onTitlePrinted())
14850                            pw.println();
14851                        pw.println("Intent Filter Verifier:");
14852                        pw.print("  Using: ");
14853                        pw.print(verifierPackageName);
14854                        pw.print(" (uid=");
14855                        pw.print(getPackageUid(verifierPackageName, 0));
14856                        pw.println(")");
14857                    } else if (verifierPackageName != null) {
14858                        pw.print("ifv,"); pw.print(verifierPackageName);
14859                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14860                    }
14861                } else {
14862                    pw.println();
14863                    pw.println("No Intent Filter Verifier available!");
14864                }
14865            }
14866
14867            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14868                boolean printedHeader = false;
14869                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14870                while (it.hasNext()) {
14871                    String name = it.next();
14872                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14873                    if (!checkin) {
14874                        if (!printedHeader) {
14875                            if (dumpState.onTitlePrinted())
14876                                pw.println();
14877                            pw.println("Libraries:");
14878                            printedHeader = true;
14879                        }
14880                        pw.print("  ");
14881                    } else {
14882                        pw.print("lib,");
14883                    }
14884                    pw.print(name);
14885                    if (!checkin) {
14886                        pw.print(" -> ");
14887                    }
14888                    if (ent.path != null) {
14889                        if (!checkin) {
14890                            pw.print("(jar) ");
14891                            pw.print(ent.path);
14892                        } else {
14893                            pw.print(",jar,");
14894                            pw.print(ent.path);
14895                        }
14896                    } else {
14897                        if (!checkin) {
14898                            pw.print("(apk) ");
14899                            pw.print(ent.apk);
14900                        } else {
14901                            pw.print(",apk,");
14902                            pw.print(ent.apk);
14903                        }
14904                    }
14905                    pw.println();
14906                }
14907            }
14908
14909            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14910                if (dumpState.onTitlePrinted())
14911                    pw.println();
14912                if (!checkin) {
14913                    pw.println("Features:");
14914                }
14915                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14916                while (it.hasNext()) {
14917                    String name = it.next();
14918                    if (!checkin) {
14919                        pw.print("  ");
14920                    } else {
14921                        pw.print("feat,");
14922                    }
14923                    pw.println(name);
14924                }
14925            }
14926
14927            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14928                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14929                        : "Activity Resolver Table:", "  ", packageName,
14930                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14931                    dumpState.setTitlePrinted(true);
14932                }
14933                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14934                        : "Receiver Resolver Table:", "  ", packageName,
14935                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14936                    dumpState.setTitlePrinted(true);
14937                }
14938                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14939                        : "Service Resolver Table:", "  ", packageName,
14940                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14941                    dumpState.setTitlePrinted(true);
14942                }
14943                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14944                        : "Provider Resolver Table:", "  ", packageName,
14945                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14946                    dumpState.setTitlePrinted(true);
14947                }
14948            }
14949
14950            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14951                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14952                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14953                    int user = mSettings.mPreferredActivities.keyAt(i);
14954                    if (pir.dump(pw,
14955                            dumpState.getTitlePrinted()
14956                                ? "\nPreferred Activities User " + user + ":"
14957                                : "Preferred Activities User " + user + ":", "  ",
14958                            packageName, true, false)) {
14959                        dumpState.setTitlePrinted(true);
14960                    }
14961                }
14962            }
14963
14964            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14965                pw.flush();
14966                FileOutputStream fout = new FileOutputStream(fd);
14967                BufferedOutputStream str = new BufferedOutputStream(fout);
14968                XmlSerializer serializer = new FastXmlSerializer();
14969                try {
14970                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14971                    serializer.startDocument(null, true);
14972                    serializer.setFeature(
14973                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14974                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14975                    serializer.endDocument();
14976                    serializer.flush();
14977                } catch (IllegalArgumentException e) {
14978                    pw.println("Failed writing: " + e);
14979                } catch (IllegalStateException e) {
14980                    pw.println("Failed writing: " + e);
14981                } catch (IOException e) {
14982                    pw.println("Failed writing: " + e);
14983                }
14984            }
14985
14986            if (!checkin
14987                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14988                    && packageName == null) {
14989                pw.println();
14990                int count = mSettings.mPackages.size();
14991                if (count == 0) {
14992                    pw.println("No applications!");
14993                    pw.println();
14994                } else {
14995                    final String prefix = "  ";
14996                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14997                    if (allPackageSettings.size() == 0) {
14998                        pw.println("No domain preferred apps!");
14999                        pw.println();
15000                    } else {
15001                        pw.println("App verification status:");
15002                        pw.println();
15003                        count = 0;
15004                        for (PackageSetting ps : allPackageSettings) {
15005                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15006                            if (ivi == null || ivi.getPackageName() == null) continue;
15007                            pw.println(prefix + "Package: " + ivi.getPackageName());
15008                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15009                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15010                            pw.println();
15011                            count++;
15012                        }
15013                        if (count == 0) {
15014                            pw.println(prefix + "No app verification established.");
15015                            pw.println();
15016                        }
15017                        for (int userId : sUserManager.getUserIds()) {
15018                            pw.println("App linkages for user " + userId + ":");
15019                            pw.println();
15020                            count = 0;
15021                            for (PackageSetting ps : allPackageSettings) {
15022                                final long status = ps.getDomainVerificationStatusForUser(userId);
15023                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15024                                    continue;
15025                                }
15026                                pw.println(prefix + "Package: " + ps.name);
15027                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15028                                String statusStr = IntentFilterVerificationInfo.
15029                                        getStatusStringFromValue(status);
15030                                pw.println(prefix + "Status:  " + statusStr);
15031                                pw.println();
15032                                count++;
15033                            }
15034                            if (count == 0) {
15035                                pw.println(prefix + "No configured app linkages.");
15036                                pw.println();
15037                            }
15038                        }
15039                    }
15040                }
15041            }
15042
15043            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15044                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15045                if (packageName == null && permissionNames == null) {
15046                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15047                        if (iperm == 0) {
15048                            if (dumpState.onTitlePrinted())
15049                                pw.println();
15050                            pw.println("AppOp Permissions:");
15051                        }
15052                        pw.print("  AppOp Permission ");
15053                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15054                        pw.println(":");
15055                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15056                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15057                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15058                        }
15059                    }
15060                }
15061            }
15062
15063            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15064                boolean printedSomething = false;
15065                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15066                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15067                        continue;
15068                    }
15069                    if (!printedSomething) {
15070                        if (dumpState.onTitlePrinted())
15071                            pw.println();
15072                        pw.println("Registered ContentProviders:");
15073                        printedSomething = true;
15074                    }
15075                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15076                    pw.print("    "); pw.println(p.toString());
15077                }
15078                printedSomething = false;
15079                for (Map.Entry<String, PackageParser.Provider> entry :
15080                        mProvidersByAuthority.entrySet()) {
15081                    PackageParser.Provider p = entry.getValue();
15082                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15083                        continue;
15084                    }
15085                    if (!printedSomething) {
15086                        if (dumpState.onTitlePrinted())
15087                            pw.println();
15088                        pw.println("ContentProvider Authorities:");
15089                        printedSomething = true;
15090                    }
15091                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15092                    pw.print("    "); pw.println(p.toString());
15093                    if (p.info != null && p.info.applicationInfo != null) {
15094                        final String appInfo = p.info.applicationInfo.toString();
15095                        pw.print("      applicationInfo="); pw.println(appInfo);
15096                    }
15097                }
15098            }
15099
15100            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15101                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15102            }
15103
15104            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15105                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15106            }
15107
15108            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15109                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15110            }
15111
15112            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15113                // XXX should handle packageName != null by dumping only install data that
15114                // the given package is involved with.
15115                if (dumpState.onTitlePrinted()) pw.println();
15116                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15117            }
15118
15119            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15120                if (dumpState.onTitlePrinted()) pw.println();
15121                mSettings.dumpReadMessagesLPr(pw, dumpState);
15122
15123                pw.println();
15124                pw.println("Package warning messages:");
15125                BufferedReader in = null;
15126                String line = null;
15127                try {
15128                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15129                    while ((line = in.readLine()) != null) {
15130                        if (line.contains("ignored: updated version")) continue;
15131                        pw.println(line);
15132                    }
15133                } catch (IOException ignored) {
15134                } finally {
15135                    IoUtils.closeQuietly(in);
15136                }
15137            }
15138
15139            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15140                BufferedReader in = null;
15141                String line = null;
15142                try {
15143                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15144                    while ((line = in.readLine()) != null) {
15145                        if (line.contains("ignored: updated version")) continue;
15146                        pw.print("msg,");
15147                        pw.println(line);
15148                    }
15149                } catch (IOException ignored) {
15150                } finally {
15151                    IoUtils.closeQuietly(in);
15152                }
15153            }
15154        }
15155    }
15156
15157    private String dumpDomainString(String packageName) {
15158        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15159        List<IntentFilter> filters = getAllIntentFilters(packageName);
15160
15161        ArraySet<String> result = new ArraySet<>();
15162        if (iviList.size() > 0) {
15163            for (IntentFilterVerificationInfo ivi : iviList) {
15164                for (String host : ivi.getDomains()) {
15165                    result.add(host);
15166                }
15167            }
15168        }
15169        if (filters != null && filters.size() > 0) {
15170            for (IntentFilter filter : filters) {
15171                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15172                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15173                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15174                    result.addAll(filter.getHostsList());
15175                }
15176            }
15177        }
15178
15179        StringBuilder sb = new StringBuilder(result.size() * 16);
15180        for (String domain : result) {
15181            if (sb.length() > 0) sb.append(" ");
15182            sb.append(domain);
15183        }
15184        return sb.toString();
15185    }
15186
15187    // ------- apps on sdcard specific code -------
15188    static final boolean DEBUG_SD_INSTALL = false;
15189
15190    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15191
15192    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15193
15194    private boolean mMediaMounted = false;
15195
15196    static String getEncryptKey() {
15197        try {
15198            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15199                    SD_ENCRYPTION_KEYSTORE_NAME);
15200            if (sdEncKey == null) {
15201                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15202                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15203                if (sdEncKey == null) {
15204                    Slog.e(TAG, "Failed to create encryption keys");
15205                    return null;
15206                }
15207            }
15208            return sdEncKey;
15209        } catch (NoSuchAlgorithmException nsae) {
15210            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15211            return null;
15212        } catch (IOException ioe) {
15213            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15214            return null;
15215        }
15216    }
15217
15218    /*
15219     * Update media status on PackageManager.
15220     */
15221    @Override
15222    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15223        int callingUid = Binder.getCallingUid();
15224        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15225            throw new SecurityException("Media status can only be updated by the system");
15226        }
15227        // reader; this apparently protects mMediaMounted, but should probably
15228        // be a different lock in that case.
15229        synchronized (mPackages) {
15230            Log.i(TAG, "Updating external media status from "
15231                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15232                    + (mediaStatus ? "mounted" : "unmounted"));
15233            if (DEBUG_SD_INSTALL)
15234                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15235                        + ", mMediaMounted=" + mMediaMounted);
15236            if (mediaStatus == mMediaMounted) {
15237                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15238                        : 0, -1);
15239                mHandler.sendMessage(msg);
15240                return;
15241            }
15242            mMediaMounted = mediaStatus;
15243        }
15244        // Queue up an async operation since the package installation may take a
15245        // little while.
15246        mHandler.post(new Runnable() {
15247            public void run() {
15248                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15249            }
15250        });
15251    }
15252
15253    /**
15254     * Called by MountService when the initial ASECs to scan are available.
15255     * Should block until all the ASEC containers are finished being scanned.
15256     */
15257    public void scanAvailableAsecs() {
15258        updateExternalMediaStatusInner(true, false, false);
15259        if (mShouldRestoreconData) {
15260            SELinuxMMAC.setRestoreconDone();
15261            mShouldRestoreconData = false;
15262        }
15263    }
15264
15265    /*
15266     * Collect information of applications on external media, map them against
15267     * existing containers and update information based on current mount status.
15268     * Please note that we always have to report status if reportStatus has been
15269     * set to true especially when unloading packages.
15270     */
15271    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15272            boolean externalStorage) {
15273        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15274        int[] uidArr = EmptyArray.INT;
15275
15276        final String[] list = PackageHelper.getSecureContainerList();
15277        if (ArrayUtils.isEmpty(list)) {
15278            Log.i(TAG, "No secure containers found");
15279        } else {
15280            // Process list of secure containers and categorize them
15281            // as active or stale based on their package internal state.
15282
15283            // reader
15284            synchronized (mPackages) {
15285                for (String cid : list) {
15286                    // Leave stages untouched for now; installer service owns them
15287                    if (PackageInstallerService.isStageName(cid)) continue;
15288
15289                    if (DEBUG_SD_INSTALL)
15290                        Log.i(TAG, "Processing container " + cid);
15291                    String pkgName = getAsecPackageName(cid);
15292                    if (pkgName == null) {
15293                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15294                        continue;
15295                    }
15296                    if (DEBUG_SD_INSTALL)
15297                        Log.i(TAG, "Looking for pkg : " + pkgName);
15298
15299                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15300                    if (ps == null) {
15301                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15302                        continue;
15303                    }
15304
15305                    /*
15306                     * Skip packages that are not external if we're unmounting
15307                     * external storage.
15308                     */
15309                    if (externalStorage && !isMounted && !isExternal(ps)) {
15310                        continue;
15311                    }
15312
15313                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15314                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15315                    // The package status is changed only if the code path
15316                    // matches between settings and the container id.
15317                    if (ps.codePathString != null
15318                            && ps.codePathString.startsWith(args.getCodePath())) {
15319                        if (DEBUG_SD_INSTALL) {
15320                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15321                                    + " at code path: " + ps.codePathString);
15322                        }
15323
15324                        // We do have a valid package installed on sdcard
15325                        processCids.put(args, ps.codePathString);
15326                        final int uid = ps.appId;
15327                        if (uid != -1) {
15328                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15329                        }
15330                    } else {
15331                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15332                                + ps.codePathString);
15333                    }
15334                }
15335            }
15336
15337            Arrays.sort(uidArr);
15338        }
15339
15340        // Process packages with valid entries.
15341        if (isMounted) {
15342            if (DEBUG_SD_INSTALL)
15343                Log.i(TAG, "Loading packages");
15344            loadMediaPackages(processCids, uidArr);
15345            startCleaningPackages();
15346            mInstallerService.onSecureContainersAvailable();
15347        } else {
15348            if (DEBUG_SD_INSTALL)
15349                Log.i(TAG, "Unloading packages");
15350            unloadMediaPackages(processCids, uidArr, reportStatus);
15351        }
15352    }
15353
15354    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15355            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15356        final int size = infos.size();
15357        final String[] packageNames = new String[size];
15358        final int[] packageUids = new int[size];
15359        for (int i = 0; i < size; i++) {
15360            final ApplicationInfo info = infos.get(i);
15361            packageNames[i] = info.packageName;
15362            packageUids[i] = info.uid;
15363        }
15364        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15365                finishedReceiver);
15366    }
15367
15368    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15369            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15370        sendResourcesChangedBroadcast(mediaStatus, replacing,
15371                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15372    }
15373
15374    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15375            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15376        int size = pkgList.length;
15377        if (size > 0) {
15378            // Send broadcasts here
15379            Bundle extras = new Bundle();
15380            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15381            if (uidArr != null) {
15382                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15383            }
15384            if (replacing) {
15385                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15386            }
15387            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15388                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15389            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15390        }
15391    }
15392
15393   /*
15394     * Look at potentially valid container ids from processCids If package
15395     * information doesn't match the one on record or package scanning fails,
15396     * the cid is added to list of removeCids. We currently don't delete stale
15397     * containers.
15398     */
15399    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15400        ArrayList<String> pkgList = new ArrayList<String>();
15401        Set<AsecInstallArgs> keys = processCids.keySet();
15402
15403        for (AsecInstallArgs args : keys) {
15404            String codePath = processCids.get(args);
15405            if (DEBUG_SD_INSTALL)
15406                Log.i(TAG, "Loading container : " + args.cid);
15407            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15408            try {
15409                // Make sure there are no container errors first.
15410                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15411                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15412                            + " when installing from sdcard");
15413                    continue;
15414                }
15415                // Check code path here.
15416                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15417                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15418                            + " does not match one in settings " + codePath);
15419                    continue;
15420                }
15421                // Parse package
15422                int parseFlags = mDefParseFlags;
15423                if (args.isExternalAsec()) {
15424                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15425                }
15426                if (args.isFwdLocked()) {
15427                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15428                }
15429
15430                synchronized (mInstallLock) {
15431                    PackageParser.Package pkg = null;
15432                    try {
15433                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15434                    } catch (PackageManagerException e) {
15435                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15436                    }
15437                    // Scan the package
15438                    if (pkg != null) {
15439                        /*
15440                         * TODO why is the lock being held? doPostInstall is
15441                         * called in other places without the lock. This needs
15442                         * to be straightened out.
15443                         */
15444                        // writer
15445                        synchronized (mPackages) {
15446                            retCode = PackageManager.INSTALL_SUCCEEDED;
15447                            pkgList.add(pkg.packageName);
15448                            // Post process args
15449                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15450                                    pkg.applicationInfo.uid);
15451                        }
15452                    } else {
15453                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15454                    }
15455                }
15456
15457            } finally {
15458                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15459                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15460                }
15461            }
15462        }
15463        // writer
15464        synchronized (mPackages) {
15465            // If the platform SDK has changed since the last time we booted,
15466            // we need to re-grant app permission to catch any new ones that
15467            // appear. This is really a hack, and means that apps can in some
15468            // cases get permissions that the user didn't initially explicitly
15469            // allow... it would be nice to have some better way to handle
15470            // this situation.
15471            final VersionInfo ver = mSettings.getExternalVersion();
15472
15473            int updateFlags = UPDATE_PERMISSIONS_ALL;
15474            if (ver.sdkVersion != mSdkVersion) {
15475                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15476                        + mSdkVersion + "; regranting permissions for external");
15477                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15478            }
15479            updatePermissionsLPw(null, null, updateFlags);
15480
15481            // Yay, everything is now upgraded
15482            ver.forceCurrent();
15483
15484            // can downgrade to reader
15485            // Persist settings
15486            mSettings.writeLPr();
15487        }
15488        // Send a broadcast to let everyone know we are done processing
15489        if (pkgList.size() > 0) {
15490            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15491        }
15492    }
15493
15494   /*
15495     * Utility method to unload a list of specified containers
15496     */
15497    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15498        // Just unmount all valid containers.
15499        for (AsecInstallArgs arg : cidArgs) {
15500            synchronized (mInstallLock) {
15501                arg.doPostDeleteLI(false);
15502           }
15503       }
15504   }
15505
15506    /*
15507     * Unload packages mounted on external media. This involves deleting package
15508     * data from internal structures, sending broadcasts about diabled packages,
15509     * gc'ing to free up references, unmounting all secure containers
15510     * corresponding to packages on external media, and posting a
15511     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15512     * that we always have to post this message if status has been requested no
15513     * matter what.
15514     */
15515    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15516            final boolean reportStatus) {
15517        if (DEBUG_SD_INSTALL)
15518            Log.i(TAG, "unloading media packages");
15519        ArrayList<String> pkgList = new ArrayList<String>();
15520        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15521        final Set<AsecInstallArgs> keys = processCids.keySet();
15522        for (AsecInstallArgs args : keys) {
15523            String pkgName = args.getPackageName();
15524            if (DEBUG_SD_INSTALL)
15525                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15526            // Delete package internally
15527            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15528            synchronized (mInstallLock) {
15529                boolean res = deletePackageLI(pkgName, null, false, null, null,
15530                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15531                if (res) {
15532                    pkgList.add(pkgName);
15533                } else {
15534                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15535                    failedList.add(args);
15536                }
15537            }
15538        }
15539
15540        // reader
15541        synchronized (mPackages) {
15542            // We didn't update the settings after removing each package;
15543            // write them now for all packages.
15544            mSettings.writeLPr();
15545        }
15546
15547        // We have to absolutely send UPDATED_MEDIA_STATUS only
15548        // after confirming that all the receivers processed the ordered
15549        // broadcast when packages get disabled, force a gc to clean things up.
15550        // and unload all the containers.
15551        if (pkgList.size() > 0) {
15552            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15553                    new IIntentReceiver.Stub() {
15554                public void performReceive(Intent intent, int resultCode, String data,
15555                        Bundle extras, boolean ordered, boolean sticky,
15556                        int sendingUser) throws RemoteException {
15557                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15558                            reportStatus ? 1 : 0, 1, keys);
15559                    mHandler.sendMessage(msg);
15560                }
15561            });
15562        } else {
15563            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15564                    keys);
15565            mHandler.sendMessage(msg);
15566        }
15567    }
15568
15569    private void loadPrivatePackages(VolumeInfo vol) {
15570        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15571        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15572        synchronized (mInstallLock) {
15573        synchronized (mPackages) {
15574            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15575            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15576            for (PackageSetting ps : packages) {
15577                final PackageParser.Package pkg;
15578                try {
15579                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15580                    loaded.add(pkg.applicationInfo);
15581                } catch (PackageManagerException e) {
15582                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15583                }
15584
15585                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15586                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15587                }
15588            }
15589
15590            int updateFlags = UPDATE_PERMISSIONS_ALL;
15591            if (ver.sdkVersion != mSdkVersion) {
15592                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15593                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15594                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15595            }
15596            updatePermissionsLPw(null, null, updateFlags);
15597
15598            // Yay, everything is now upgraded
15599            ver.forceCurrent();
15600
15601            mSettings.writeLPr();
15602        }
15603        }
15604
15605        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15606        sendResourcesChangedBroadcast(true, false, loaded, null);
15607    }
15608
15609    private void unloadPrivatePackages(VolumeInfo vol) {
15610        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15611        synchronized (mInstallLock) {
15612        synchronized (mPackages) {
15613            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15614            for (PackageSetting ps : packages) {
15615                if (ps.pkg == null) continue;
15616
15617                final ApplicationInfo info = ps.pkg.applicationInfo;
15618                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15619                if (deletePackageLI(ps.name, null, false, null, null,
15620                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15621                    unloaded.add(info);
15622                } else {
15623                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15624                }
15625            }
15626
15627            mSettings.writeLPr();
15628        }
15629        }
15630
15631        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15632        sendResourcesChangedBroadcast(false, false, unloaded, null);
15633    }
15634
15635    /**
15636     * Examine all users present on given mounted volume, and destroy data
15637     * belonging to users that are no longer valid, or whose user ID has been
15638     * recycled.
15639     */
15640    private void reconcileUsers(String volumeUuid) {
15641        final File[] files = FileUtils
15642                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15643        for (File file : files) {
15644            if (!file.isDirectory()) continue;
15645
15646            final int userId;
15647            final UserInfo info;
15648            try {
15649                userId = Integer.parseInt(file.getName());
15650                info = sUserManager.getUserInfo(userId);
15651            } catch (NumberFormatException e) {
15652                Slog.w(TAG, "Invalid user directory " + file);
15653                continue;
15654            }
15655
15656            boolean destroyUser = false;
15657            if (info == null) {
15658                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15659                        + " because no matching user was found");
15660                destroyUser = true;
15661            } else {
15662                try {
15663                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15664                } catch (IOException e) {
15665                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15666                            + " because we failed to enforce serial number: " + e);
15667                    destroyUser = true;
15668                }
15669            }
15670
15671            if (destroyUser) {
15672                synchronized (mInstallLock) {
15673                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15674                }
15675            }
15676        }
15677
15678        final UserManager um = mContext.getSystemService(UserManager.class);
15679        for (UserInfo user : um.getUsers()) {
15680            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15681            if (userDir.exists()) continue;
15682
15683            try {
15684                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15685                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15686            } catch (IOException e) {
15687                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15688            }
15689        }
15690    }
15691
15692    /**
15693     * Examine all apps present on given mounted volume, and destroy apps that
15694     * aren't expected, either due to uninstallation or reinstallation on
15695     * another volume.
15696     */
15697    private void reconcileApps(String volumeUuid) {
15698        final File[] files = FileUtils
15699                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15700        for (File file : files) {
15701            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15702                    && !PackageInstallerService.isStageName(file.getName());
15703            if (!isPackage) {
15704                // Ignore entries which are not packages
15705                continue;
15706            }
15707
15708            boolean destroyApp = false;
15709            String packageName = null;
15710            try {
15711                final PackageLite pkg = PackageParser.parsePackageLite(file,
15712                        PackageParser.PARSE_MUST_BE_APK);
15713                packageName = pkg.packageName;
15714
15715                synchronized (mPackages) {
15716                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15717                    if (ps == null) {
15718                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15719                                + volumeUuid + " because we found no install record");
15720                        destroyApp = true;
15721                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15722                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15723                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15724                        destroyApp = true;
15725                    }
15726                }
15727
15728            } catch (PackageParserException e) {
15729                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15730                destroyApp = true;
15731            }
15732
15733            if (destroyApp) {
15734                synchronized (mInstallLock) {
15735                    if (packageName != null) {
15736                        removeDataDirsLI(volumeUuid, packageName);
15737                    }
15738                    if (file.isDirectory()) {
15739                        mInstaller.rmPackageDir(file.getAbsolutePath());
15740                    } else {
15741                        file.delete();
15742                    }
15743                }
15744            }
15745        }
15746    }
15747
15748    private void unfreezePackage(String packageName) {
15749        synchronized (mPackages) {
15750            final PackageSetting ps = mSettings.mPackages.get(packageName);
15751            if (ps != null) {
15752                ps.frozen = false;
15753            }
15754        }
15755    }
15756
15757    @Override
15758    public int movePackage(final String packageName, final String volumeUuid) {
15759        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15760
15761        final int moveId = mNextMoveId.getAndIncrement();
15762        try {
15763            movePackageInternal(packageName, volumeUuid, moveId);
15764        } catch (PackageManagerException e) {
15765            Slog.w(TAG, "Failed to move " + packageName, e);
15766            mMoveCallbacks.notifyStatusChanged(moveId,
15767                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15768        }
15769        return moveId;
15770    }
15771
15772    private void movePackageInternal(final String packageName, final String volumeUuid,
15773            final int moveId) throws PackageManagerException {
15774        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15775        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15776        final PackageManager pm = mContext.getPackageManager();
15777
15778        final boolean currentAsec;
15779        final String currentVolumeUuid;
15780        final File codeFile;
15781        final String installerPackageName;
15782        final String packageAbiOverride;
15783        final int appId;
15784        final String seinfo;
15785        final String label;
15786
15787        // reader
15788        synchronized (mPackages) {
15789            final PackageParser.Package pkg = mPackages.get(packageName);
15790            final PackageSetting ps = mSettings.mPackages.get(packageName);
15791            if (pkg == null || ps == null) {
15792                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15793            }
15794
15795            if (pkg.applicationInfo.isSystemApp()) {
15796                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15797                        "Cannot move system application");
15798            }
15799
15800            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15801                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15802                        "Package already moved to " + volumeUuid);
15803            }
15804
15805            final File probe = new File(pkg.codePath);
15806            final File probeOat = new File(probe, "oat");
15807            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15808                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15809                        "Move only supported for modern cluster style installs");
15810            }
15811
15812            if (ps.frozen) {
15813                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15814                        "Failed to move already frozen package");
15815            }
15816            ps.frozen = true;
15817
15818            currentAsec = pkg.applicationInfo.isForwardLocked()
15819                    || pkg.applicationInfo.isExternalAsec();
15820            currentVolumeUuid = ps.volumeUuid;
15821            codeFile = new File(pkg.codePath);
15822            installerPackageName = ps.installerPackageName;
15823            packageAbiOverride = ps.cpuAbiOverrideString;
15824            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15825            seinfo = pkg.applicationInfo.seinfo;
15826            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15827        }
15828
15829        // Now that we're guarded by frozen state, kill app during move
15830        final long token = Binder.clearCallingIdentity();
15831        try {
15832            killApplication(packageName, appId, "move pkg");
15833        } finally {
15834            Binder.restoreCallingIdentity(token);
15835        }
15836
15837        final Bundle extras = new Bundle();
15838        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15839        extras.putString(Intent.EXTRA_TITLE, label);
15840        mMoveCallbacks.notifyCreated(moveId, extras);
15841
15842        int installFlags;
15843        final boolean moveCompleteApp;
15844        final File measurePath;
15845
15846        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15847            installFlags = INSTALL_INTERNAL;
15848            moveCompleteApp = !currentAsec;
15849            measurePath = Environment.getDataAppDirectory(volumeUuid);
15850        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15851            installFlags = INSTALL_EXTERNAL;
15852            moveCompleteApp = false;
15853            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15854        } else {
15855            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15856            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15857                    || !volume.isMountedWritable()) {
15858                unfreezePackage(packageName);
15859                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15860                        "Move location not mounted private volume");
15861            }
15862
15863            Preconditions.checkState(!currentAsec);
15864
15865            installFlags = INSTALL_INTERNAL;
15866            moveCompleteApp = true;
15867            measurePath = Environment.getDataAppDirectory(volumeUuid);
15868        }
15869
15870        final PackageStats stats = new PackageStats(null, -1);
15871        synchronized (mInstaller) {
15872            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15873                unfreezePackage(packageName);
15874                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15875                        "Failed to measure package size");
15876            }
15877        }
15878
15879        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15880                + stats.dataSize);
15881
15882        final long startFreeBytes = measurePath.getFreeSpace();
15883        final long sizeBytes;
15884        if (moveCompleteApp) {
15885            sizeBytes = stats.codeSize + stats.dataSize;
15886        } else {
15887            sizeBytes = stats.codeSize;
15888        }
15889
15890        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15891            unfreezePackage(packageName);
15892            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15893                    "Not enough free space to move");
15894        }
15895
15896        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15897
15898        final CountDownLatch installedLatch = new CountDownLatch(1);
15899        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15900            @Override
15901            public void onUserActionRequired(Intent intent) throws RemoteException {
15902                throw new IllegalStateException();
15903            }
15904
15905            @Override
15906            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15907                    Bundle extras) throws RemoteException {
15908                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15909                        + PackageManager.installStatusToString(returnCode, msg));
15910
15911                installedLatch.countDown();
15912
15913                // Regardless of success or failure of the move operation,
15914                // always unfreeze the package
15915                unfreezePackage(packageName);
15916
15917                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15918                switch (status) {
15919                    case PackageInstaller.STATUS_SUCCESS:
15920                        mMoveCallbacks.notifyStatusChanged(moveId,
15921                                PackageManager.MOVE_SUCCEEDED);
15922                        break;
15923                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15924                        mMoveCallbacks.notifyStatusChanged(moveId,
15925                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15926                        break;
15927                    default:
15928                        mMoveCallbacks.notifyStatusChanged(moveId,
15929                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15930                        break;
15931                }
15932            }
15933        };
15934
15935        final MoveInfo move;
15936        if (moveCompleteApp) {
15937            // Kick off a thread to report progress estimates
15938            new Thread() {
15939                @Override
15940                public void run() {
15941                    while (true) {
15942                        try {
15943                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15944                                break;
15945                            }
15946                        } catch (InterruptedException ignored) {
15947                        }
15948
15949                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15950                        final int progress = 10 + (int) MathUtils.constrain(
15951                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15952                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15953                    }
15954                }
15955            }.start();
15956
15957            final String dataAppName = codeFile.getName();
15958            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15959                    dataAppName, appId, seinfo);
15960        } else {
15961            move = null;
15962        }
15963
15964        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15965
15966        final Message msg = mHandler.obtainMessage(INIT_COPY);
15967        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15968        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15969                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15970        mHandler.sendMessage(msg);
15971    }
15972
15973    @Override
15974    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15975        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15976
15977        final int realMoveId = mNextMoveId.getAndIncrement();
15978        final Bundle extras = new Bundle();
15979        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15980        mMoveCallbacks.notifyCreated(realMoveId, extras);
15981
15982        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15983            @Override
15984            public void onCreated(int moveId, Bundle extras) {
15985                // Ignored
15986            }
15987
15988            @Override
15989            public void onStatusChanged(int moveId, int status, long estMillis) {
15990                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15991            }
15992        };
15993
15994        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15995        storage.setPrimaryStorageUuid(volumeUuid, callback);
15996        return realMoveId;
15997    }
15998
15999    @Override
16000    public int getMoveStatus(int moveId) {
16001        mContext.enforceCallingOrSelfPermission(
16002                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16003        return mMoveCallbacks.mLastStatus.get(moveId);
16004    }
16005
16006    @Override
16007    public void registerMoveCallback(IPackageMoveObserver callback) {
16008        mContext.enforceCallingOrSelfPermission(
16009                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16010        mMoveCallbacks.register(callback);
16011    }
16012
16013    @Override
16014    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16015        mContext.enforceCallingOrSelfPermission(
16016                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16017        mMoveCallbacks.unregister(callback);
16018    }
16019
16020    @Override
16021    public boolean setInstallLocation(int loc) {
16022        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16023                null);
16024        if (getInstallLocation() == loc) {
16025            return true;
16026        }
16027        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16028                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16029            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16030                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16031            return true;
16032        }
16033        return false;
16034   }
16035
16036    @Override
16037    public int getInstallLocation() {
16038        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16039                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16040                PackageHelper.APP_INSTALL_AUTO);
16041    }
16042
16043    /** Called by UserManagerService */
16044    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16045        mDirtyUsers.remove(userHandle);
16046        mSettings.removeUserLPw(userHandle);
16047        mPendingBroadcasts.remove(userHandle);
16048        if (mInstaller != null) {
16049            // Technically, we shouldn't be doing this with the package lock
16050            // held.  However, this is very rare, and there is already so much
16051            // other disk I/O going on, that we'll let it slide for now.
16052            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16053            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16054                final String volumeUuid = vol.getFsUuid();
16055                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16056                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16057            }
16058        }
16059        mUserNeedsBadging.delete(userHandle);
16060        removeUnusedPackagesLILPw(userManager, userHandle);
16061    }
16062
16063    /**
16064     * We're removing userHandle and would like to remove any downloaded packages
16065     * that are no longer in use by any other user.
16066     * @param userHandle the user being removed
16067     */
16068    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16069        final boolean DEBUG_CLEAN_APKS = false;
16070        int [] users = userManager.getUserIdsLPr();
16071        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16072        while (psit.hasNext()) {
16073            PackageSetting ps = psit.next();
16074            if (ps.pkg == null) {
16075                continue;
16076            }
16077            final String packageName = ps.pkg.packageName;
16078            // Skip over if system app
16079            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16080                continue;
16081            }
16082            if (DEBUG_CLEAN_APKS) {
16083                Slog.i(TAG, "Checking package " + packageName);
16084            }
16085            boolean keep = false;
16086            for (int i = 0; i < users.length; i++) {
16087                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16088                    keep = true;
16089                    if (DEBUG_CLEAN_APKS) {
16090                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16091                                + users[i]);
16092                    }
16093                    break;
16094                }
16095            }
16096            if (!keep) {
16097                if (DEBUG_CLEAN_APKS) {
16098                    Slog.i(TAG, "  Removing package " + packageName);
16099                }
16100                mHandler.post(new Runnable() {
16101                    public void run() {
16102                        deletePackageX(packageName, userHandle, 0);
16103                    } //end run
16104                });
16105            }
16106        }
16107    }
16108
16109    /** Called by UserManagerService */
16110    void createNewUserLILPw(int userHandle) {
16111        if (mInstaller != null) {
16112            mInstaller.createUserConfig(userHandle);
16113            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16114            applyFactoryDefaultBrowserLPw(userHandle);
16115            primeDomainVerificationsLPw(userHandle);
16116        }
16117    }
16118
16119    void newUserCreated(final int userHandle) {
16120        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16121    }
16122
16123    @Override
16124    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16125        mContext.enforceCallingOrSelfPermission(
16126                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16127                "Only package verification agents can read the verifier device identity");
16128
16129        synchronized (mPackages) {
16130            return mSettings.getVerifierDeviceIdentityLPw();
16131        }
16132    }
16133
16134    @Override
16135    public void setPermissionEnforced(String permission, boolean enforced) {
16136        // TODO: Now that we no longer change GID for storage, this should to away.
16137        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16138                "setPermissionEnforced");
16139        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16140            synchronized (mPackages) {
16141                if (mSettings.mReadExternalStorageEnforced == null
16142                        || mSettings.mReadExternalStorageEnforced != enforced) {
16143                    mSettings.mReadExternalStorageEnforced = enforced;
16144                    mSettings.writeLPr();
16145                }
16146            }
16147            // kill any non-foreground processes so we restart them and
16148            // grant/revoke the GID.
16149            final IActivityManager am = ActivityManagerNative.getDefault();
16150            if (am != null) {
16151                final long token = Binder.clearCallingIdentity();
16152                try {
16153                    am.killProcessesBelowForeground("setPermissionEnforcement");
16154                } catch (RemoteException e) {
16155                } finally {
16156                    Binder.restoreCallingIdentity(token);
16157                }
16158            }
16159        } else {
16160            throw new IllegalArgumentException("No selective enforcement for " + permission);
16161        }
16162    }
16163
16164    @Override
16165    @Deprecated
16166    public boolean isPermissionEnforced(String permission) {
16167        return true;
16168    }
16169
16170    @Override
16171    public boolean isStorageLow() {
16172        final long token = Binder.clearCallingIdentity();
16173        try {
16174            final DeviceStorageMonitorInternal
16175                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16176            if (dsm != null) {
16177                return dsm.isMemoryLow();
16178            } else {
16179                return false;
16180            }
16181        } finally {
16182            Binder.restoreCallingIdentity(token);
16183        }
16184    }
16185
16186    @Override
16187    public IPackageInstaller getPackageInstaller() {
16188        return mInstallerService;
16189    }
16190
16191    private boolean userNeedsBadging(int userId) {
16192        int index = mUserNeedsBadging.indexOfKey(userId);
16193        if (index < 0) {
16194            final UserInfo userInfo;
16195            final long token = Binder.clearCallingIdentity();
16196            try {
16197                userInfo = sUserManager.getUserInfo(userId);
16198            } finally {
16199                Binder.restoreCallingIdentity(token);
16200            }
16201            final boolean b;
16202            if (userInfo != null && userInfo.isManagedProfile()) {
16203                b = true;
16204            } else {
16205                b = false;
16206            }
16207            mUserNeedsBadging.put(userId, b);
16208            return b;
16209        }
16210        return mUserNeedsBadging.valueAt(index);
16211    }
16212
16213    @Override
16214    public KeySet getKeySetByAlias(String packageName, String alias) {
16215        if (packageName == null || alias == null) {
16216            return null;
16217        }
16218        synchronized(mPackages) {
16219            final PackageParser.Package pkg = mPackages.get(packageName);
16220            if (pkg == null) {
16221                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16222                throw new IllegalArgumentException("Unknown package: " + packageName);
16223            }
16224            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16225            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16226        }
16227    }
16228
16229    @Override
16230    public KeySet getSigningKeySet(String packageName) {
16231        if (packageName == null) {
16232            return null;
16233        }
16234        synchronized(mPackages) {
16235            final PackageParser.Package pkg = mPackages.get(packageName);
16236            if (pkg == null) {
16237                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16238                throw new IllegalArgumentException("Unknown package: " + packageName);
16239            }
16240            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16241                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16242                throw new SecurityException("May not access signing KeySet of other apps.");
16243            }
16244            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16245            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16246        }
16247    }
16248
16249    @Override
16250    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16251        if (packageName == null || ks == null) {
16252            return false;
16253        }
16254        synchronized(mPackages) {
16255            final PackageParser.Package pkg = mPackages.get(packageName);
16256            if (pkg == null) {
16257                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16258                throw new IllegalArgumentException("Unknown package: " + packageName);
16259            }
16260            IBinder ksh = ks.getToken();
16261            if (ksh instanceof KeySetHandle) {
16262                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16263                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16264            }
16265            return false;
16266        }
16267    }
16268
16269    @Override
16270    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16271        if (packageName == null || ks == null) {
16272            return false;
16273        }
16274        synchronized(mPackages) {
16275            final PackageParser.Package pkg = mPackages.get(packageName);
16276            if (pkg == null) {
16277                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16278                throw new IllegalArgumentException("Unknown package: " + packageName);
16279            }
16280            IBinder ksh = ks.getToken();
16281            if (ksh instanceof KeySetHandle) {
16282                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16283                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16284            }
16285            return false;
16286        }
16287    }
16288
16289    public void getUsageStatsIfNoPackageUsageInfo() {
16290        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16291            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16292            if (usm == null) {
16293                throw new IllegalStateException("UsageStatsManager must be initialized");
16294            }
16295            long now = System.currentTimeMillis();
16296            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16297            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16298                String packageName = entry.getKey();
16299                PackageParser.Package pkg = mPackages.get(packageName);
16300                if (pkg == null) {
16301                    continue;
16302                }
16303                UsageStats usage = entry.getValue();
16304                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16305                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16306            }
16307        }
16308    }
16309
16310    /**
16311     * Check and throw if the given before/after packages would be considered a
16312     * downgrade.
16313     */
16314    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16315            throws PackageManagerException {
16316        if (after.versionCode < before.mVersionCode) {
16317            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16318                    "Update version code " + after.versionCode + " is older than current "
16319                    + before.mVersionCode);
16320        } else if (after.versionCode == before.mVersionCode) {
16321            if (after.baseRevisionCode < before.baseRevisionCode) {
16322                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16323                        "Update base revision code " + after.baseRevisionCode
16324                        + " is older than current " + before.baseRevisionCode);
16325            }
16326
16327            if (!ArrayUtils.isEmpty(after.splitNames)) {
16328                for (int i = 0; i < after.splitNames.length; i++) {
16329                    final String splitName = after.splitNames[i];
16330                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16331                    if (j != -1) {
16332                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16333                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16334                                    "Update split " + splitName + " revision code "
16335                                    + after.splitRevisionCodes[i] + " is older than current "
16336                                    + before.splitRevisionCodes[j]);
16337                        }
16338                    }
16339                }
16340            }
16341        }
16342    }
16343
16344    private static class MoveCallbacks extends Handler {
16345        private static final int MSG_CREATED = 1;
16346        private static final int MSG_STATUS_CHANGED = 2;
16347
16348        private final RemoteCallbackList<IPackageMoveObserver>
16349                mCallbacks = new RemoteCallbackList<>();
16350
16351        private final SparseIntArray mLastStatus = new SparseIntArray();
16352
16353        public MoveCallbacks(Looper looper) {
16354            super(looper);
16355        }
16356
16357        public void register(IPackageMoveObserver callback) {
16358            mCallbacks.register(callback);
16359        }
16360
16361        public void unregister(IPackageMoveObserver callback) {
16362            mCallbacks.unregister(callback);
16363        }
16364
16365        @Override
16366        public void handleMessage(Message msg) {
16367            final SomeArgs args = (SomeArgs) msg.obj;
16368            final int n = mCallbacks.beginBroadcast();
16369            for (int i = 0; i < n; i++) {
16370                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16371                try {
16372                    invokeCallback(callback, msg.what, args);
16373                } catch (RemoteException ignored) {
16374                }
16375            }
16376            mCallbacks.finishBroadcast();
16377            args.recycle();
16378        }
16379
16380        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16381                throws RemoteException {
16382            switch (what) {
16383                case MSG_CREATED: {
16384                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16385                    break;
16386                }
16387                case MSG_STATUS_CHANGED: {
16388                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16389                    break;
16390                }
16391            }
16392        }
16393
16394        private void notifyCreated(int moveId, Bundle extras) {
16395            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16396
16397            final SomeArgs args = SomeArgs.obtain();
16398            args.argi1 = moveId;
16399            args.arg2 = extras;
16400            obtainMessage(MSG_CREATED, args).sendToTarget();
16401        }
16402
16403        private void notifyStatusChanged(int moveId, int status) {
16404            notifyStatusChanged(moveId, status, -1);
16405        }
16406
16407        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16408            Slog.v(TAG, "Move " + moveId + " status " + status);
16409
16410            final SomeArgs args = SomeArgs.obtain();
16411            args.argi1 = moveId;
16412            args.argi2 = status;
16413            args.arg3 = estMillis;
16414            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16415
16416            synchronized (mLastStatus) {
16417                mLastStatus.put(moveId, status);
16418            }
16419        }
16420    }
16421
16422    private final class OnPermissionChangeListeners extends Handler {
16423        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16424
16425        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16426                new RemoteCallbackList<>();
16427
16428        public OnPermissionChangeListeners(Looper looper) {
16429            super(looper);
16430        }
16431
16432        @Override
16433        public void handleMessage(Message msg) {
16434            switch (msg.what) {
16435                case MSG_ON_PERMISSIONS_CHANGED: {
16436                    final int uid = msg.arg1;
16437                    handleOnPermissionsChanged(uid);
16438                } break;
16439            }
16440        }
16441
16442        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16443            mPermissionListeners.register(listener);
16444
16445        }
16446
16447        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16448            mPermissionListeners.unregister(listener);
16449        }
16450
16451        public void onPermissionsChanged(int uid) {
16452            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16453                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16454            }
16455        }
16456
16457        private void handleOnPermissionsChanged(int uid) {
16458            final int count = mPermissionListeners.beginBroadcast();
16459            try {
16460                for (int i = 0; i < count; i++) {
16461                    IOnPermissionsChangeListener callback = mPermissionListeners
16462                            .getBroadcastItem(i);
16463                    try {
16464                        callback.onPermissionsChanged(uid);
16465                    } catch (RemoteException e) {
16466                        Log.e(TAG, "Permission listener is dead", e);
16467                    }
16468                }
16469            } finally {
16470                mPermissionListeners.finishBroadcast();
16471            }
16472        }
16473    }
16474
16475    private class PackageManagerInternalImpl extends PackageManagerInternal {
16476        @Override
16477        public void setLocationPackagesProvider(PackagesProvider provider) {
16478            synchronized (mPackages) {
16479                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16480            }
16481        }
16482
16483        @Override
16484        public void setImePackagesProvider(PackagesProvider provider) {
16485            synchronized (mPackages) {
16486                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16487            }
16488        }
16489
16490        @Override
16491        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16492            synchronized (mPackages) {
16493                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16494            }
16495        }
16496
16497        @Override
16498        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16499            synchronized (mPackages) {
16500                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16501            }
16502        }
16503
16504        @Override
16505        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16506            synchronized (mPackages) {
16507                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16508            }
16509        }
16510
16511        @Override
16512        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16513            synchronized (mPackages) {
16514                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16515            }
16516        }
16517
16518        @Override
16519        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16520            synchronized (mPackages) {
16521                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16522                        packageName, userId);
16523            }
16524        }
16525
16526        @Override
16527        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16528            synchronized (mPackages) {
16529                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16530                        packageName, userId);
16531            }
16532        }
16533    }
16534
16535    @Override
16536    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16537        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16538        synchronized (mPackages) {
16539            final long identity = Binder.clearCallingIdentity();
16540            try {
16541                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16542                        packageNames, userId);
16543            } finally {
16544                Binder.restoreCallingIdentity(identity);
16545            }
16546        }
16547    }
16548
16549    private static void enforceSystemOrPhoneCaller(String tag) {
16550        int callingUid = Binder.getCallingUid();
16551        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16552            throw new SecurityException(
16553                    "Cannot call " + tag + " from UID " + callingUid);
16554        }
16555    }
16556}
16557